我正在尝试使用之前经过 SES 身份验证的帐户从 Lambda 发送电子邮件;使用 Nodemailer 与 Node.js 一起使用。没有错误,但也没有发送。
这是我正在使用的过程:
module.exports.eviarCorreoPrueba = (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
console.log('inicia envio de correos');
var transporter = nodemailer.createTransport({
//pool: true,
host: 'email-smtp.us-east-1.amazonaws.com',
port: 465,
secure: true,
auth: {
user: 'user',
pass: 'pass'
}
});
console.log('se crea transporte ');
var mailOptions = {
from: 'test@email.com',
to: 'test@email.com',
subject: 'Prueba Lambda',
html: 'hello World'
};
console.log('se asignan las opciones de correo');
console.log('inicia envio de correo');
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
callback(null, {
statusCode: 200,
body: JSON.stringify({
input: 'not send'
})
})
} else {
console.log('Email sent');
}
});
console.log('funcion finalizada');
};
这些是日志答案结果:
最佳答案
以防万一有人遇到“nodemailer 无法在 Lambda 中工作”问题:
您帖子中的代码可以在本地服务器上运行,因为:
在您的本地环境中,有一个正在运行的服务器来调度所有调用堆栈,包括同步和异步任务。一旦您在本地环境中调用了transporter.sendMail(),它将被放置到当前调用堆栈的末尾并一直执行,直到调用堆栈中的最后一个执行完成。在您的情况下,异步函数 transporter.sendMail()
将安排在 console.log('funcion Finalizada');
为什么它在 Lambda 中不起作用:
每次调用lambda函数时,它都会执行代码,然后在执行完成后杀死进程,这意味着它将无法调用异步transporter.sendMail()
因为在 console.log('funcion Finalizada');
之后,lambda 函数进程将被终止,并且计划的异步任务将在执行之前被清除。
要使其在 Lambda 中运行:
1) 将您的函数更改为异步
函数
module.exports.eviarCorreoPrueba = async (event, context) => { ... }
2) 在继续之前等待您的 transporter.sendMail()
被调用
const response = await new Promise((rsv, rjt) => {
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
return rjt(error)
}
rsv('Email sent');
});
});
return {
statusCode: 200,
body: JSON.stringify({
input: response
})
}
3)让你的nodemailer电子邮件机器人工作的最后一件事: 您需要转Less secure app access和 Allow access to your Google Account因为您只是使用用户名和密码来连接您的 Gmail 帐户。
*注意:如果您想使用更安全的方法连接您的 Gmail(例如 OAuth 2.0),您可以引用我的文章:Create a Free Serverless Contact Form Using Gmail, Nodemailer, and AWS Lambda
希望这可以帮助任何遇到此问题的人。
干杯,
关于node.js - 使用 Lambda、NodeJs 和 Nodemailer 发送电子邮件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54296952/