如何使用Gmail的SMTP服务器发送邮件
在网站运营或者自动化应用中,发送电子邮件几乎是一个必不可少的功能。无论是订单通知、用户注册验证,还是表单提交回执,都需要依赖可靠的邮件发送机制。但许多开发者或站长在配置电子邮件服务时,常常被“SMTP”卡住 —— 什么是 SMTP?去哪找?怎么用?
其实,如果你有 Gmail 帐号,就已经拥有了一个稳定、安全的 SMTP 发信工具。本文将手把手教你如何使用 Gmail 的 SMTP 服务器发送邮件,无论你是要在网站后台、WordPress程序中发信,还是用 Python/PHP 做邮件通知系统,都能快速上手。
获取 Gmail SMTP 配置信息
要使用Gmail的SMTP服务,首先需要确认你的 Gmail 帐号开启了相关权限。以下是 Gmail SMTP 的基础连接参数:
值得注意的是,从 2025 年 5 月 1 日起,Gmail 不再支持“低安全性应用”直接使用邮箱密码来访问SMTP服务,需要使用“应用专用密码”才能从第三方访问Google的SMTP服务。那如何获得应用专用密码呢?
首先登录你的Gmail账号,打开:https://myaccount.google.com/
点击左侧菜单栏的“安全性”,开启两步验证,如图:
然后打开 https://myaccount.google.com/apppasswords 这个网址设置“应用专用密码”,应用名称可随便起一个,如图:
生成的16位的专用密码只会显示一次,需要记录下来,如图:
使用的时候,需要删除密码中的空格,比如上图中的密码是“dmggldecfrgusxuf”。
测试SMTP服务器能不能用
我有一台Debian的服务器,所以我找ChatGPT要了一段Python代码,Python 自带 smtplib 和 email 模块,可以很方便地通过 Gmail SMTP 发送带标题、正文甚至附件的邮件。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
发件人和收件人信息
sender_email = "y[email protected]m"
receiver_email = "a[email protected]m"
app_password = "dmggldecfrgusxuf" # Gmail 应用专用密码
构建邮件内容
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = "测试邮件 - 来自 Debian 的 Python SMTP"
邮件正文(纯文本)
body = "你好,这是通过 Gmail SMTP 发出的测试邮件。"
message.attach(MIMEText(body, "plain"))
发送邮件
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls() # TLS 加密
server.login(sender_email, app_password)
server.sendmail(sender_email, receiver_email, message.as_string())
server.quit()
print("邮件发送成功 ✅")
except Exception as e:
print("邮件发送失败 ❌")
print(str(e))
没有任何意外,邮件当然是发送成功了。如图:
免费的Gmail邮箱每天可以发送500封邮件,而企业版的workspace每天可以发2000封,应该够用了。
如果你使用的是Gmail企业邮箱,你还需要设置域名的MX邮件记录以及SPF,防止你的外发电子邮件被接收邮件服务器标记为垃圾邮件。
常见问题
为什么邮件服务器返回以下错误信息:Username and Password not accepted. 有两种可能:
你还在使用旧的验证方式:直接使用邮箱用户名+密码的方式访问SMTP服务器
虽然使用了“应该专用密码”,但是忘记删除“应该专用密码”中的空格
如果确认不是上述问题,可以向ChatGPT请教,让ChatGPT帮你分析,提供解决方案。
使用体验
Gmail的SMTP服务器极其稳定,虽然企业邮箱月租7.2美元一个月,但是我觉得物有所值,值得尝试。
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
vfk4v9
bebqc0
byf70j
jvbfq3
jnfjc4
Greetings! Veryy useful adbice witthin this post! It's thee littpe changes which wikl mmake thee largest changes.
Thanks ffor sharing!
An outstqnding share! I havce just forwardded this ontoo
a co-worker who was doling a little homerwork on this. Annd hee in faact orddered mee bteakfast because I
found it for him... lol. So alpow mme to reword this....
Thanks for the meal!! Buut yeah, thanks for spending the timke
too tapk abvout thiss matter her oon yolur site.
2zbu4x
Heyy There. I fond your bloig thhe use of msn. This is
an exrremely neatly written article. I will be
shre tto bookmark it andd com bck to learn extea off your helpfhl information. Thanks for the post.
I'll certainlly return.
If some onee desires too be updated wiith hottest technologies
after tha he mjst bee visiit this website and be upp tto date every day.
n987jb