0

I tried to send some files in mail using Django EmailMessage class

The files attachment that I want to send are in DB, provided by each user during registration to my site.

I'have tried this but it does not work

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/models:

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:

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

My question is : How to fix this

VITALYS WEB
  • 759
  • 1
  • 8
  • 16

1 Answers1

0

Since the file is stored in your DB, it will probably not be saved /media/documents/CNI/1847635-2524541_FZLHlIr.jpg at this location. So what you have to do is specify the filename, data, mimetype using the attach() method. Here is an example of how it should work:

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

You can read more at Django Docs. Look for attach(), and know that it is different from attach_file()

EDIT 1

Since you mentioned in the comments that id_card throws an error, I am assuming you are not fetching the correct model. From what I can see I am unsure if you are doing it correctly. You should fetch the Profile model instance in the following way:

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

and then in order to attach the file use:

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

Hope this helps!

N. Ivanov
  • 1,795
  • 2
  • 15
  • 28
  • id_card is not defined (NameError) – VITALYS WEB Aug 16 '17 at 10:30
  • @VITALYSWEB I have updated my answer, should be `user.profile.id_card` if that doesn't work then you are probably not fetching the correct model. – N. Ivanov Aug 16 '17 at 10:31
  • @VITALYSWEB I have updated my answer look under **EDIT 1**. Hope this helps! – N. Ivanov Aug 16 '17 at 10:35
  • Now i'm having this error : AttributeError at /core/send_mail_uber/8/ 'FieldFile' object has no attribute 'content_type' Sorry to be so annoying, I'm a beginner in django – VITALYS WEB Aug 16 '17 at 10:40
  • @VITALYSWEB If you will be sending only images you can hardcode it like so `'image/png'`, and that should be the fastest workaround. I would suggest you to go over some django tutorials [Tango with Django](https://leanpub.com/tangowithdjango19/) is a free one, and will help you understand django more. Also may I ask you if this solved your problem, to upvote and mark the answer as accepted so that future visitors can solve their issue faster? Thanks! – N. Ivanov Aug 16 '17 at 10:52
  • thanx for the suggestion, for my i case i have to send both imageFiles and PDF. i'll try to get more informations about django Contentypes and look for a solution after – VITALYS WEB Aug 16 '17 at 10:59
  • a tip to get your emails up and running, you can split the filename and check the file extension (pdf, jpg, png) and have a dictionary like `myDict = {"pdf": "application/pdf", "png": "image/png"}`, and just call the dictionary with the given filename ending. Warning! this is not the best practice, but rather a workaround and a simple fix. Hope this helps! – N. Ivanov Aug 16 '17 at 11:01