使用node.js通过服务帐户在G-suite的注册域上发送自动电子邮件

问题描述

我想在用户注册时向我的网站发送电子邮件,或者想重设密码或需要了解诸如广告系列之类的事件。

我已经创建了一个项目,为OAuth授权注册了一个网络服务器,并将一堆用户与该用户相关联,并为其创建了一个服务帐户。

我试图通过项目的创建者发送邮件,并且工作正常。但是,由于这是一个自动化过程,因此G-suite建议使用服务帐户。这需要额外的步骤,因为您必须在握手中使用与特定服务帐户关联的私钥,才能从https://oauth2.googleapis.com/token中检索access_token才能使用服务邮件。 https://developers.google.com/identity/protocols/oauth2/service-account#delegatingauthority

这是服务帐户acces_token检索(工作正常,因此我不确定是否应该包括它)。

const { OAuth2 } = google.auth
const OAUTH_PLAYGROUND = 'https://developers.google.com/oauthplayground'
const {
    MAILING_SERVICE_CLIENT_ID,MAILING_SERVICE_CLIENT_SECRET,MAILING_SERVICE_REFRESH_TOKEN,SENDER_EMAIL_ADDRESS,} = process.env
const PRIVATE_KEY = fs.readFileSync(__dirname + '/rsa_private.key')

const getServiceMailToken = async () => {
    const header = {
        algorithm: 'RS256',}
    const claims = {
        iss: SENDER_EMAIL_ADDRESS,aud: 'https://oauth2.googleapis.com/token',scope: 'https://www.googleapis.com/auth/gmail.send',iat: Math.floor(Date.now() / 1000),exp: Math.floor(Date.now() / 1000) + 3600,}
    const requestToken = jwt.sign(claims,PRIVATE_KEY,header)
    lastIssued = claims.exp - 5

    const response = await fetch(
        'https://oauth2.googleapis.com/token?' +
            new URLSearchParams({
                grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',assertion: requestToken,}),{
            method: 'POST',headers: {
                Authorization: 'Bearer ' + requestToken,'Content-Type': 'application/json',response_type: 'application/json','Accept-Encoding': 'gzip,deflate,br',Accept: '*/*',},}
    )
    token = await response.json()
}

这是尝试使用access_token以及为网络服务器生成的clientIdclientSecretrefreshToken发送邮件。

const sendMail = async (data) => {
        if (token === undefined || token.exp < Math.floor(Date.now() / 1000)) {
            await getServiceMailToken()
        }
        const smtpTransport = nodemailer.createTransport({
            service: 'gmail',auth: {
                type: 'OAuth2',rejectUnauthorized: false,user: SENDER_EMAIL_ADDRESS,clientId: MAILING_SERVICE_CLIENT_ID,clientSecret: MAILING_SERVICE_CLIENT_SECRET,refreshToken: MAILING_SERVICE_REFRESH_TOKEN,accessToken: token.access_token,})
        const filePath = `${__dirname}/templates/${
            TEMPLATES[data.template].fileName
        }`
        ejs.renderFile(filePath,data,{},(e,content) => {
            if (e) return e
            const mailOptions = {
                from: SENDER_EMAIL_ADDRESS,to: data.email,subject: TEMPLATES[data.template].subject,html: content,}
            smtpTransport.sendMail(mailOptions,(err,info) => {
                if (err) return err
                return info
            })
        })
    },}

module.exports = sendMail

这是我收到的错误消息:

send mail err { Error: Invalid login: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8  https://support.google.com/mail/?p=BadCredentials s14sm1656619ljh.98 - gsmtp

在某些情况下,当我与项目的创建者发送邮件时,我要替换的唯一代码是更改.env文件中的电子邮件,并用替换请求access_token

auth2Client.setCredentials({
     refresh_token: MAILING_SERVICE_REFRESH_TOKEN,})
const accessToken = await oauth2Client.getAccessToken()

我希望此问题与某种权限有关。我的项目已激活用于发送电子邮件的角色委托,并且服务帐户也已激活它。该项目使不安全的应用程序可以访问它,并且服务帐户角色是所有者。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...