如何用Python实现邮件中添加PPT附件?
解决Python发送邮件时PPT附件无法正常添加的问题
问题原因及修复要点:
MIMEMultipart类型错误
你使用的MIMEMultipart("alternative")仅用于提供纯文本/HTML格式的可选邮件正文,不支持包含附件。需改用默认的MIMEMultipart()(对应mixed类型),该类型支持同时承载正文和附件。附件缺少识别头
仅通过MIMEApplication添加文件内容不够,必须设置Content-Disposition头,明确告知邮件客户端这是附件而非嵌入内容。附件文件名无正确后缀
你设置的附件名为file_name,缺少.ppt/.pptx后缀,会导致客户端无法识别文件类型,建议使用带后缀的原文件名。
修改后的完整代码:
import smtplib, ssl from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication import os sender_email = "myemail@gmail.com" receiver_email = "to@gmail.com" password = input("Type your password and press enter:") # 使用mixed类型的MIMEMultipart,支持正文+附件 message = MIMEMultipart() message["Subject"] = "subject" message["From"] = sender_email message["To"] = receiver_email html = """\ <html> <body> <p> email text </p> </body> </html> """ text_part = MIMEText(html, "html") pitch_deck = r"path to ppt" # 替换为实际PPT文件路径,比如r"C:\docs\demo.pptx" # 处理附件逻辑 with open(pitch_deck, "rb") as ppt: # 获取带后缀的原文件名 file_name = os.path.basename(pitch_deck) attachment = MIMEApplication(ppt.read(), Name=file_name) # 设置附件标识头 attachment["Content-Disposition"] = f'attachment; filename="{file_name}"' message.attach(attachment) # 添加HTML正文 message.attach(text_part) context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server: server.login(sender_email, password) server.sendmail( sender_email, receiver_email, message.as_string() )
额外注意事项:
- 确保
pitch_deck变量指向正确的PPT文件路径,Windows路径可使用原始字符串(加r前缀)或转义斜杠。 - 若使用Gmail账号,开启两步验证的情况下需使用应用专用密码登录;未开启两步验证可暂时允许低安全性应用访问(不推荐,建议优先启用两步验证并使用应用密码)。
内容的提问来源于stack exchange,提问作者Vidyaramanan
相关产品推荐
相关产品推荐

