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

此示例展示如何在 Python 中发送带附件的电子邮件,附件从文件系统上的文件读取:

send_email_attachment.py
#!/usr/bin/env python3
import smtplib
import mimetypes
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_file_to_email(email, filename):
    """将文件标识为 filename,附加到电子邮件消息"""
    with open(filename, 'rb') as fp:
        file_data = fp.read()
        maintype, _, subtype = (mimetypes.guess_type(filename)[0] or 'application/octet-stream').partition("/")
        email.add_attachment(file_data, maintype=maintype, subtype=subtype, filename=filename)

# 附加文件
attach_file_to_email(msg, "myfile.pdf")

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

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

此代码中的实用函数是:

email_utils.py
import smtplib
import mimetypes

def attach_file_to_email(email, filename):
    """将文件标识为 filename,附加到电子邮件消息"""
    with open(filename, 'rb') as fp:
        file_data = fp.read()
        maintype, _, subtype = (mimetypes.guess_type(filename)[0] or 'application/octet-stream').partition("/")
        email.add_attachment(file_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(mail)
    s.quit()

像这样初始化你的电子邮件:

create_email_msg.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')

然后像这样附加文件:

attach_example.py
attach_file_to_email(msg, "myfile.pdf")

并使用以下命令发送电子邮件

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

Check out similar posts by category: Python