使用 Nodemailer nodejs 发送邮件的现代 Oauth2 身份验证

Modern Oauth2 authentication for sending mails using Nodemailer nodejs

我正在使用 nodemailer 在我的 nodejs 应用程序中发送电子邮件。

var payload = { auth: 
               {
                user: smtpuser,
                pass: smtppass
               },
                to : toAddr,
                from  : emailfrom,
                cc : ccAddr,
                subject : subject,
                html    : content,
                attachments: attachments
              };

var transporter = nodemailer.createTransport(
                   { host: payload.host || 'smtp.office365.com', // Office 365 server
                     port: payload.port || 587,     // secure SMTP
                     secure:payload.secure || false, // false for TLS - as a boolean not string - but the default is false so just remove this completely
                     auth: payload.auth,
                     debug: true,
                     tls: payload.tls || {ciphers: 'SSLv3'}
                   });

transporter.sendMail(payload, function (error, info) {
                if (error) {
                    return console.log(error);
                }
                updateMessage(updatedMsg);
            });

我开始收到此错误:

Error: Invalid log in: 535 5.7.3 Authentication unsuccessful [SN4PR0601CA0002.namprd06.prod.outlook.com]

看来我的团队现在已经禁用了基本身份验证。

我需要实施现代身份验证 (Oauth2) 才能使用 outlook id 通过 nodemailer 发送邮件。

有人对此有任何想法吗? 需要进行哪些配置(代码)更改?

我建议您使用 Microsoft Graph 发送电子邮件。有一个易于使用的 REST API,它与 OAuth 配合得很好。

请在下面找到一些链接,以帮助您快速构建它。

https://docs.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0&tabs=http https://docs.microsoft.com/en-us/graph/auth/auth-concepts?view=graph-rest-1.0 https://docs.microsoft.com/en-us/graph/tutorials/node?view=graph-rest-1.0

经过长时间探索如何使用 OAuth2 从您的服务器发送电子邮件,我最终得到了这个工作示例。

  1. 创建应用程序https://go.microsoft.com/fwlink/?linkid=2083908
  2. 在{您的应用程序管理面板}中添加权限 > API 权限 > 添加权限 > Microsoft Graph > 应用程序权限 > Mail.Send > 添加权限
  3. 创建证书以获取客户端密码 {您的 APP 管理面板} > 证书和密码 > 客户端密码 > 新客户端密码(将“值”字符串保存在您的 client_secret)
  4. 确保您已安装所需的节点应用程序
  5. 现在您可以运行此代码从您的服务器发送任何电子邮件:
    const msal = require('@azure/msal-node');
    const fetch = require('node-fetch');

    const clientSecret = process.env.CLIENT_SECRET;
    const clientId = process.env.CLIENT_ID;
    const tenantId = process.env.TENANT_ID;
    const aadEndpoint =
      process.env.AAD_ENDPOINT || 'https://login.microsoftonline.com';
    const graphEndpoint =
      process.env.GRAPH_ENDPOINT || 'https://graph.microsoft.com';

    const msalConfig = {
      auth: {
        clientId,
        clientSecret,
        authority: aadEndpoint + '/' + tenantId,
      },
    };

    const tokenRequest = {
      scopes: [graphEndpoint + '/.default'],
    };

    const cca = new msal.ConfidentialClientApplication(msalConfig);
    const tokenInfo = await cca.acquireTokenByClientCredential(tokenRequest);

    const mail = {
      subject: 'Microsoft Graph JavaScript Sample',
      //This "from" is optional if you want to send from group email. For this you need to give permissions in that group to send emails from it.
      from: {
        emailAddress: {
          address: 'noreply@company.com',
        },
      },
      toRecipients: [
        {
          emailAddress: {
            address: 'someemail@domain.com',
          },
        },
      ],
      body: {
        content:
          '<h1>MicrosoftGraph JavaScript Sample</h1>This is the email body',
        contentType: 'html',
      },
    };

    const headers = new fetch.Headers();
    const bearer = `Bearer ${tokenInfo.accessToken}`;

    headers.append('Authorization', bearer);
    headers.append('Content-Type', 'application/json');

    const options = {
      method: 'POST',
      headers,
      body: JSON.stringify({ message: mail, saveToSentItems: false }),
    };

    await fetch(
      graphEndpoint + '/v1.0/users/youroutlookemail@company.com/sendMail',
      options
    );

也可以在这里查看电子邮件设置:

https://docs.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0&tabs=javascript

可能会对某人有所帮助 ;)