首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Nodemailer进行现代Oauth2邮件认证

使用Nodemailer进行现代Oauth2邮件认证
EN

Stack Overflow用户
提问于 2019-10-10 11:42:37
回答 3查看 4.1K关注 0票数 6

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

代码语言:javascript
运行
复制
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);
            });

我开始收到这个错误:

错误:登录无效: 535 5.7.3身份验证失败的SN4PR0601CA0002.namprd06.prod.outlook.com

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

我需要实现现代身份验证(Oauth2),以便能够使用outlook通过nodemailer发送邮件。

有人知道这件事吗?需要哪些配置(代码)更改?

EN

Stack Overflow用户

发布于 2022-05-07 10:54:41

在很长一段时间内发现如何使用OAuth2从服务器发送电子邮件后,我最后给出了这个工作示例。

  1. 创建一个应用程序https://go.microsoft.com/fwlink/?linkid=2083908
  2. 在{您的应用程序管理面板}> API权限>添加权限> Microsoft图形>应用程序权限> Mail.Send >添加权限中添加权限
  3. 创建证书以获取客户端机密{您的应用程序管理面板}>证书&机密>客户端机密>新客户端秘密(将“值”字符串保存在某个地方--这是您的client_secret)
  4. 确保已安装了所需的节点应用程序。
  5. 现在您可以运行以下代码从服务器发送任何电子邮件:
代码语言:javascript
运行
复制
    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://learn.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0&tabs=javascript

可能会对某人有帮助;)

票数 8
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58322118

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档