我在 Google 上创建了一个应用程序密码,也存储在 .env 文件中:
EMAIL_SERVICE=gmail
[email protected]
EMAIL_PASSWORD="xxxx yyyy zzzz cccc"
这是代码:
const sendEmailResetPassword = async (
email,
) => {
return new Promise((resolve, reject) => {
// Create a transporter object using Gmail SMTP transport
const transporter = nodemailer.createTransport({
service: process.env.EMAIL_SERVICE,
auth: {
user: process.env.EMAIL_USERNAME,
pass: process.env.EMAIL_PASSWORD,
},
});
// Define the email options
const mailOptions = {
from: process.env.EMAIL_USERNAME,
to: email,
subject: subject,
};
// Send the email
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log("Error occurred:", error.message);
reject(error);
} else {
resolve(info);
}
});
});
};
当我使用
npm run dev
在本地运行服务时,我没有收到任何错误,并且电子邮件已成功发送。
当我构建映像并运行 docker 容器时,它失败了,我知道 .env 被识别,因为我检查了使用
docker exec -it container env
它打印:
EMAIL_SERVICE=gmail
[email protected]
EMAIL_PASSWORD="xxxx yyyy zzzz cccc"
当我运行 docker 容器时发送时,我得到这个:
response: '535-5.7.8 Username and Password not accepted. For more information, go to\n' +
'535 5.7.8 https://support.google.com/mail/?p=BadCredentials fl25-20020a05600c0b9900b0040b3e26872dsm28169818wmb.8 - gsmtp',
responseCode: 535,
此外,其他 .env 变量也正在工作,例如 MySQL URL 等,因此 .env 变量可以被识别并且可以正常工作。
Google生成的密码是这样的:
"AAAA BBBB CCCC DDDD"
,我删除了空格,删除了括号,所以它看起来像这样:
AAAABBBBCCCCDDDD
并且成功了。