【问题标题】:Sending an Gmail by OAuth 2.0 Playground通过 OAuth 2.0 Playground 发送 Gmail
【发布时间】:2019-07-13 05:52:21
【问题描述】:

我已经编写了通过 OAuth2 将邮件从我的 gmail 帐户发送到另一个帐户的代码。在OAuth2中,我们需要在https://developers.google.com/oauthplayground/上生成一个refreshToken和accessToken,这个生成的accessToken会在3600秒后过期。我想要一些会生成 accessToken 的代码。

我已经编写了代码,我直接从该站点 https://developers.google.com/oauthplayground/ 放置 refreshToken 和 accessToken 。

//javascript代码主文件app.js

async function sendEmail() {
    const nodemailer = require("nodemailer");
    const { google } = require("googleapis");
    const OAuth2 = google.auth.OAuth2;

    const smtpTransport = nodemailer.createTransport({
        service: "gmail",
        auth: {
            type: "OAuth2",
            user: "***************@gmail.com", 
            clientId: "***********.apps.googleusercontent.com",
            clientSecret: "*************",
            refreshToken: "**************",
            accessToken: "********************************"
        }
    });

    const mailOptions = {
        from: "**************@gmail.com",
        to: "**************@gmail.com",
        subject: "Hello",
        generateTextFromHTML: true,
        html: "<h1>TEST MAIL SAYS HELLO</h1>"
    };
       smtpTransport.sendMail(mailOptions, (error, response) => {
         error ? console.log(error) : console.log(response);
         smtpTransport.close();
        });
     } 
 sendEmail();

这工作正常,但我希望使用一些代码生成 accessToken。

【问题讨论】:

  • 如果您使用的是网络应用程序,请查看this
  • 谢谢你 Jescnallas,但我想要这个用于服务器端 Web 应用程序,我已经阅读了文档,但没有找到解决方案。
  • 您是否尝试过遵循文档中的 4 个步骤?您能否在帖子中分享您对 oauth 令牌的尝试?

标签: node.js gmail nodemailer oauth2-playground


【解决方案1】:

为了获取访问令牌和刷新令牌,您需要在应用中的某个时间点输入您的凭据。这将需要某种前端部分。在后端,您将使用 googleapis 节点库中的 auth 包来获取这些凭据并生成您需要的令牌。

另一种方法是创建一个服务帐户,该帐户将代表您的帐户发送电子邮件。您想要什么流程,任何人都可以使用 Gmail 发送电子邮件,还是您自己?

【讨论】:

  • 我想向第一次访问我网站的人发送一封 gmail 感谢信息。为此,我想先尝试发送简单的消息。帮助我发送关于在 nodejs 上编写服务器端代码的 gmail 消息。谢谢
猜你喜欢
  • 2021-03-07
  • 1970-01-01
  • 2014-12-31
  • 2020-04-11
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
  • 2022-06-10
  • 2011-03-08
相关资源
最近更新 更多