使用Django发送带附件的电子邮件

3

我在数据库中有文件的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'属性"

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


1
什么是实例模型?确切地说是演示领域? - mastisa
3个回答

3
假设你有一个模型,如下所示:
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()

Reference:
mimetypes.guess_type()


0

在Python中发送电子邮件的最佳方法是使用SMTP。

以下是在Ubuntu中配置Postfix并发送邮件的步骤:

  1. sudo apt-get install mailutils

    只需按“ok”即可处理所有弹出窗口(您可以稍后更改主机名)。

  2. sudo vim /etc/postfix/main.cf

    将以下行from inet_interfaces = all更改为inet_interfaces = localhost

  3. sudo service postfix restart

完成所有这些步骤后,请尝试以下代码:

import os.path
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

def send_email(subject, message, from_email, to_email=[], attachment=[]):
    """
    :param subject: email subject
    :param message: Body content of the email (string), can be HTML/CSS or plain text
    :param from_email: Email address from where the email is sent
    :param to_email: List of email recipients, example: ["a@a.com", "b@b.com"]
    :param attachment: List of attachments, exmaple: ["file1.txt", "file2.txt"]
    """
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = ", ".join(to_email)
    msg.attach(MIMEText(message, 'html'))

    for f in attachment:
        with open(f, 'rb') as a_file:
            basename = os.path.basename(f)
            part = MIMEApplication(a_file.read(), Name=basename)

        part[
            'Content-Disposition'] = 'attachment; filename="%s"' % basename
        msg.attach(part)

    email = smtplib.SMTP('localhost')
    email.sendmail(from_email, to_email, msg.as_string())

0

我通过更改代码得到了解决方案

mail.attach_file(instance.presentation, instance.presentation.read(), instance.presentation.content_type)

mail.attach_file(instance.presentation.path)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接