我试图发送带附件的电子邮件。我收到IOError:[Errno 2]没有这样的文件或目录。但它说的网址并不存在?嗯,它确实存在。表单上传文件,它生成的FileField.url,Signature = ...& Expires = ...& AWSAccessKeyId =附加到结尾,当我在另一个窗口中调用它时,它可以正常工作。
我的Django应用程序使用Amazon-SES。我用send_mail()发送它们很好,但是这个包装器不支持附件,所以我在tasks.py中切换到了这个:
from django.core.mail.message import EmailMessage
from celery import task
import logging
from apps.profiles.models import Client
@task(name='send-email')
def send_published_article(sender, subject, body, attachment):
recipients = []
for client in Client.objects.all():
recipients.append(client.email)
email = EmailMessage(subject, body, sender, [recipients])
email.attach_file(attachment)
email.send()
我在form.save()
的视图中调用它from story.tasks import send_published_article
def add_article(request):
if request.method == 'POST':
form = ArticleForm(request.POST, request.FILES or None)
if form.is_valid():
article = form.save(commit=False)
article.author = request.user
article.save()
if article.is_published:
subject = article.title
body = article.text
attachment = article.docfile.url
send_published_article.delay(request.user.email,
subject,
body,
attachment)
return redirect(article)
else:
form = ArticleForm()
return render_to_response('story/article_form.html',
{ 'form': form },
context_instance=RequestContext(request))
以下是日志的内容:
app/celeryd.1: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/mail/message.py", line 268, in attach_file
app/celeryd.1: content = open(path, 'rb').read()
app/celeryd.1: IOError: [Errno 2] No such file or directory:
任何
答案 0 :(得分:1)
编辑#2 - 如果要使用.read()函数,则文件模式必须为'r'。
原因是“没有这样的文件或目录”是因为我忘了使用default_storage.open()。该文件与应用程序不在同一台计算机上,静态文件存储在AWS S3上。
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, 'r')
if docfile:
email.attach(docfile.name, docfile.read())
else:
pass
except:
pass
email.send()
答案 1 :(得分:0)
附件必须是文件系统上的文件,在Django e-mail documentation中搜索attach_file。
因此,您可以链接到电子邮件中的文件(URL),也可以下载该文件,然后将其附加,然后在本地删除。