我有一个 AWS Lambda 函数:
发送邮件.js
const AWS = require('aws-sdk');
const ses = new AWS.SES();
function sendEmail(subject, message, senderEmail) {
const params = {
Destination: {
ToAddresses: [
process.env.VERIFIED_EMAIL
]
},
Message: {
Body: {
Text: {
Data: message,
Charset: 'UTF-8'
}
},
Subject: {
Data: subject,
Charset: 'UTF-8'
}
},
Source: process.env.VERIFIED_EMAIL,
ReplyToAddresses: [senderEmail]
}
return ses.sendEmail(params).promise();
}
module.exports = sendEmail;
来自
index.js
const sendEmail = require('./sendEmail');
exports.handler = async (event, context) => {
return sendEmail(event.subject, event.message, event.email).then((response) => { context.done(null, 'Email sent')});
};
我有环境。变量 VERIFIED_EMAIL 设置为由 AWS/SES 验证的个人电子邮件。
我的测试用例:
{
"email": "[email protected]",
"subject": "desc",
"message": "Hello!"
}
通过并返回“电子邮件已发送”,但我实际上没有收到电子邮件。我还部署了 API-GATEWAY,我可以使用 Postman 调用 API,我收到相同的“电子邮件已发送”消息,但实际上没有发送任何电子邮件。
我认为处于沙盒模式应该不是问题,因为我发送的电子邮件已经过验证。
附:
当查看 SES 管理控制台时,它说正在发送电子邮件(它们占用了每日 200 封配额的一部分),然后它们都没有被退回或拒绝,只是简单地发送。
在深入研究之前,您应该通过 SES 检查一些事项。
在沙盒模式下,“源电子邮件地址”和“目标电子邮件地址”都必须被验证。相反,邮件不会被送达。
如果您验证电子邮件域,则必须在您的域中添加适当的 dns 和 DKIM 记录。如果您使用公司域,还需要额外的白名单许可。
您的 IAM AWS 用户应该被允许执行 SES api 调用。检查您的策略和角色。检查您使用的 Secret Key 和 Secret Id。
当您使用不适当的电子邮件类型和电子邮件发送端点时可能会出现问题(例如,您尝试通过“BulkTemplatedMessage”端点发送“SingleTemplatedMessage”)
首先检查所有这些东西。
那你可以试试别的。在我的项目中我们使用基于java的AWS SDK在BE和SES之间进行交互。它提供包含消息状态的日志(如果消息发送成功、被拒绝、其 ID 和其他错误)
此外,要跟踪您发送的每条消息,您可以设置 SES-SNS 以与通知交换。它在下面的文章中描述
https://sysgears.com/articles/how-to-track-email-status-with-amazon-ses-and-amazon-sns/
您的邮件客户端可能会出现其他问题(垃圾邮件过滤器等)
按照清单对 SES 电子邮件发送进行故障排除:
额外检查
如果您发送带有模板的电子邮件(即使这不直接适用于问题的代码)如果有一些错误,它不会警告您或给出任何错误。我发现非常有用的是在发送模板之前检查模板的格式是否正确。为此你可以使用这样的东西:
import { SESv2Client, SendEmailCommand, TestRenderEmailTemplateCommand } from "@aws-sdk/client-sesv2";
/**
* Used to discover potential issues with the templates before sending them
* @param templateName the name of the template to render
* @param templateData the data to replace tags in the template
*/
async function testRenderEmailTemplate(templateName, templateData) {
const command = new TestRenderEmailTemplateCommand({
TemplateName: templateName,
TemplateData: JSON.stringify(templateData),
});
const response = await client.send(command);
return response;
}
async function sendEmail(
templateName,
templateData,
recipient,
) {
const templateIsValid = await testRenderEmailTemplate(templateName, templateData); // this will fail and the error will show you what's wrong with your template
const command = new SendEmailCommand({
ReplyToAddresses: ["[email protected]],
Destination: {
ToAddresses: [recipient],
},
Content: {
Template: {
TemplateName: templateName,
TemplateData: JSON.stringify(templateData),
},
},
FromEmailAddress: "[email protected]",
});
const response = await client.send(command);
return response.$metadata.httpStatusCode === 200;
}