如何在 Python 中通过 SMTP 发送带 BytesIO 附件的电子邮件

此示例详细说明如何在 Python 中发送电子邮件,附件来自 io.BytesIO 实例而不是从文件系统上的文件读取附件:

example-5.txt
__author__ = "Uli Köhler"
__license__ = "CC0 1.0 Universal (public domain)"
__version__ = "1.0"
import smtplib
import mimetypes
from io import BytesIO
from email.message import EmailMessage

# 创建消息并设置文本内容
msg = EmailMessage()
msg['Subject'] = 'This email contains an attachment'
msg['From'] = 'sender@domain.com'
msg['To'] = 'recipient@domain.com'
# 设置文本内容
msg.set_content('Please see attached file')

def attach_bytesio_to_email(email, buf, filename):
    """将文件标识为 filename,附加到电子邮件消息"""
    # 重置读取位置并提取数据
    buf.seek(0)
    binary_data = buf.read()
    # 猜测 MIME 类型或使用 'application/octet-stream'
    maintype, _, subtype = (mimetypes.guess_type(filename)[0] or 'application/octet-stream').partition("/")
    # 添加为附件
    email.add_attachment(binary_data, maintype=maintype, subtype=subtype, filename=filename)

# 附加文件
buf = BytesIO()
buf.write(b"This is a test text")
attach_bytesio_to_email(msg, buf, "test.txt")

def send_mail_smtp(mail, host, username, password):
    s = smtplib.SMTP(host)
    s.starttls()
    s.login(username, password)
    s.send_message(msg)
    s.quit()

send_mail_smtp(msg, 'smtp.my-domain.com', 'sender@domain.com', 'sae7ooka0S')

上面的脚本使用以下实用函数:

example-4.py
    """将文件标识为 filename,附加到电子邮件消息"""
    # 重置读取位置并提取数据
    buf.seek(0)
    binary_data = buf.read()
    # 猜测 MIME 类型或使用 'application/octet-stream'
    maintype, _, subtype = (mimetypes.guess_type(filename)[0] or 'application/octet-stream').partition("/")
    # 添加为附件
    email.add_attachment(binary_data, maintype=maintype, subtype=subtype, filename=filename

def send_mail_smtp(mail, host, username, password):
    s = smtplib.SMTP(host)
    s.starttls()
    s.login(username, password)
    s.send_message(msg)
    s.quit()

你可以直接在代码中使用。初始化电子邮件消息的最简单方法是使用

example-3.py
msg = EmailMessage()
msg['Subject'] = 'This email contains an attachment'
msg['From'] = 'sender@domain.com'
msg['To'] = 'recipient@domain.com'
# 设置文本内容
msg.set_content('Please see attached file')

然后使用以下命令附加你的 BytesIO 实例(名为 buf

example-2.py

添加完附件后,使用以下命令发送消息

example-1.py

Check out similar posts by category: E-Mail, Python