worthwhile / django-herald

A Django messaging library

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can't send mails with attachments

saranshbansal opened this issue · comments

I've been struggling for days to make it work but the lack of documentation and silent failures made it impossible to debug the issues. It seems that the mails are not being sent if I include an attachment in it.


def sendMail():
    SendThisMail(user, my_modal).send(user=my_user) # creates an error on this line as the file object is closed and inaccessible.

@registry.register_decorator()
class SendThisMail(SomeBaseClass, EmailNotification):
    def __init__(self, user, my_modal: models.MyModal):
        super().__init__(user, my_modal)

        self.subject = "abc"

        file = open('.staticfiles/assets/some.pdf', 'rb')

        self.attachments = [('attachment_1', File(file))]

        self.context = {
            **self.context,
            'subject': self.subject,
            'attachment': self.attachments,
        }

        self.to_emails = [user.email]

What's wrong with it?

Made it work after wasting 2 days!


@registry.register_decorator()
class SendThisMail(SomeBaseClass, EmailNotification):
    def __init__(self, user, my_modal: models.MyModal):
        super().__init__(user, my_modal)

        self.subject = "abc"

        file = open('docs/my.pdf', 'r').read() <- the magic code. Please document it well.

        self.attachments = [('abc.pdf', file, 'application/pdf')]

        self.context = {
            'subject': self.subject,
            **self.context,
        }

        self.to_emails = [user.email]

def sendMail():
    SendThisMail(user, my_modal).send(user=my_user)

In #58, you can now add attachments that are already closed, and herald will automatically open them again.