Django发送邮件时.eml附件内容混入正文的解决方法咨询
解决Django发送邮件时.eml附件内容显示在正文的问题
这个问题我之前做邮件功能时也踩过坑!核心原因是Django默认对.eml文件的MIME类型判断有误,导致邮件客户端把它当成了邮件正文的一部分来渲染,而不是作为独立附件处理。
解决方案:手动指定.eml文件的MIME类型
.eml文件的标准MIME类型是message/rfc822,我们只需要在添加附件时明确指定这个类型,就能让客户端正确识别它为独立附件,不会把内容解析到正文里。
方法1:修改attach_file调用,指定mimetype
你可以在遍历附件时,判断文件后缀是否为.eml,然后针对性设置MIME类型:
import os from django.core.mail import EmailMultiAlternatives # 初始化邮件对象 msg = EmailMultiAlternatives( subject="你的邮件主题", body="邮件正文内容", from_email="sender@yourdomain.com", to=["recipient@example.com"], ) # 处理所有附件 for attachment in your_attachment_collection: file_path = attachment.path filename = attachment.name if filename.lower().endswith(".eml"): # 对.eml文件指定正确的MIME类型 msg.attach_file(file_path, mimetype="message/rfc822") else: # 其他文件(比如CSV)用默认逻辑处理即可 msg.attach_file(file_path) # 发送邮件 msg.send()
方法2:使用attach方法手动添加附件(可选)
如果你更倾向于手动读取文件内容,也可以用attach方法实现同样的效果:
for attachment in your_attachment_collection: file_path = attachment.path filename = attachment.name if filename.lower().endswith(".eml"): with open(file_path, "rb") as f: file_content = f.read() msg.attach(filename, file_content, mimetype="message/rfc822") else: msg.attach_file(file_path)
为什么这样有效?
当你不指定mimetype时,Django会通过文件扩展名自动猜测类型,.eml文件可能被识别为text/plain(纯文本类型),这就会让邮件客户端把它的内容直接追加到正文里。而指定message/rfc822后,客户端会明确知道这是一个独立的邮件格式附件,只会在附件列表中显示,不会解析到正文。
你可以发送一封测试邮件验证一下,应该就能看到.eml文件只出现在附件栏,正文里不会再显示它的内容了。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

