【发布时间】: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