如何使用 Nodemailer 触发通过我自己的 Gmail 帐户从我的网站向我自己的 NodeJS Gmail 帐户发送电子邮件?

How to trigger sending an email from my website via my own Gmail account to my own Gmail account in NodeJS, using Nodemailer?

我的情况是这样的:

const nm = require('nodemailer');
const {google} = require('googleapis');
const OAuth2 = google.auth.OAuth2;

const api = module.exports = {};

api.createTransporter = async () => {
    const client = new OAuth2(
        process.env.CLIENT_ID,
        process.env.CLIENT_SECRET,
        'https://developers.google.com/oauthplayground'
    );
    client.setCredentials({
        refresh_token: process.env.REFRESH_TOKEN
    });

    console.log(`Refresh token is: ${process.env.REFRESH_TOKEN}`);
    const accessToken = await new Promise((resolve, reject) => {
        client.getAccessToken((err, token) => {
            if (err)
                reject(err);
            resolve(token);
        });
    });

    console.log('access token:');
    console.log(accessToken);

    return nm.createTransport({
        service: 'Gmail',
        auth: {
            type: 'OAuth2',
            user: process.env.EMAIL,
            accessToken,
            clientId: process.env.CLIENT_ID,
            clientSecret: process.env.CLIENT_SECRET,
            refreshToken: process.env.REFRESH_TOKEN
        }
    });
};

然后我使用另一个模块中的sendMail函数成功发送了一封邮件。但是,我的刷新令牌在 7 天后过期。根据Google OAuth guide:

A Google Cloud Platform project with an OAuth consent screen configured for an external user type and a publishing status of "Testing" is issued a refresh token expiring in 7 days. There is currently a limit of 50 refresh tokens per Google Account per OAuth 2.0 client ID. If the limit is reached, creating a new refresh token automatically invalidates the oldest refresh token without warning. This limit does not apply to service accounts.

换句话说,您似乎需要使用服务帐户(这需要 Google workspace/GSuite,这是一项付费服务​​)或者您需要验证您的应用程序。但是,我是唯一一个使用它的人。我不是为用户创建帐户,只是为了从我自己发送电子邮件给自己。每 7 天必须获得一个新的刷新令牌对我来说不是一个好的选择。似乎使用 API 键是唯一的其他方法,而且你可以做的事情可能会受到严重限制(我不确定你是否可以使用它发送电子邮件)。

从没有用户的基于服务器的应用程序使用 Nodemailer 在 NodeJS 中发送电子邮件的首选方法是什么?有没有一种方法可以在不支付 GSuite/Google Workspace 帐户费用的情况下使用 Gmail?我只是想使用 OAuth 来确保安全,因为我使用的是我自己的帐户,但如果有更简单的方法我还不明白,我洗耳恭听!谢谢

我将与您分享我们为我工作的公司创建的所有网络应用所做的工作。 (www.piersolutions.ca)

Nodemailer很强大,但我觉得你用错了。我和你一样用NodeJs开发

function xxx() {
 async function main() {
        // Generate test SMTP service account from ethereal.email
        // Only needed if you don't have a real mail account for testing
        let testAccount = await nodemailer.createTestAccount();

        // create reusable transporter object using the default SMTP transport
        let transporter = nodemailer.createTransport({
            host: "smtp.gmail.com",
            port: 587,
            secure: false, // true for 465, false for other ports
            auth: {
                user: "xxx@gmail.com",
                pass: "xxx",
//your password needs to be a special password in Gmail.
            },
        });

        // send mail with defined transport object
        let clientEmail = await transporter.sendMail({
            from: "xxx.com", // sender address
            to: username, // list of receivers
            subject: "Welcome To PSD", // Subject line
            text: "Hey " + firstname + ", \n\nYou have been registered for ..." // plain text body
        });

        console.log("Message sent: %s", clientEmail.messageId);
        // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>

        // Preview only available when sending through an Ethereal account
        // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
    }

    main().catch(console.error);
}

您的密码在 gmail 中,您必须为您的 gmail 帐户设置 2 因素身份验证,然后添加应用专用密码。您可以 google 如何获取 google 的 smtp 密码。我可以给任何人发邮件。您可以在变量中定义接收电子邮件的用户,或者在其中硬核他们。由于只有您收到电子邮件,因此最好进行硬编码。希望这对您有所帮助