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

使用Python smtplib调用Gmail发送邮件无报错但未成功送达

Python脚本无报错但Gmail邮件无法发送的问题排查

我尝试通过Python脚本发送邮件,脚本执行过程未返回任何错误信息,但邮件始终未成功发送。已验证以下内容:

  • 邮箱凭据准确
  • SMTP服务器及端口设置无误
  • 收件人邮箱地址有效
  • Gmail账号已开启双因素认证并生成了专门用于此脚本的应用密码

脱敏后的相关代码

import pandas as pd
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# Read data from Excel file
excel_file = "C:\\Users\\YourUsername\\Downloads\\AAAAAA.xlsx"
df = pd.read_excel(excel_file)

# Retrieve email addresses from columns 1 and 2
email_addresses = df.iloc[:, 0].values.flatten()

# Email account credentials
sender_email = "*******@gmail.com"
sender_password = "********"  # 

# Additional details for email content
subject = "Greetings"
body = "Hello, sir"

# Connect to the SMTP server
with smtplib.SMTP("smtp.gmail.com", 587) as server:
    server.starttls()
    server.login(sender_email, sender_password)

    # Send the email to each recipient
    for email_address in email_addresses:
        msg = MIMEMultipart()
        msg['From'] = sender_email
        msg['To'] = email_address
        msg['Subject'] = subject
        msg.attach(MIMEText(body, 'plain'))

        server.sendmail(sender_email, email_address, msg.as_string())

    # Close the SMTP session
    server.quit()

可能的原因分析

  • Excel数据读取异常:代码注释标注要读取第1和第2列的邮箱地址,但实际仅读取了第1列(iloc[:,0]),若目标数据在第2列则会导致收件人列表为空或错误。此外,需确认Excel中的邮箱地址格式是否规范(无空格、为字符串类型),可添加print(email_addresses)验证读取结果。
  • 上下文管理器与手动关闭冲突:使用with smtplib.SMTP(...) as server时,上下文管理器会自动在代码块结束时关闭SMTP会话,后续手动调用server.quit()可能导致会话提前终止,部分邮件未完成发送。建议删除server.quit()语句。
  • 邮件被归类为垃圾邮件:Gmail的反垃圾机制可能因邮件内容过于简洁、无个性化信息将其拦截至垃圾邮件箱。测试时可先发送至自己的邮箱,检查垃圾邮件文件夹;同时建议丰富邮件内容,避免触发拦截规则。
  • 发送方法的潜在问题:尝试用server.send_message(msg)替代server.sendmail(sender_email, email_address, msg.as_string()),send_message直接处理MIMEMultipart对象,减少格式转换可能引发的异常。
  • 网络环境限制:本地防火墙、代理服务器可能拦截SMTP连接,导致邮件未实际送达Gmail服务器。可更换网络环境测试脚本。
  • 应用密码权限或生效延迟:确认生成的应用密码是针对「Mail」应用的,且双因素认证处于启用状态。部分情况下应用密码生成后需等待数分钟才能正常使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 21:17:27