Skip to content

搞英语 → 看世界

翻译英文优质信息和名人推特

Menu
  • 首页
  • 作者列表
  • 独立博客
  • 专业媒体
  • 名人推特
  • 邮件列表
  • 关于本站
Menu

如何使用 Gmail SMTP 服务器发送电子邮件

Posted on 2022-05-31

本分步教程介绍了如何连接到 Gmail SMTP 服务器以从Node.js Web 应用程序发送电子邮件,该应用程序可以部署在 Google Cloud Functions、AWS Lambda、Cloud Run 或在本地计算机上运行。

与使用用户名和密码组合的大多数其他 Node SMTP 教程不同,这种方法使用 OAuth,并且不需要您在 Google 帐户中打开安全性较低的应用程序访问。

创建 Gmail OAuth 凭据

创建一个新的 Google Cloud 项目并启用 Gmail API,如上一个教程中所述。

Gmail SMTP OAuth Application

在 APIs & Services 部分,点击 Credentials 并点击 Create credentials > OAuth Client Id 创建一个新的客户端 ID,用于向 Google 的 OAuth 服务器识别您的应用程序。

将应用程序类型设置为Web Application并将以下 URL 放入Authorized Redirect URI中。

 https://developers.google.com/oauthplayground

单击Create按钮,您将获得下一步需要的 OAuth Client ID 和 Client Secret 值。

创建 Gmail 刷新令牌

Gmail Access Refresh Token

接下来,我们将使用 Google Developer OAuth 2.0 Playground 生成一个刷新令牌。访问令牌有效期为一小时,但刷新令牌永久有效(除非手动撤销),并可用于生成新的访问令牌。

转到google.com/oauthplayground ,单击齿轮图标并选中“ Use your own OAuth credentials ”选项。复制粘贴您在上一步中生成的客户端 ID 和客户端密码。

在Select & Authorize APIs部分中,输入范围https://mail.google.com并单击Authorize APIs按钮以生成授权代码。

单击Exchange authorization code for tokens以生成我们在下一步中需要的刷新令牌。

Refresh Token

准备 Node.js 应用程序

创建一个新文件夹并安装googleapis和nodemailer软件包。

 mkdir gmail-smtp-sender cd gmail-smtp-sender npm init --y npm install dotenv googleapis nodemailer --save touch index.js

在根文件夹中创建一个新的.env文件并在文件中添加凭据。将文件添加到.gitignore ,这样它就不会添加到存储库中。

 // Replace these with your own credentials CLIENT_ID = 'r2l82l8.apps.googleusercontent.com' CLIENT_SECRET = 'GOCSPX-5n00Mqm5Jc45p' REFRESH_TOKEN = '1//04yt8hEatvIr3uyk-ZJSYIhmYqMk4C4EqfPK24w' REDIRECT_URL = 'https://developers.google.com/oauthplayground'

打开index.js文件并添加以下代码。您可能需要将发件人的电子邮件替换为您已授权发送电子邮件的 Gmail 帐户的电子邮件地址。

Gmail SMTP 服务器名称是smtp.gmail.com ,Gmail SMTP 端口是465 。当邮件通过 SMTP 发送时,您每天最多可以发送 100 封电子邮件。

 const { google } = require ( 'googleapis' ) ; const nodemailer = require ( 'nodemailer' ) ; require ( 'dotenv' ) . config ( ) ; const sendEmail = async ( ) => { const oauth2Client = new google . auth . OAuth2 ( process . env . CLIENT_ID , process . env . CLIENT_SECRET , process . env . REDIRECT_URL ) ; oauth2Client . setCredentials ( { refresh_token : process . env . REFRESH_TOKEN } ) ; const accessToken = await oauth2Client . getAccessToken ( ) ; const myEmail = '[email protected]' ; const smtpTransport = nodemailer . createTransport ( { service : 'gmail' , host : 'smtp.gmail.com' , port : 465 , secure : true , auth : { type : 'OAuth2' , user : myEmail , clientId : process . env . CLIENT_ID , clientSecret : process . env . CLIENT_SECRET , refreshToken : process . env . REFRESH_TOKEN , accessToken , } , } ) ; const mailOptions = { from : 'Sender Name <[email protected]>' , to : 'Receiver Name <[email protected]>' , subject : 'Test email ?' , text : 'This is a test email from Node.js ?' , html : 'This is a <b>test email</b> from Node.js ?' , } ; try { const response = await smtpTransport . sendMail ( mailOptions ) ; console . log ( ` Email sent! ` , response ) ; } catch ( f ) { console . error ( f . message ) ; } finally { smtpTransport . close ( ) ; } } ; sendEmail ( ) . then ( ( ) => console . log ( 'Done!' ) ) ;

这是应用程序发送的测试电子邮件。如果电子邮件接收者客户端不支持HTML 邮件,则呈现纯文本版本。

Gmail Sent email

正确的 Gmail OAuth 范围

虽然您可以使用https://www.googleapis.com/auth/gmail.send范围从 Gmail 发送电子邮件,但您需要对 Gmail SMTP 使用受限的https://mail.google.com/范围。如果您的 OAuth 客户端在为用户请求权限时使用不同的范围,应用程序将返回535-5.7.8 Username and Password not accepted错误。

原文: https://www.labnol.org/gmail-smtp-send-emails-220530

本站文章系自动翻译,站长会周期检查,如果有不当内容,请点此留言,非常感谢。
  • Abhinav
  • Abigail Pain
  • Adam Fortuna
  • Alberto Gallego
  • Alex Wlchan
  • Answer.AI
  • Arne Bahlo
  • Ben Carlson
  • Ben Kuhn
  • Bert Hubert
  • Bits about Money
  • Brian Krebs
  • ByteByteGo
  • Chip Huyen
  • Chips and Cheese
  • Christopher Butler
  • Colin Percival
  • Cool Infographics
  • Dan Sinker
  • David Walsh
  • Dmitry Dolzhenko
  • Dustin Curtis
  • Elad Gil
  • Ellie Huxtable
  • Ethan Marcotte
  • Exponential View
  • FAIL Blog
  • Founder Weekly
  • Geoffrey Huntley
  • Geoffrey Litt
  • Greg Mankiw
  • Henrique Dias
  • Hypercritical
  • IEEE Spectrum
  • Investment Talk
  • Jaz
  • Jeff Geerling
  • Jonas Hietala
  • Josh Comeau
  • Lenny Rachitsky
  • Liz Danzico
  • Lou Plummer
  • Luke Wroblewski
  • Matt Baer
  • Matt Stoller
  • Matthias Endler
  • Mert Bulan
  • Mostly metrics
  • News Letter
  • NextDraft
  • Non_Interactive
  • Not Boring
  • One Useful Thing
  • Phil Eaton
  • Product Market Fit
  • Readwise
  • ReedyBear
  • Robert Heaton
  • Ruben Schade
  • Sage Economics
  • Sam Altman
  • Sam Rose
  • selfh.st
  • Shtetl-Optimized
  • Simon schreibt
  • Slashdot
  • Small Good Things
  • Taylor Troesh
  • Telegram Blog
  • The Macro Compass
  • The Pomp Letter
  • thesephist
  • Thinking Deep & Wide
  • Tim Kellogg
  • Understanding AI
  • 英文媒体
  • 英文推特
  • 英文独立博客
©2025 搞英语 → 看世界 | Design: Newspaperly WordPress Theme