1

我正在尝试发送带有附件的电子邮件。我收到 IOError: [Errno 2] No such file or directory。但它说的网址不存在?嗯,它确实存在。表单正在上传文件,它生成的 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:

任何

4

2 回答 2

4

编辑 #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()
于 2013-06-05T19:23:03.090 回答
0

附件必须是文件系统上的文件,在Django 电子邮件文档中搜索 attach_file 。

因此,您可以链接到电子邮件中的文件 (URL),或者您可以下载文件、附加它,然后在本地删除它。

于 2013-05-03T20:09:43.383 回答