mail.py 1.19 KB
Newer Older
Jed Simson's avatar
Jed Simson committed
1 2 3 4 5
import sendgrid
from sendgrid.helpers.mail import Email, Content, Mail
import threading
import os

Jed Simson's avatar
Jed Simson committed
6
class Mailer(object):
Jed Simson's avatar
Jed Simson committed
7

8 9 10
    def __init__(self, api_key, default_from):
        self.api_key = api_key
        self.default_from = default_from
Jed Simson's avatar
Jed Simson committed
11

12
    def send_email(self, to, subject, template):
13
        sg = sendgrid.SendGridAPIClient(apikey=self.api_key)
14
        message = self.create_message(to, subject, template)
Jed Simson's avatar
Jed Simson committed
15

16 17
        def send_message(message):
            response = sg.client.mail.send.post(request_body=message.get())
Jed Simson's avatar
Jed Simson committed
18

19 20
            print('Email response status: {}'.format(response.status_code))
            return response.status_code == 200
Jed Simson's avatar
Jed Simson committed
21

22 23 24 25
        sender = threading.Thread(name='mail_sender',
                                  target=send_message,
                                  args=(message,))
        sender.start()
Jed Simson's avatar
Jed Simson committed
26

27 28 29 30 31
    def create_message(self, to, subject, template):
        from_email = Email(self.default_from)
        to_email = Email(to)
        content = Content('text/html', template)
        message = Mail(from_email, subject, to_email, content)
Jed Simson's avatar
Jed Simson committed
32

33
        return message
Jed Simson's avatar
Jed Simson committed
34

Jed Simson's avatar
Jed Simson committed
35
email_manager = Mailer(
36 37 38
    api_key=os.environ['SENDGRID_API_KEY'],
    default_from=os.environ['SENDGRID_DEFAULT_FROM']
)