Sendgrid implementation



  • import sendgrid
    import os
    from sendgrid.helpers.mail import *
    from mail_config import *
    from jinja2 import FileSystemLoader, Environment
    
    class SendGridSingleMail():
        API_KEY = SEND_GRID_SETTINGS['API_KEY']
    
        def __init__(self, to_mail, from_mail, subject, template_path):
            """
            Constructor For Send Grid Mails
    
            :param to_mail: Mail Recipient
            :param from_mail: Mail Sender
            :param template_path: Email Path
            """
            self.to_mail = Email(to_mail)
            self.from_mail = Email(from_mail)
            self.subject = subject
            self.template_path = template_path
    
        def send_mail(self):
            """
            Send the email via send mail
    
            :return: Response from send mail
            """
            sg = sendgrid.SendGridAPIClient(api_key=self.API_KEY)
    
            mail_content = self.content()
    
            content = Content("text/html", mail_content)
    
            mail = Mail(self.from_mail, self.subject, self.to_mail, content)
    
            return sg.client.mail.send.post(request_body=mail.get())
    
        def set_placeholder_data(self, data):
            """
            set the data to be used by template
    
            :param data: object data
            """
            self.placeholder_data = data
    
        def render_from_template(self, template, data=None):
            """
            render jinja template
    
            :param template:
            :param data: data to render
            :return: template rendered to string
            """
            dir = os.path.dirname(os.path.abspath(__file__))
    
            template_dir = os.path.join(dir, 'templates')
    
            loader = FileSystemLoader(template_dir)
    
            env = Environment(loader=loader)
    
            template = env.get_template(template)
    
            if data:
                return template.render(data)
            else:
                return template.render({'dummy': 'dummy'})
    
        def content(self):
            """
            Creates the content for the html email
    
            :return: String representing the email template
            """
            if self.placeholder_data:
                return self.render_from_template(self.template_path, self.placeholder_data)
            else:
                return self.render_from_template(self.template_path)
    

    Wrote this for templated mails in Sendgrid.


Log in to reply
 

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.