引言

准备工作

在开始之前,请确保您已经安装了以下Python库:

  • smtplib:用于发送邮件。
  • email:用于构建邮件内容。

您可以通过以下命令安装这些库(如果尚未安装):

pip install pyzmail

创建SMTP连接

SMTP(Simple Mail Transfer Protocol)是用于发送电子邮件的协议。首先,您需要创建一个SMTP连接。

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

# SMTP服务器设置
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_user = 'your_email@example.com'
smtp_password = 'your_password'

# 创建SMTP连接
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(smtp_user, smtp_password)

请将smtp.example.comyour_email@example.comyour_password替换为实际的SMTP服务器地址、您的邮箱地址和密码。

构建邮件内容

接下来,我们需要构建邮件内容,包括正文和附件。

# 创建MIMEMultipart对象,用于合并文本和附件
msg = MIMEMultipart()
msg['From'] = smtp_user
msg['To'] = 'recipient@example.com'
msg['Subject'] = '邮件主题'

# 添加邮件正文
body = '这是一封带有附件的邮件。'
msg.attach(MIMEText(body, 'plain'))

# 添加附件
filename = 'example.txt'
attachment = open(filename, 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f"attachment; filename= {filename}")
msg.attach(part)

请将recipient@example.com替换为收件人的邮箱地址,将example.txt替换为您的附件文件名。

发送邮件

现在,您可以使用以下代码发送邮件:

# 发送邮件
server.sendmail(smtp_user, 'recipient@example.com', msg.as_string())

关闭SMTP连接

发送邮件后,不要忘记关闭SMTP连接:

server.quit()

总结

通过以上步骤,您已经可以使用Python轻松发送带有附件的邮件。这种方法可以帮助您提高工作效率,尤其是在需要频繁发送文件的情况下。在编写邮件发送脚本时,请确保遵循相关的安全规范和最佳实践,以保护您的邮件账户和信息安全。