2013-05-03 113 views
0

我试图发送带有附件的电子邮件。我得到IOError:[Errno 2]没有这样的文件或目录。但它所说的URL不存在?那么,它确实存在。表单正在上传文件,并生成FileField.url,其中签名= ... & Expires = ... & AWSAccessKeyId =追加到最后,当我在另一个窗口中调用它时起作用。用Django发送电子邮件与亚马逊SES,芹菜任务

我的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: 

任何

回答

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() 
0

附件必须是一个文件在您的文件系统上,搜索Django e-mail documentation中的attach_file。

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

+0

我知道如何把链接放在电子邮件中。我不知道我应该使用什么命令来下载文件,然后将其删除。有什么建议么?我读过[这个SO页面](http://stackoverflow.com/questions/908258/generating-file-to-download-with-django),并注意到很多cStringIO,会处理这种类型的任务? – 2013-05-07 13:27:57