使用Python发送带有附件的邮件可以通过以下步骤实现:
1. 导入必要的模块:
import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.mime.base import MIMEBasefrom email import encodersimport os
2. 创建邮件实例并设置邮件头信息:
msg = MIMEMultipart()msg['From'] = '发件人邮箱地址'msg['To'] = '接收方邮箱地址'msg['Subject'] = '邮件主题'msg['Date'] = formatdate(localtime=True) 设置邮件发送时间
3. 添加邮件正文内容:
txt = MIMEText('邮件正文内容', 'plain', 'utf-8')msg.attach(txt)

4. 添加附件:
filename = '附件文件路径'ctype, encoding = mimetypes.guess_type(filename)if ctype is None or encoding is not None:ctype, encoding = 'application/octet-stream', 'utf-8'att = MIMEBase('application', 'octet-stream')att.set_payload(open(filename, 'rb').read())encoders.encode_base64(att)att.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(filename))msg.attach(att)
5. 登录SMTP服务器并发送邮件:
server = smtplib.SMTP('smtp.example.com', 587) 替换为你的SMTP服务器地址和端口server.starttls() 如果SMTP服务器要求TLS加密,则启用server.login(msg['From'], '邮箱密码') 使用你的邮箱地址和密码登录server.sendmail(msg['From'], msg['To'], msg.as_string())server.quit()
请确保替换示例代码中的占位符,如发件人邮箱地址、接收方邮箱地址、邮件主题、邮件正文内容以及附件文件路径,并确保你的SMTP服务器地址和端口是正确的。如果SMTP服务器要求安全连接(如使用SSL),则需要使用`smtplib.SMTP_SSL`代替`smtplib.SMTP`,并相应地调整端口(通常为465)。
还需要注意,出于安全考虑,不要在代码中硬编码你的邮箱密码,可以使用环境变量或配置文件来存储敏感信息
