简体   繁体   English

如何使用 GMAIL API 从 Google Apps 脚本发送电子邮件?

[英]How to send the email from Google Apps Script using GMAIL API?

I am trying to automise sending of the Emails from my account using Gmail API in Google Apps Script.我正在尝试使用 Google Apps 脚本中的 Gmail API 自动从我的帐户发送电子邮件。

Here is my code:这是我的代码:

function email_checker() {
  var yourEmailAddress = "###@gmail.com";
  var myEmailAddress = "support@###.com";
  var subject = "testing mail";
  var forScope = GmailApp.getInboxUnreadCount();
  var htmlBody = '<html><body>' + '<h1>HI</h1>' + '</body></html>';

  var message = 'From: Me <' + myEmailAddress + '>\r\n' +
    'To: Me <' + myEmailAddress + '>\r\n' +
    'Subject: ' + subject + '\r\n' +
    'Content-Type: text/html; charset=utf-8\r\n' +
    'Content-Transfer-Encoding: quoted-printable\r\n\r\n' +
    htmlBody;

  var draftBody = Utilities.base64Encode(message);
  draftBody = draftBody.replace(/\//g, '_').replace(/\+/g, '-');

  var params = {
    method: "post",
    contentType: "application/json",
    headers: {
      "Authorization": "Bearer " + ScriptApp.getOAuthToken()
    },
    muteHttpExceptions: true,
    payload: JSON.stringify({
      "message": {
        "raw": draftBody
      }
    })
  };

  var resp = UrlFetchApp.fetch("https://gmail.googleapis.com/upload/gmail/v1/users/me/messages/send", params);
  Logger.log(resp.getContentText());
}

I am getting the following error: Media type 'application/json' is not supported.我收到以下错误:不支持媒体类型“应用程序/json”。

Can anyone please advise on what I am doing wrong?任何人都可以请教我做错了什么吗?

Thank you.谢谢你。

I believe your goal and your current situation as follows.我相信你的目标和你目前的情况如下。

  • You want to send an email using Gmail API with UrlFetchApp.您想使用 Gmail API 和 UrlFetchApp 发送电子邮件。
  • You have already done the settings for sending the email.您已经完成了发送电子邮件的设置。
    • Gmail API is enabled. Gmail API 已启用。
    • The scopes for sending emails can be included.可以包括发送电子邮件的范围。

Modification points:改装要点:

  • From your endtpoint, it is found that the media upload request is used.从您的端点,发现使用了媒体上传请求。
  • In this case,在这种情况下,
    • the request body is required to create with multipart/alternative .需要使用multipart/alternative创建请求正文。
    • It is not required to use the base64 encode with the web safe.网络安全不需要使用 base64 编码。
    • The content type is required to use message/rfc822 .使用message/rfc822需要内容类型。
    • The created request body can be directly used for payload .创建的请求体可以直接用于payload

When above points are reflected to your script, it becomes as follows.当以上几点反映到你的脚本中时,它变成如下。

Modified script:修改后的脚本:

function email_checker() {
  var yourEmailAddress = "###@gmail.com";
  var myEmailAddress = "support@###.com";
  var subject = "testing mail";
  var forScope = GmailApp.getInboxUnreadCount();
  var htmlBody = '<html><body>' + '<h1>HI</h1>' + '</body></html>';

  var message = 'MIME-Version: 1.0\r\n' +
    'From: Me <' + myEmailAddress + '>\r\n' +
    'To: Me <' + myEmailAddress + '>\r\n' +
    'Subject: ' + subject + '\r\n' +
    'Content-type: multipart/alternative; boundary=boundaryboundary\r\n\r\n' +
    '--boundaryboundary\r\n' +
    'Content-type: text/html; charset=UTF-8\r\n' +
    'Content-Transfer-Encoding: quoted-printable\r\n\r\n' +
    htmlBody + "\r\n\r\n" +
    '--boundaryboundary--';

  var params = {
    method: "post",
    contentType: "message/rfc822",
    headers: {
      "Authorization": "Bearer " + ScriptApp.getOAuthToken()
    },
    muteHttpExceptions: true,
    payload: message
  };

  var resp = UrlFetchApp.fetch("https://gmail.googleapis.com/upload/gmail/v1/users/me/messages/send", params);
  Logger.log(resp.getContentText());
}

Note:笔记:

  • If you want to use the endpoint of POST https://gmail.googleapis.com/gmail/v1/users/{userId}/messages/send , please modify your script as follows.如果您想使用POST https://gmail.googleapis.com/gmail/v1/users/{userId}/messages/send的端点,请按如下方式修改您的脚本。

    • From

       var params = { method: "post", contentType: "application/json", headers: { "Authorization": "Bearer " + ScriptApp.getOAuthToken() }, muteHttpExceptions: true, payload: JSON.stringify({ "message": { "raw": draftBody } }) }; var resp = UrlFetchApp.fetch("https://gmail.googleapis.com/upload/gmail/v1/users/me/messages/send", params); Logger.log(resp.getContentText());
    • To

       var params = { method: "post", contentType: "application/json", headers: { "Authorization": "Bearer " + ScriptApp.getOAuthToken() }, muteHttpExceptions: true, payload: JSON.stringify({"raw": draftBody}) }; var resp = UrlFetchApp.fetch("https://gmail.googleapis.com/gmail/v1/users/me/messages/send", params); Logger.log(resp.getContentText());
    • In this case, var draftBody = Utilities.base64Encode(message); draftBody = draftBody.replace(/\\//g, '_').replace(/\\+/g, '-');在这种情况下, var draftBody = Utilities.base64Encode(message); draftBody = draftBody.replace(/\\//g, '_').replace(/\\+/g, '-'); var draftBody = Utilities.base64Encode(message); draftBody = draftBody.replace(/\\//g, '_').replace(/\\+/g, '-'); can be also modified to var draftBody = Utilities.base64EncodeWebSafe(message);也可以修改为var draftBody = Utilities.base64EncodeWebSafe(message); . .

Reference:参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Google Apps 脚本中使用 GMail API 发送电子邮件 - Send email using GMail API in Google Apps Script 使用带有 Gmail API 的 Google Apps 脚本设置 email 签名 - Set email signature using Google Apps Script with Gmail API 如何通过 Gmail API 和 Google Apps 脚本请求和发送付款 - How to request and send payments via Gmail API and Google Apps Script 使用 Google Apps 脚本,您如何从电子邮件中删除内置的 Gmail 类别标签? - Using Google Apps Script, how do you remove built in Gmail category labels from an email? 如何通过Google Apps脚本发出Gmail API批处理请求? - How to make a Gmail API batch request from google apps script? 谷歌表格的应用程序脚本可以向非 Gmail 地址发送电子邮件吗? - Can apps script for google sheets send an email to a non Gmail address? 如何使用谷歌应用程序脚本发送草稿电子邮件 - How to send a draft email using google apps script 如何在 Google Apps 脚本中使用 MailApp 发送带有附件的 HTML email? - How to send a HTML email with attachment using MailApp in Google Apps Script? Google Apps Script - 如何从 Sheet 发送 HTML 电子邮件? - Google Apps Script - How to send HTML email from Sheet? Gmail / Google应用程序使用脚本/ api每小时/每天自动永久删除垃圾电子邮件 - Gmail /Google apps deleting trash email forever Hourly/Daily using script/api automatically
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM