Skip to main content
 首页 » 编程设计

python之发送带有附件 django 的电子邮件

2024年09月07日40落叶无声

我的数据库中有文件 url。我想将文件作为电子邮件附件发送。我试过下面的代码

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’”

如果文件路径存储在数据库中,发送带附件的邮件的最佳方式是什么。

请您参考如下方法:

假设您有一个模型,

class MyModel(models.Model): 
    # other fields 
    presentation = models.FileField(upload_to='some/place/') 


在你的信号中,

<b>import mimetypes</b> 
 
 
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) 
 
        <b>content_type = mimetypes.guess_type(instance.presentation.name)[0] # change is here <<<</b> 
        mail.attach_file(instance.presentation, instance.presentation.read(),<b> content_type) # <<< change is here also</b> 
 
        return mail.send()

引用:
mimetypes.guess_type()