Home > Net >  Send different attachment files such as picture, pdf, audio files, video files and zip files via ema
Send different attachment files such as picture, pdf, audio files, video files and zip files via ema

Time:08-05

I have a platform (e-commerce website) where I do upload different types of files and then I send them to users based on requests via email. I did try but get the following error:

FileNotFoundError at /some-url/[Errno 2] No such file or directory: 'http://127.0.0.1:8000/media/book_file/selfish_gene.pdf'

I got some help regarding sending pdf files via email but that one is not working as well. I do appreciate any guidance and help in advance regarding sending other files such as audio, picture, and video via email in Django.

Below I do provide a snippet of the code. Hope it helps.

Model:

class Book(models.Model):
 title           = models.CharField(max_length=255)
 author           = models.CharField(max_length=255)
 isbn           = models.CharField(max_length=255)
 page           = models.IntegerField(null=True, blank=True)


class BookFiles(models.Model):
 book = models.ForeignKey(Book, null=True, on_delete=models.SET_NULL)
 file = models.FileField(upload_to='book_file/', null=True, blank=True)

View:

def send_book(request):
 message = 'body of this email'
 subject= 'the subject of this email'
 recipient_email = '[email protected]'
 from_email = '[email protected]'
 email=EmailMessage(subject,message,from_email,[recipient_email])
 email.content_subtype='html'
 
 the_domain = request.build_absolute_uri('/')[:-1]
 book_object = Book.objects.get(title='Selfish Gene').bookfiles_set.all().first().file.url
 the_file=open(f'{the_domain}{book_object}',"r")
 email.attach("file_name.pdf", the_file.read(),'application/pdf')

 email.send()

CodePudding user response:

just remove the .url from book_object and send the book_object.read()

def send_book(request):
    subject= 'the subject of this email'
    message = 'body of this email'
    recipient_email = '[email protected]'
    from_email = '[email protected]'
    email=EmailMessage(subject,message,from_email,[recipient_email])
    email.content_subtype='html'

    # the_domain = request.build_absolute_uri('/')[:-1]
    book_object = Book.objects.get(title='Selfish Gene').bookfiles_set.all().first().file
    # the_file=open(f'{the_domain}{book_object}',"r")
    email.attach("file_name.pdf", book_object.read(),'application/pdf')

    email.send()

CodePudding user response:

Have you set the MEDIA_ROOT in your settings.py to the absolute path to where the files resides on the disk? And , if so, what is it set to?

As a reference to media settings in Django, have a look at this article: https://testdriven.io/blog/django-static-files/#media-files

  • Related