我正在尝试发送带有附件的邮件。我已经使用SES服务发送简单的HTML内容邮件。但现在我想发送带有附件的邮件。
我正在使用Amazon SES服务发送电子邮件,并且正在使用'sendRawEmail'方法发送带有附件的邮件。
我收到这样的错误消息。InvalidParameterValue: Nested group
我没有找到任何有关此类错误的Node示例。
我在尝试使用NodeJS SES API发送电子邮件时感到非常沮丧。我发现了问题,并使用mailcomposer
npm软件包修复了该问题。现在,我可以发送带有附件的邮件了。
安装AWS开发工具包
npm i aws-sdk
现在安装manilcomposer
npm i mailcomposer
下面的完整代码
请求正文:如果要发送带有Base64内容的邮件。
{
email: ['jen****@gmail.com', 'Aa****@gmail.com'],
from: 'no-reply@*****.com',
subject: 'Sending emails with attachments',
text: 'please find attachments',
attachments: [{
filename: 'sample.pdf',
content: {{file}}, // file content base64 staring
encoding: 'base64',
}]
}
如果要发送带有文件路径的邮件。
{
email: ['jen****@gmail.com', 'Aa****@gmail.com'],
from: 'no-reply@*****.com',
subject: 'Sending emails with attachments',
text: 'please find attachments',
attachments: [{
filename: 'sample.pdf',
path: './home/sample,pdf'
}]
}
业务逻辑代码:
const ses = new AWS.SES({ region: 'us-east-1' }); //specify region for the particular see service.
const mailcomposer = require('mailcomposer');
exports.handler = function (event, context) {
console.log('Event: ',JSON.stringify(event));
if (!event.email) {
context.fail('Missing argument: email');
return;
}
if (!event.subject) {
context.fail('Missing argument: subject');
}
if (!event.from) {
context.fail('Missing argument: from');
}
if (!event.html && !event.text) {
context.fail('Missing argument: html|text');
}
const to = event.email;
const from = event.from;
const subject = event.subject;
const htmlBody = event.html;
const textBody = event.text;
const attachments = event.attachments;
const mailOptions = {
from: from,
subject: subject,
text: textBody,
html: htmlBody,
to: to,
attachments: attachments ? attachments : []
};
const mail = mailcomposer(mailOptions);
mail.build(function (err, message) {
const req = ses.sendRawEmail({ RawMessage: { Data: message } });
req.on('build', function () {
req.httpRequest.headers['Force-headers'] = '1';
});
req.send(function (err, data) {
if (err) {
console.log(err, err.stack);
context.fail('Internal Error: The email could not be sent.');
} else {
console.log(message);
console.log('The email was successfully sent')
context.succeed('The email was successfully sent');
}
});
});
};
if you have and any query regarding mailcomposer then check [here][1] this link below
[1]: https://nodemailer.com/extras/mailcomposer/