如何在django发送图像的电子邮件

时间:2015-07-31 11:02:33

标签: python django django-class-based-views

我试图通过电子邮件发送图片。我已经提到了下面的代码。任何人都可以检查我做了什么错误。我提到了下面的代码

Adapter

我收到如下错误 强制转换为Unicode:需要字符串或缓冲区,发现InMemoryUploadedFile

2 个答案:

答案 0 :(得分:0)

试试这个:

import os
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from email.MIMEImage import MIMEImage

# You probably want all the following code in a function or method.
# You also need to set subject, sender and to_mail yourself.
html_content = render_to_string('foo.html', context)
text_content = render_to_string('foo.txt', context)
msg = EmailMultiAlternatives(subject, text_content,
                             sender, [to_mail])

msg.attach_alternative(html_content, "text/html")

msg.mixed_subtype = 'related'

for f in ['img1.png', 'img2.png']:
    fp = open(os.path.join(os.path.dirname(__file__), f), 'rb')
    msg_img = MIMEImage(fp.read())
    fp.close()
    msg_img.add_header('Content-ID', '<{}>'.format(f))
    msg.attach(msg_img)

msg.send()

来源:Sending emails with embedded images in Django

答案 1 :(得分:0)

您不能使用django管理的文件作为第一个参数调用open()open()希望文件的路径作为第一个参数,并且您没有传递一个,因此错误消息。

相反,Django提供了一个文件抽象API,允许您直接从Django提供给您的上传文件对象中读取图像数据:

msg = EmailMultiAlternatives(...)
# [...]
for attachment in self.request.FILES.getlist("attachment"):
    # rewind file object, make sure it's open
    img_file.open('rb')
    try:
        # directly read in data from uploaded file object
        img_data = img_file.read()
        msg_img = MIMEImage(img_data)
        msg.attach(msg_img)
    finally:
        # not strictly mandated by django, but why not
        img_file.close()

msg.send()

PS。:您的原始代码可能会泄漏文件描述符。始终尝试将withopen合并。