Skip to main content

Python 电子邮件

Python SMTP 发送邮件

本章节主要提供一个完整的,Python 发送纯文本邮件、发送HTML邮件与附件 的完整例子,只需要修改对应邮箱的 smtp 服务器地址和用户的邮箱账号即可。

需要主要的是:

  • 确保邮件服务端的地址正确,比如 qq 的是 smtp.qq.com,每个邮件服务商的都不一样。
  • 登录密码一般情况下都是客户端授权码,qq 邮箱的也是。

发送纯文本邮件

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

# qq邮件配置
smtp_server = "smtp.qq.com"
smtp_port = 587  # 587 或者 465,如果一个不行,换一个。
sender_email = "xxxxxx@qq.com"
sender_password = "xxxxxx"  # 客户端授权码
receiver_email = ["xxxxxx@qq.com"]

# 创建邮件对象
msg = MIMEText("这是一个纯文本邮件示例。\n祝你学习愉快!", "plain", "utf-8")
msg["Subject"] = "纯文本邮件测试"
msg["Date"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
msg["From"] = sender_email
msg["To"] = ",".join(receiver_email)

# 连接并发送邮件
with smtplib.SMTP(smtp_server, smtp_port) as server:
    server.set_debuglevel(2)
    server.starttls()  # 启用 TLS
    server.login(sender_email, sender_password)
    server.sendmail(sender_email, receiver_email, msg.as_string())
    print("邮件发送成功!")

发送HTML邮件与附件

发送 HTML + 图片 + 附件 代码。

import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import datetime

# qq邮件配置
smtp_server = "smtp.qq.com"
smtp_port = 587  # 587 或者 465,如果一个不行,换一个
sender_email = "xxxxxx@qq.com"
sender_password = "xxxxxx"  # 客户端授权码
receiver_email = ["xxxxxx@qq.com"]

# 创建邮件对象
msg = MIMEMultipart()
msg["Subject"] = "HTML+图片+附件+邮件测试"
msg["Date"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
msg["From"] = sender_email
msg["To"] = ",".join(receiver_email)

# HTML 内容
html_content = """
<html>
<head>
    <title>HTML 邮件</title>
</head>
<body>
    <h1>欢迎学习 Python 邮件发送!</h1>
    <p>这是一封包含图片的 HTML 邮件。</p>
    <img src="cid:img_id1" alt="示例图片" style="width:200px;">
    <p>这是一个段落!</p>
</body>
</html>
"""
msg.attach(MIMEText(html_content, "html", "utf-8"))

# 添加图片,并在正文 HTML 中引用
image_path = "/Users/yzy/Desktop/PopChar.png"
with open(image_path, "rb") as f:
    image = MIMEImage(f.read())
    image.add_header("Content-ID", "img_id1")
    msg.attach(image)

# 添加多个附件
for filename in ['/Users/yzy/.vimrc', '/Users/yzy/.zshrc']:
    with open(filename, 'rb') as f:
        attachment = MIMEBase("application", "octet-stream")
        attachment.add_header('Content-Disposition', 'attachment', filename=filename.split("/")[-1])
        attachment.set_payload(f.read())
        encoders.encode_base64(attachment)
        msg.attach(attachment)

# 连接并发送邮件
with smtplib.SMTP(smtp_server, smtp_port) as server:
    server.set_debuglevel(2)
    server.starttls()  # 启用 TLS
    server.login(sender_email, sender_password)
    server.sendmail(sender_email, receiver_email, msg.as_string())
    print("邮件发送成功!")