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

Python 如何在django中发送图像电子邮件,python,django,django-class-based-views,Python,Django,Django Class Based Views,我已尝试在电子邮件中发送图像。我已经提到了下面的代码。有人能检查一下我犯了什么错误吗。我在下面提到了代码 msg = EmailMultiAlternatives(subject, text_content, from_email, to, cc='',headers =sendgrid ) msg.attach_alternative(html_content, "text/html") #print "path",os.path.join(settings.MEDIA_ROOT+'/i

我已尝试在电子邮件中发送图像。我已经提到了下面的代码。有人能检查一下我犯了什么错误吗。我在下面提到了代码

 msg = EmailMultiAlternatives(subject, text_content, from_email, to, cc='',headers =sendgrid )
 msg.attach_alternative(html_content, "text/html")
 #print "path",os.path.join(settings.MEDIA_ROOT+'/instance/errorscreenshot/'+Image)
 for attachment in self.request.FILES.getlist("attachment"):
       #Path = os.path.join(settings.MEDIA_ROOT+'/instance/errorscreenshot/'+attachment) ---->>>>> when i tried to give path of image, then also am getting error like "cannot concatenate str and InMemoryUploadedFile object"**
       #print "path",attachment
       fp = open(attachment,'rb')
       msg_img = MIMEImage(fp.read())
       msg.attach(msg_img)

 msg.send(fail_silently=False)
我得到的错误如下 强制使用Unicode:需要字符串或缓冲区,在MemoryUploadedFile中找到

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()
来源:

不能使用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()

注:您的原始代码可能会泄漏文件描述符。始终尝试与打开组合。

您可以发布错误消息的完整堆栈跟踪吗?目前还不清楚该异常是从何处引发的。还有,你为什么要重新打开上传的文件?Django上传的文件对象具有读取方法。我想发送上传图像的电子邮件。这就是我想读的,这是如何解决OP的问题,他无法从表单上传中获取图像数据的?