'InMemoryUploadedFile'对象没有属性'encode' [英] 'InMemoryUploadedFile' object has no attribute 'encode'

查看:51
本文介绍了'InMemoryUploadedFile'对象没有属性'encode'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Django中发送带有附件的电子邮件.文件是 request.FILE ['file'] 对象(InMemoryUploadedFile类型).我通过 EmailMessage(...)创建消息,然后通过 message.attach(f.name,f.read(),f.content_type)附加文件..>

发送电子邮件失败,出现以下错误:'InMemoryUploadedFile'对象没有属性'encode'

解决方案

这在 forms.py

中的表单定义中对我有用从django.core.mail中的

 导入EmailMultiAlternativesemail = EmailMultiAlternatives(subject =某些主题",from_email='from_address@some_domain.com',到= ['recipient1@another_domain.com'],body =一些html内容")email.content_subtype ="html"如果hasattr(self.files,'getlist'):files = self.files.getlist('document []')对于文件中的_file:_file.open()email.attach(_file.name,_file.read(),_file.content_type)_file.close()email.send() 

documents [] 是输入html标记的名称:

<输入名称="document []" id ="file" type ="file">

I'm trying to send an email with an attachment in Django. File is request.FILE['file']object (InMemoryUploadedFile type). I create message by EmailMessage(...) and then attach file by message.attach(f.name, f.read(), f.content_type).

Sending email fails with given error: 'InMemoryUploadedFile' object has no attribute 'encode'

解决方案

This worked for me inside a form definition in forms.py

from django.core.mail import EmailMultiAlternatives

email = EmailMultiAlternatives(
    subject='some subject',
    from_email='from_address@some_domain.com',
    to=['recipient1@another_domain.com'],
    body='some html content')
email.content_subtype = "html"
if hasattr(self.files, 'getlist'):
    files = self.files.getlist('document[]')
    for _file in files:
        _file.open()
        email.attach(_file.name, _file.read(), _file.content_type)
        _file.close()
email.send()

Where documents[] is the name of the input html tag:

<input name="document[]" id="file" type="file">

这篇关于'InMemoryUploadedFile'对象没有属性'encode'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆