You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python smtplib发送Gmail邮件时如何正确设置邮件主题?

你的问题核心是smtplib.SMTP.sendmail方法的第三个参数要求是符合SMTP协议规范的完整邮件内容,必须包含邮件头(主题、发件人、收件人等字段)和正文,二者之间需要用空行分隔,你之前加主题后丢失正文,大概率是漏掉了这个空行。

另外你现有代码还有三个明显问题:

  • 调用sendMail时只传了2个参数,和函数定义的3个参数(to、subject、message)不匹配
  • sendmail第一个参数填了text,应为实际发件人邮箱地址
  • 连接SMTP服务器失败后没有终止流程,后续调用server.ehlo()会抛出变量未定义错误

方案1:手动拼接邮件内容(简单纯文本邮件适用)

import smtplib
import socket

email = '你的Gmail地址'
# 注意:Gmail现已不支持直接用账号密码登录,需开启两步验证后生成「应用专用密码」填在此处
password = '你的Gmail应用专用密码'
    
def sendMail(to, subject, message):
    server = None
    try:
        server = smtplib.SMTP('smtp.gmail.com', 587)
        print("Connection Status: Connected")
    except socket.gaierror:
        print("Connection Status: ERROR: Not connected to the internet")
        return
    try:
        server.ehlo()
        server.starttls()
        server.login(email, password)
        # 构造完整邮件内容,头和正文之间必须有空行
        full_mail = f"From: {email}\nTo: {to}\nSubject: {subject}\n\n{message}"
        server.sendmail(email, to, full_mail.encode('utf-8'))
        print("邮件发送成功")
    except smtplib.SMTPAuthenticationError:
        print("ERROR: Username or Password are not accepted")
    finally:
        if server:
            server.quit()
    
# 调用时传入三个参数:收件人地址、主题、正文
try:
    sendMail('收件人Gmail地址', '这是测试主题', '这是测试正文内容')
except Exception as e:
    print(f"发送出错:{e}")

方案2:使用email标准库构造邮件(更规范,支持复杂格式、避免乱码)

如果后续需要发HTML内容、附件、中文内容,推荐用Python自带的email库构造邮件,避免手动拼接的格式错误:

import smtplib
import socket
from email.mime.text import MIMEText

email = '你的Gmail地址'
password = '你的Gmail应用专用密码'
    
def sendMail(to, subject, message):
    server = None
    try:
        server = smtplib.SMTP('smtp.gmail.com', 587)
        print("Connection Status: Connected")
    except socket.gaierror:
        print("Connection Status: ERROR: Not connected to the internet")
        return
    try:
        server.ehlo()
        server.starttls()
        server.login(email, password)
        # 构造MIME邮件对象,第二个参数plain表示纯文本,改成html即可发HTML邮件
        msg = MIMEText(message, 'plain', 'utf-8')
        msg['From'] = email
        msg['To'] = to
        msg['Subject'] = subject
        # 转成字符串格式发送
        server.sendmail(email, to, msg.as_string())
        print("邮件发送成功")
    except smtplib.SMTPAuthenticationError:
        print("ERROR: Username or Password are not accepted")
    finally:
        if server:
            server.quit()

sendMail('收件人Gmail地址', '这是测试主题', '这是测试正文内容')

内容的提问来源于stack exchange,提问作者Zacky2613

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 23:36:04