编辑:我可以在本地机器上发送附件,但不能在 Heroku 上。我将附加代码更改为:
if docfile:
email.attach_file(docfile.name)
这可以在本地、shell 中以及当我运行我的应用程序的本地主机服务器时工作。
所以我一直在尝试让 django 发送带有附件的电子邮件,这些附件存储为故事模型中的 File 对象。我有一个任务来处理这个:
from celery import task
from django.core.mail.message import EmailMessage
from django.core.files.storage import default_storage
from apps.account.models import UserProfile
@task(name='send-email')
def send_published_article(sender, subject, body, attachment=None):
recipients = []
for profile in UserProfile.objects.all():
if profile.user_type == 'Client':
recipients.append(profile.user.email)
email = EmailMessage(subject, body, sender, recipients)
try:
docfile = default_storage.open(attachment.name, 'w+')
if docfile:
email.attach_file(docfile.name)
else:
pass
except:
pass
email.send()
我一直在尝试查找 shell 的错误,在我到达最后一行并运行 email.send() 之前,一切似乎都很好。shell 会显示此错误跟踪:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/vagrant/nns/local/lib/python2.7/site-packages/django/core/mail/message.py", line 248, in send
return self.get_connection(fail_silently).send_messages([self])
File "/home/vagrant/nns/local/lib/python2.7/site-packages/django/core/mail/backends/console.py", line 23, in send_messages
self.stream.write('%s\n' % message.message().as_string())
File "/home/vagrant/nns/local/lib/python2.7/site-packages/django/core/mail/message.py", line 215, in message
msg = self._create_message(msg)
File "/home/vagrant/nns/local/lib/python2.7/site-packages/django/core/mail/message.py", line 272, in _create_message
return self._create_attachments(msg)
File "/home/vagrant/nns/local/lib/python2.7/site-packages/django/core/mail/message.py", line 285, in _create_attachments
msg.attach(self._create_attachment(*attachment))
File "/home/vagrant/nns/local/lib/python2.7/site-packages/django/core/mail/message.py", line 312, in _create_attachment
attachment = self._create_mime_attachment(content, mimetype)
File "/home/vagrant/nns/local/lib/python2.7/site-packages/django/core/mail/message.py", line 300, in _create_mime_attachment
Encoders.encode_base64(attachment)
File "/usr/lib/python2.7/email/encoders.py", line 45, in encode_base64
encdata = _bencode(orig)
File "/usr/lib/python2.7/email/encoders.py", line 31, in _bencode
hasnewline = (s[-1] == '\n')
TypeError: 'File' object does not support indexing
谁能帮我理解我做错了什么?