如何通过 Gmail API 在 JavaScript 中发送带有附件和消息的邮件

问题描述 投票:0回答:2

我可以发送附件,但无法发送附件和消息

当我添加消息发送时,失败了。

  function sendMessage(message, callback)
  {

    var email =
        "To: " + $('#compose-to').val() + "\r\n" +
        "Subject: " + $('#compose-subject').val() + "\r\n" +
        'Content-Transfer-Encoding: base64\r\n' +
        'Content-Type: text/html; charset="UTF-8"\r\n' +
        "" +
        message+
        "\r\n\r\n" +
        "--foo_bar_baz\r\n" +
        "Content-Type: image/png\r\n" +
        "MIME-Version: 1.0\r\n" +
        "Content-Disposition: attachment\r\n\r\n" +
        file_ + "\r\n\r\n";

    var sendRequest = gapi.client.gmail.users.messages.send({
      'userId': 'me',
      'resource': {
        'raw': window.btoa(unescape(encodeURIComponent(email))).replace(/\+/g, '-').replace(/\//g, '_')
      }
    });

    return sendRequest.execute(callback);
  }

希望通过 gmail api 在 javascript 中发送带有附件和消息的邮件

gmail gmail-api
2个回答
0
投票

发布答案用于文档目的。

根据文件上传文档,需要将

Content-Type
更改为
multipart/mixed
。大多数文件都需要此设置,因为这是 Gmail API 中添加附件的工作方式。


0
投票

我终于找到了同时发送短信和图片的解决方案!

首先,您必须按照这些步骤来创建连接gapi,但这不是主题

第二次您必须将附件转换为 Base64,在我的例子中,它是一个 url 图像(图像到 Base64

然后你必须编写这个语法(非常精确):

async function sendMessage1ereRelance(gmail) {
   const base64 = await imageUrlToBase64(urlToYourImage);
   const emailBody = 'Ceci est un body';
   const subject = 'Ceci est un test';
   const utf8Subject = `=?utf-8?B?${Buffer.from(subject).toString(
       'base64'
   )}?=`;

   const messageParts = [
       'To: [email protected]',
       'Subject: ' + utf8Subject,
       'MIME-Version: 1.0',
       'Content-Type: multipart/mixed; boundary="mixed_boundary"',
       '',
       `--mixed_boundary`,
       'Content-Type: multipart/alternative; boundary="alt_boundary"',
       '',
       `--alt_boundary`,
       `Content-Type: text/plain; charset="UTF-8"`,
       `Content-Transfer-Encoding: base64`,
       '',
       Buffer.from(emailBody).toString('base64'),
       `--alt_boundary`,
       'Content-Type: image/jpeg; name="image.png"',
       'Content-Disposition: attachment; filename="image.png"',
       'Content-Transfer-Encoding: base64',
       '',
       base64,
       `--alt_boundary--`,
       `--mixed_boundary--`,
    ];
    const message = messageParts.join('\r\n');

    // The body needs to be base64url encoded.
    const encodedMessage = Buffer.from(message)
       .toString('base64')
       .replace(/\+/g, '-')
       .replace(/\//g, '_')
       .replace(/=+$/, '');

   // Send the email with the attachment
   await gmail.users.messages.send({
       userId: 'me',
       requestBody: {
           raw: encodedMessage,
      },
   });

   console.log('Email with attachment sent successfully');
}

祝你有美好的一天

© www.soinside.com 2019 - 2024. All rights reserved.