Skip to main content
 首页 » 编程设计

python之emailmultialternatives 在 django 中附加文件和 html 内容

2025年05月04日36jackei

我尝试使用 EmailMultiAlternatives 以 html 格式发送电子邮件,并且 一段文字。我还想在此电子邮件中包含一个文件。

但后者似乎删除了我的 html 内容。

这是我的代码:

msg = EmailMultiAlternatives(subject, html2text(html_content),  
list(email_from), list(email_to),  
attachments=((request.session['customer']+".txt.blowfish",  
request.session["customer"].content),))  
 
msg.attach_alternative(html_content, "text/html")  
 
msg.send()  

我使用最新的SVN版本 我也尝试使用 msg.attact() 而不是附件,结果相同!

发送替代文本内容,但不发送 html 内容。它只是 显示文件。

任何线索将不胜感激,

请您参考如下方法:

我遇到了同样的问题!

我用来将文件附加到 HTML 电子邮件的代码是:

email_dict = {} 
email_dict['user'] = user                        
 
t = loader.get_template('emails/myemail.html') 
html = t.render(Context(email_dict)) 
 
msg = EmailMultiAlternatives(subject='My Subject',  
                             body=html,  
                             from_email=settings.DEFAULT_FROM_EMAIL,  
                             to=['my_email@email.com'],)  
 
attachment = open('filepath', 'rb') 
msg.attach('Name.txt', attachment.read(), 'text/csv') 
 
msg.content_subtype = 'html' 
msg.send() 

所以也许这样的事情对你有用:

msg = EmailMultiAlternatives(subject=subject,  
                             body=html2text(html_content),  
                             from_email=list(email_from),  
                             to=list(email_to)) 
 
 
attachment = open(request.session['customer']+".txt.blowfish", 'rb') 
msg.attach('Name.txt.blowfish', attachment.read(), 'text/plain') 
 
msg.content_subtype = 'html' 
msg.send() 

希望对您有所帮助!