Saiful Azad
Saiful Azad

Reputation: 1901

Django can not sent email with attachments

I am trying to sent email by using this code. But when I was trying. Either html or email attachment in sent. But not both. If I omit attachment email body is sent. but if I add attachment email body is not sent . Please someone provide you suggestion.

  msg = EmailMultiAlternatives(subject=self.mail_subject, from_email=from_mail, to=(to,),
                                         connection=connection)
            if isinstance(attachment, list):
                for attach_path in attachment:
                    msg.attach_file(attach_path)

            msg.attach_alternative(html_with_context_data, "text/html")
            try:
                msg.send(fail_silently=True)
            except:
                pass

Upvotes: 1

Views: 108

Answers (2)

Saiful Azad
Saiful Azad

Reputation: 1901

After spending 2 hours I have added only one line. Now I am getting both HTML and attachment.

msg.content_subtype = 'html'

Upvotes: 0

e4c5
e4c5

Reputation: 53734

With code like this what do you expect?

        try:
            msg.send(fail_silently=True)
        except:
            pass

You are telling django to fail silently which means it will not tell you if something goes wrong. And even if you switched off the silent mode, your exception handling is going to make sure that you never ever hear about it!!

Never do this

        except:
            pass

Always catch specific extensions, and on the rare cases that you need to catch generic exceptions like this, log it.

import traceback

except:
    traceback.print_exc()

Then you will see why exactly your attachment is not being sent.

(perhaps this should be a comment but it's far too long for that)

Upvotes: 1

Related Questions