【问题标题】:Sending email with attached .ods File发送带有附加 .ods 文件的电子邮件
【发布时间】:2018-11-29 12:51:28
【问题描述】:
send_mail('Subject here', 'Here is the message.', 'selva@gmail.com', ['stab@gmail.com'], fail_silently=False)
mail = send_mail('Subject here', 'Here is the message.', 'selvakumaremmy@gmail.com', ['vsolvstab@gmail.com'], fail_silently=False)
mail.attach('AP_MODULE_bugs.ods','AP_MODULE_bugs.ods','application/vnd.oasis.opendocument.spreadsheet')
mail.send()

我正在使用 Django send_mail 类发送邮件。这里我想发送带有附件的邮件,我的附件文件(.ods)在本地存储中。

【问题讨论】:

    标签: python django django-rest-framework django-mailer


    【解决方案1】:

    你必须使用EmailMessage

    from django.core.mail import EmailMessage
    
    email = EmailMessage(
        'Hello',
        'Body goes here',
        'from@example.com',
        ['to1@example.com', 'to2@example.com'],
        ['bcc@example.com'],
        reply_to=['another@example.com'],
        headers={'Message-ID': 'foo'},
    

    )

    mail.attach('AP_MODULE_bugs.ods',mimetype='application/vnd.oasis.opendocument.spreadsheet')
    

    mail.send()

    attach() 创建一个新的文件附件并将其添加到消息中。调用attach()有两种方式:

    • 您可以将单个参数传递给它,即 email.MIMEBase.MIMEBase 实例。这将直接插入到生成的消息中。
    • 或者,您可以传递 attach() 三个参数:文件名, 内容和模仿类型。文件名是文件附件的名称 它将出现在电子邮件中,内容是将要发送的数据 附件中包含的 mimetype 是可选的 MIME 类型的附件。如果省略 mimetype,则 MIME 内容类型 将从附件的文件名中猜测。

      例如:message.attach('design.png', img_data, 'image/png')

    【讨论】:

    • 谢谢@selvakumar
    【解决方案2】:

    尝试使用attach_file()

    例如:

    mail = EmailMessage('Subject here', 'Here is the message.', 'selva@gmail.com',  ['stab@gmail.com'])
    mail.attach_file('PATH TO AP_MODULE_bugs.ods', mimetype='application/vnd.oasis.opendocument.spreadsheet')
    mail.send()
    

    【讨论】:

    • 返回异常“对象没有属性'attach_file”
    • 更新了 sn-p。
    猜你喜欢
    • 2020-06-04
    • 2015-09-09
    • 2012-06-15
    • 2017-09-06
    • 1970-01-01
    • 2018-07-24
    相关资源
    最近更新 更多