我一直在尝试使用 Gmail API 创建一个托管在 AWS Lambda 上的简单邮件程序 API。
我正在使用 `aws-lambda-multipart-parser` 解析多部分/表单数据。我使用 Nodemailer 的 Mailcomposer 创建了邮件正文。
当我发送邮件时,附件文件显示已损坏,我无法打开它们。
import multipart from 'aws-lambda-multipart-parser'
import MailComposer from 'nodemailer/lib/mail-composer';
import { JWT } from "google-auth-library"
import { google } from 'googleapis'
import privatekey from './../../gw-mailer/gw_mailer_service_keys.json' // This was downloaded when you created your Service Account Key
const scopes = ['https://www.googleapis.com/auth/gmail.send'];
export const handler = async (event, context) => {
// console.log(event.body)
const body = multipart.parse(event, false);
// const body = await parser.parse(event);
const file = [{
filename: body.attachments.filename,
content: body.attachments.content,
contentType: body.attachments.contentType,
}]
console.log(file)
const mail = new MailComposer({
from: '[email protected]',
to: '[email protected]',
subject: 'Test',
text: 'Test message',
attachments: file
})
const message = await mail.compile().build()
// console.log(message)
sendMail(message)
return {
statusCode: 200,
body: JSON.stringify(body)
}
}
const sendMail = async (message) => {
const jwtClient = new JWT({
email: privatekey.client_email,
key: privatekey.private_key,
scopes,
subject: '[email protected]',
});
const gmail = google.gmail({ version: 'v1', auth: jwtClient });
const res = await gmail.users.messages.send({
userId: 'me',
requestBody: {
raw: Buffer.from(message).toString('base64')
}
});
}
我哪里出错了?
我尝试过使用编码和 mimetypes,但似乎没有任何效果。
如果您的附件是 URL 照片,则仅使用路径和 cid。不要使用或指定文件名,这是经过惨痛教训才知道的。
当我分配文件名时,照片附件将附加在电子邮件中,但不会显示图像。只会显示文件名,当我点击它时,它就像 23 字节,无法打开它。一旦我删除了代码中的文件名部分,它就开始像魅力一样工作。有道理