首页 文章

Django通过附件发送电子邮件

提问于
浏览
0

我试图使用Django EmailMessage 类在邮件中发送一些文件

我要发送的文件附件在DB中,由每个用户在注册到我的站点时提供 .

我试过这个,但它不起作用

的myapp / views.py:

from django.core.mail import EmailMessage

def contactUber(request,id):
    user = User.objects.get(id=id)
    msg = EmailMessage(
        'Hello', #subject
        'Body goes here', #content
        'vitalysweb@gmail.com', #from
        ['uber@uber.com'] #to
        )
    msg.attach_file(user.profile.id_card.url) #the file that i want to attach
    msg.send()
    messages.success(request, "Email envoyé avec succes") #success msg
    return redirect(user_detail, id=str(id))

MYAPP /型号:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    birth_date = models.DateField(('Date de naissance'), null=True, blank=True)
    #DOCUMENTS TO UPLOAD
    id_card = models.FileField(('Carte Nationale d\'Identité'), upload_to='documents/CNI')
    drive_licence = models.FileField(('Permis de conduire'), upload_to='documents/RIB')
    uploaded_at = models.DateTimeField(('Ajouté le'), auto_now=True)
    docs_are_checked = models.BooleanField(('Documents validés'), default=False)

追溯:

Traceback (most recent call last):
  File "C:\venvs\env1\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
response = get_response(request)
  File "C:\venvs\env1\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
  File "C:\venvs\env1\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\djangoprojects\mysite\mysite\core\views.py", line 272, in contactUber
msg.attach_file(user.profile.id_card.url) #the file that i want to attach
  File "C:\venvs\env1\lib\site-packages\django\core\mail\message.py", line 394, in attach_file
with open(path, 'rb') as file:
FileNotFoundError: [Errno 2] No such file or directory: '/media/documents/CNI/1847635-2524541_FZLHlIr.jpg'
[16/Aug/2017 12:10:27] "GET /core/send_mail_uber/16/ HTTP/1.1" 500 73307

我的问题是:如何解决这个问题

1 回答

  • 0

    由于文件存储在您的数据库中,因此可能不会在此位置保存 /media/documents/CNI/1847635-2524541_FZLHlIr.jpg . 所以你需要做的是使用 attach() 方法指定文件名,数据,mimetype . 以下是它应该如何工作的示例:

    msg.attach(user.profile.id_card.name, user.profile.id_card.read(), user.profile.id_card.content_type)
    

    您可以在Django Docs阅读更多内容 . 寻找 attach() ,并知道它与 attach_file() 不同

    EDIT 1

    由于您在评论中提到 id_card 抛出错误,我假设您没有获取正确的模型 . 从我所看到的,我不确定你是否正确地做到了 . 您应该按以下方式获取 Profile 模型实例:

    someVar = Profile.objects.get(user=request.user) # assuming the current user is the one that you would like to be
    

    然后为了附加文件使用:

    msg.attach(someVar.id_card.name, someVar.id_card.read(), 'image/png') # assuming you will be attaching png's only
    

    希望这可以帮助!

相关问题