使用gmail javascript api从特定用户发送电子邮件

时间:2017-03-26 20:08:19

标签: javascript gmail-api

我希望从特定的Gmail帐户发送电子邮件(特别是输入到表单中的值),并且由于平台限制,我必须使用客户端(即javascript)代码来执行此操作。我正在测试以下代码,但似乎是使用我的个人 gmail凭据,而不是我试图指定的客户端ID。我做错了什么?

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Base64/1.0.0/base64.min.js"></script>
<script type="text/javascript">
  var CLIENT_ID = 'myclientid.apps.googleusercontent.com';
  var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"];
  var SCOPES = 'https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/gmail.send';
  function handleClientLoad() {
    gapi.load('client:auth2', initClient);
  }
  function initClient() {
    gapi.client.init({
      discoveryDocs: DISCOVERY_DOCS,
      clientId: CLIENT_ID,
      scope: SCOPES
    });
  }

  // ucs-2 string to base64 encoded ascii
  function utoa(str) {
    return window.btoa(unescape(encodeURIComponent(str)));
  }
  // base64 encoded ascii to ucs-2 string
  function atou(str) {
    return decodeURIComponent(escape(window.atob(str)));
  }

  function submitForm(form) {
    var formid = form.id.length>0 ? '('+form.id+') ' : '';
    var bodyText='The form '+formid+'was filled out on '+window.location.href+'\r\n'+
                 'The following values were submitted:';
    for (var i=0;i<form.childElementCount;i++) {
        bodyText += '\r\n'+'\r\n'+form[i].name+'\r\n'+form[i].value;
    }
    var unencodedEmail = 'To: '+form.attributes.getNamedItem('data-submit-to').value+
                         '\r\nSubject: A form '+formid+'was filled out on '+window.location.href+
                         '\r\n'+bodyText;
    try {
        var authInstance = gapi.auth2.getAuthInstance();
        authInstance.signIn({ client_id: CLIENT_ID });
        try {
            var base64EncodedEmail = utoa(unencodedEmail);
            var request = gapi.client.gmail.users.messages.send({
                'userId': 'me',
                'resource': {
                  'message': {
                    'raw': base64EncodedEmail
                  }
                }
              });
            request.execute(function() {/*do post email sending stuff*/});
        } finally {
            authInstance.signOut();
        }
    } finally { 
        return false;//prevent the form from redirecting
    }
  }
</script>

<script async defer src="https://apis.google.com/js/api.js"
  onload="this.onload=function(){};handleClientLoad()"
  onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>

1 个答案:

答案 0 :(得分:1)

您无法使用其他人的凭据,您需要使用自己的凭据。如果您按照Javascript Quickstart for Gmail进行操作,则会发现凭据来自您的Google邮件帐户。这就是我们有一个名为OAuth的东西的原因。如果谷歌允许这样做,这将被利用和恶意使用。