如何在Python中为邮件添加.jpeg或PDF格式的附件?
Python发送带附件邮件的修复方案
你的代码已经能正常发送纯文本邮件,只需添加附件处理逻辑即可,使用EmailMessage的add_attachment方法就可以实现,无需依赖过时的MIMEMultipart类。以下是修改后的完整代码:
import os from email.message import EmailMessage import ssl import smtplib email_sender = 'Example@gmail.com' Password = 'gmail app password' email_receiver = 'Example@gmail.com' subject = 'message subject' body = 'message body text' em = EmailMessage() em['From'] = email_sender em['To'] = email_receiver em['Subject'] = subject em.set_content(body) # 处理附件 attachment_path = "你的完整附件路径(比如./report.pdf)" attachment_filename = os.path.basename(attachment_path) # 读取附件内容 with open(attachment_path, 'rb') as f: file_data = f.read() # 获取文件后缀作为子类型,无后缀则用通用二进制类型 file_ext = os.path.splitext(attachment_path)[1].strip('.') file_subtype = file_ext if file_ext else 'octet-stream' # 添加附件到邮件 em.add_attachment( file_data, maintype='application', # 通用二进制类型主类型,若为图片可改为'image' subtype=file_subtype, filename=attachment_filename ) context = ssl.create_default_context() with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as smtp: smtp.login(email_sender, Password) smtp.sendmail(email_sender, email_receiver, em.as_string())
关键说明:
- 替换
attachment_path为你的实际附件路径,确保文件存在且路径正确 - 如果添加图片附件,可将
maintype改为'image',subtype对应'png'或'jpg'等 - 如需添加多个附件,重复执行「读取文件+add_attachment」的逻辑即可
- 确认Gmail应用密码有效,账号需开启两步验证后生成专用应用密码
内容的提问来源于stack exchange,提问作者RonaldHucklebee
相关产品推荐
相关产品推荐

