oauth-2.0 如何发送电子邮件与谷歌使用nodemailer后,谷歌禁用不太确定的应用程序选项?

rjjhvcjd  于 2022-10-31  发布在  其他
关注(0)|答案(2)|浏览(289)

我想找到一种方法,从我的应用程序使用nodemailer发送电子邮件给用户,无论是某种谷歌身份验证或任何其他方式。下面提到的工作代码已停止工作后,谷歌已禁用不太安全的应用程序选项。

  1. const nodemailer = require('nodemailer')
  2. const sendEmail = async options => {
  3. const transporter = nodemailer.createTransport({
  4. // host: "smtp.gmail.com",
  5. // port: "465",
  6. // secure: true,
  7. service:'gmail',
  8. auth: {
  9. user: "USER_EMAIL",
  10. pass: "USER_PASSWORD"
  11. },
  12. tls:{rejectUnauthorized:false}
  13. })
  14. const message = {
  15. from: `${process.env.FROM_NAME} <${process.env.FROM_EMAIL}>`,
  16. to: options.email,
  17. subject: options.subject,
  18. text: options.message,
  19. html: options.message,
  20. attachments: [
  21. {
  22. filename: '.png',
  23. path: __dirname + '.png',
  24. cid: '.png'
  25. }
  26. ]
  27. }
  28. const info = await transporter.sendMail(message)
  29. console.log('Message sent : %s', info.messageId)
  30. console.log(__dirname)
  31. }
  32. module.exports = sendEmail
nhaq1z21

nhaq1z211#

在写这篇文章的时候,谷歌已经不再支持Less Secure Apps了,而且你也不能使用你的谷歌账户密码。
你得生成一个新的应用密码。
应用程序密码仅在两步验证打开时有效。请按照以下步骤获取应用程序密码
1.转到https://myaccount.google.com/security
1.启用2FA
1.创建电子邮件的应用程序密码
1.将该密码(16个字符)复制到Nodemailer auth中的pass参数中。

  1. const client = nodemailer.createTransport({
  2. service: "Gmail",
  3. auth: {
  4. user: "username@gmail.com",
  5. pass: "Google-App-Password-Without-Spaces"
  6. }
  7. });
  8. client.sendMail(
  9. {
  10. from: "sender",
  11. to: "recipient",
  12. subject: "Sending it from Heroku",
  13. text: "Hey, I'm being sent from the cloud"
  14. }
  15. )
展开查看全部
rks48beu

rks48beu2#

您应该检查一下Xoauth2
Nodmailer支持多种Oauth类型

  1. let transporter = nodemailer.createTransport({
  2. host: "smtp.gmail.com",
  3. port: 465,
  4. secure: true,
  5. auth: {
  6. type: "OAuth2",
  7. user: "user@example.com",
  8. clientId: "000000000000-xxx0.apps.googleusercontent.com",
  9. clientSecret: "XxxxxXXxX0xxxxxxxx0XXxX0",
  10. refreshToken: "1/XXxXxsss-xxxXXXXXxXxx0XXXxxXXx0x00xxx",
  11. accessToken: "ya29.Xx_XX0xxxxx-xX0X0XxXXxXxXXXxX0x",
  12. expires: 1484314697598,
  13. },
  14. });

相关问题