如何使用使用Google Email发送邮件

简介

在本教程中,我们将详细讲解如何通过 Google Email(Gmail)向外发送邮件,包括如何进行 SMTP 配置、生成 App 密码以及一些常见问题的解决方法。适合初学者快速上手。


准备工作

  1. 确保启用两步验证:为了确保账户的安全,Google 要求启用两步验证才能使用 SMTP 发送邮件。
  2. 申请 App 专用密码:由于常规的 Google 密码无法直接用于 SMTP 配置,需申请一个专门的 App 密码。

步骤一:启用两步验证

  1. 登录你的 Gmail 账号。
  2. 点击右上角的头像,进入“管理您的 Google 账户”。
  3. 在左侧找到“安全”选项卡。
  4. 在“两步验证”选项中,点击“启用”,并按照提示完成设置。

步骤二:生成 App 密码

  1. 返回“安全”页面,找到“App 密码”。
  2. 输入 Google 账户的登录密码以验证身份。
  3. 在“选择应用程序”下拉列表中选择“邮件”,设备类型选择“其他”,可以自定义一个名字(例如:SMTP)。
  4. 点击“生成”按钮,系统会为你生成一个 16 位的 App 专用密码。保存此密码,稍后会在配置 SMTP 时用到。

步骤三:配置 SMTP 信息

使用 Gmail SMTP 发送邮件需要以下信息:

  • SMTP 服务器:smtp.gmail.com
  • 端口号:587(TLS)或 465(SSL)
  • SSL/TLS 加密:是
  • 用户名:你的 Gmail 邮箱地址
  • 密码:上一步生成的 App 密码

在代码中可以这样配置(假设使用的是 Node.js):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const nodemailer = require("nodemailer");

const transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 587, // 使用TLS
secure: false, // true for 465, false for other ports
auth: {
user: "[email protected]", // 你的Gmail地址
pass: "your-app-password", // 上一步生成的App密码
},
});

// 发送邮件
const mailOptions = {
from: "[email protected]",
to: "[email protected]",
subject: "Hello from Gmail",
text: "This is a test email sent from a Node.js app using Gmail SMTP.",
};

transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log("邮件发送成功: %s", info.messageId);
});