【问题标题】:Email body is sent in a file [Gmail API, Node.js]电子邮件正文在文件中发送 [Gmail API, Node.js]
【发布时间】:2021-06-03 05:09:30
【问题描述】:

我尝试使用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,不明白我的代码有什么问题。

【问题讨论】:

    标签: node.js google-cloud-platform gmail-api


    【解决方案1】:

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

    发件人:

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

    收件人:

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

    注意:

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

    【讨论】:

      猜你喜欢
      • 2021-09-11
      • 2019-09-22
      • 2014-10-30
      • 2020-05-07
      • 2018-01-26
      • 2017-10-28
      • 2013-01-31
      • 2017-03-07
      • 2018-07-28
      相关资源
      最近更新 更多