发送带有附件django的电子邮件 [英] Send email with attachment django
本文介绍了发送带有附件django的电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据库中有文件url。我想将文件作为附件发送到电子邮件中。我已经尝试了以下代码
I have the file url in my db. I want to send the file as an attachment in email. I have tried the below code
def mail_business_plan(sender, instance, created, **kwargs):
if created:
ctx = {"ctx":instance}
from_email = 'info@some_email.in'
subject = 'Business Plan by' + instance.company_name
message = get_template('email/business_team.html').render(ctx)
to = ['some_email@gmail.com']
mail = EmailMessage(subject, message, to=to, from_email=from_email)
mail.attach_file(instance.presentation, instance.presentation.read(), instance.presentation.content_type)
return mail.send()
我收到错误,因为 AttributeError:'FieldFile'对象没有属性'content_type'
I am getting error as "AttributeError: 'FieldFile' object has no attribute 'content_type'"
如果文件路径存储在数据库中,发送带有附件的邮件的最佳方法是什么。
What's the best way to send mail with attachment, if the file path is stored in the database.
推荐答案
假设您有一个模型,
Assuming you have a model as,
class MyModel(models.Model):
# other fields
presentation = models.FileField(upload_to='some/place/')
并在您的信号中,
import mimetypes
def mail_business_plan(sender, instance, created, **kwargs):
if created:
ctx = {"ctx": instance}
from_email = 'info@some_email.in'
subject = 'Business Plan by' + instance.company_name
message = get_template('email/business_team.html').render(ctx)
to = ['some_email@gmail.com']
mail = EmailMessage(subject, message, to=to, from_email=from_email)
content_type = mimetypes.guess_type(instance.presentation.name)[0] # change is here <<<
mail.attach_file(instance.presentation, instance.presentation.read(), content_type) # <<< change is here also
return mail.send()
这篇关于发送带有附件django的电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文