【问题标题】:Failed sending mail through google api with javascript使用javascript通过google api发送邮件失败
【发布时间】:2015-08-15 22:40:47
【问题描述】:

我正在尝试使用 JavaScript 通过 Google API 发送电子邮件。

我的问题是,当我尝试发送没有附件的简单邮件时,出现以下错误:

'raw' RFC822 有效负载消息字符串或通过 /upload/* URL 上传消息`

我的代码

function sendMessage() {
gapi.client.load('gmail', 'v1', function() {
    // Web-safe base64 
    var to = 'someone@someone.nl',
        subject = 'Hello World',
        content = 'send a Gmail.'

    var base64EncodedEmail = btoa(
          "Content-Type:  text/plain; charset=\"UTF-8\"\n" +
          "Content-length: 5000\n" +
          "Content-Transfer-Encoding: message/rfc2822\n" +
          "to: someone@someone.nl\n" +
          "from: \"test\" <test@gmail.com>\n" +
          "subject: Hello world\n\n" +

          "The actual message text goes here"
            ).replace(/\+/g, '-').replace(/\//g, '_');

    var mail= base64EncodedEmail;
    console.log(mail);
    var request = gapi.client.gmail.users.messages.send({
      'userId': "me",
      'message': {
          'raw': mail
        }
    });
    request.execute(function(response){
     console.log(response);
   });
  });        

}

【问题讨论】:

  • 您能解释一下为什么replace(/\+/g, '-').replace(/\//g, '_') ••• 将+ 替换为-/ 替换为_?还可以简化使用'(单引号)以避免转义"

标签: javascript email google-api google-api-client


【解决方案1】:

几天后,我自己找到了答案。问题是正文中的“消息”只能在您在电子邮件中发送附件时使用。

如果您没有附件,则查询看起来像我在这里写下的

var mail= base64EncodedEmail;
console.log(mail);
var request = gapi.client.gmail.users.messages.send({
  'userId': "me",
  'resource': {
      'raw': mail
    }
});
request.execute(function(response){
 console.log(response);
});

【讨论】:

  • 谢谢!我发现 drafts.createmessage.send 没有使用相同的语法是不一致的......
  • 这个有python版本吗?
  • Python 3.8: raw = base64.urlsafe_b64encode(message.as_bytes()).decode() gmail_api.users().messages().send(userId= "me", body = {'raw ': raw}).execute()
猜你喜欢
  • 2018-07-12
  • 2014-10-02
  • 2011-12-10
  • 2012-08-10
  • 1970-01-01
  • 2021-04-18
  • 2021-06-14
  • 2014-05-23
相关资源
最近更新 更多