moki
moki

Reputation: 646

Django mail attachment is blank

I am trying to send a mail with an attachment using Django, the attached file is sent to the server from a user submitted form. My code is shown below

 form = RequestForm(request.POST, request.FILES)
 if form.is_valid():
        form.save()
        messages.info(request, '')
        subject = ''
        message = ""
        attachment = request.FILES['attachment']
        mail = EmailMessage(subject, message, '', [''])
        mail.attach(filename=attachment.name, mimetype=attachment.content_type, content=attachment.read())
        mail.send()

I am receiving the mail, but the attachment in the mail is blank, i.e it doesn't contain any content. What am I missing here?

Upvotes: 0

Views: 993

Answers (2)

moki
moki

Reputation: 646

I have solved the issue, I placed the form.save() at the bottom i.e after sending the mail and the issue resolved. This is because, once we use form.save() the attachment gets stored in its path and we need to open it before we read it.

form = RequestForm(request.POST, request.FILES)
if form.is_valid():
        messages.info(request, '')
        subject = ''
        message = ""
        attachment = request.FILES['attachment']
        mail = EmailMessage(subject, message, '', [''])
        mail.attach(filename=attachment.name, mimetype=attachment.content_type, content=attachment.read())
        mail.send()
        form.save()

Upvotes: 1

Stephen Delaney
Stephen Delaney

Reputation: 63

I believe you need to use attach_file instead of attach. attach_file allows you to pass a path, whereas you need to pass the actual data with attach. See docs.

Also, test that your attachment is actually getting uploaded, that you specified the right enctype on your form, etc. For example:

<form enctype="multipart/form-data" action="/whatever/" method="post">

Upvotes: 0

Related Questions