电子邮件正文在文件 [Gmail API、Node.js] 中发送

Email body is sent in a file [Gmail API, Node.js]

我曾尝试使用 Gmail API Node.js Client,但电子邮件正文是在文件附件中发送的。其他一切正常(从、到、主题等)。

可以看到我的问题的原始代码here,但下面是我正在尝试做的一个更简单的例子:

import {google} from 'googleapis'

const accessToken = 'token created using google OAuth2 from googleapis package' // this is working properly, so I won't include the code here

async function sendMail(subject: string, text: string, to: string, from: string)
{
    const utf8Subject = `=?utf-8?B?${Buffer.from(subject).toString('base64')}?=`
    const messageParts =
    [
        `From: ${from}`,
        `To: ${to}`,
        'Content-Type: text/html charset=utf-8',
        'MIME-Version: 1.0',
        `Subject: ${utf8Subject}`,
        '',
        text,
    ]
  
    const message = messageParts.join('\n')
    const encodedMessage = Buffer.from(message)
        .toString('base64')
        .replace(/\+/g, '-')
        .replace(/\//g, '_')
        .replace(/=+$/, '')

  const gmail = google.gmail({version: 'v1', auth: accessToken})

  await gmail.users.messages.send(
  {
    userId: 'me',
    requestBody:
    {
      raw: encodedMessage,
    }
  })
}

sendMail('Some subject', 'Some text', 'to@example.com', 'from@example.com')

to 收到的电子邮件没有正文,text 变量不知何故变成了一个文件。使用 text/html 时,此文件的扩展名为 .html.

我试图找到像 Body:HTML: 这样的标签,但我找不到任何标签。查看official example,我不明白我的代码有什么问题。

我认为在你的header中,;需要用作Content-Typecharset之间的分隔符。我认为这可能是您遇到问题的原因。当你的脚本修改后,变成如下。

发件人:

'Content-Type: text/html charset=utf-8',

收件人:

'Content-Type: text/html; charset=utf-8',

注:

  • 在这个答案中,假设const gmail = google.gmail({version: 'v1', auth: accessToken})可以用来发送邮件。请注意这一点。