Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ''' Boilerplate for constructing an email with the Python SendGrid v3 API.
- Example Usage:
- mail = SendGridEmail(
- subject='Test Email',
- to_email='customer@email.com',
- from_email='test@superdupertest.com',
- html_template='test.html'
- )
- mail.apply_subs([
- ('-name-', 'jimmy'),
- ('-company-', 'JimbosJellyBeans'),
- ])
- mail.attach_item(
- file='test_file.txt',
- type_='text/plain',
- filename='Test File.txt',
- disposition='attachment',
- cid='TestFile'
- )
- response = mail.send()
- print(response)
- '''
- import base64
- import sendgrid
- from sendgrid.helpers.mail import \
- Email, Content, Mail, Substitution, Attachment
- from secrets import SENDGRID_API_KEY
- class SendGridEmail:
- ''' A basic SendGrid email object constructor.
- Parameters:
- subject (str): email title.
- from_email (str): address to use as the sender.
- to_email (str): address to send the email to.
- html_template (str): path to the HTML to use as the email body.
- Attributes:
- mail (Mail): a SendGrid Mail object.
- '''
- def __init__(self, subject, from_email, to_email, html_template):
- self.subject = subject
- self.to_email = Email(to_email)
- self.from_email = Email(from_email)
- self.html_template = html_template
- self.mail = self._create_mail()
- def _create_mail(self):
- ''' Creates basic SendGrid Mail object.'''
- html = open(self.html_template, 'r').read()
- content = Content(type_='text/html', value=html)
- return Mail(self.from_email, self.subject, self.to_email, content)
- def _encode_file(self, file):
- ''' Return file contents as base64 encoded.'''
- with open(file, 'rb') as f:
- data = f.read()
- f.close()
- encoded = base64.b64encode(data).decode()
- return encoded
- def attach_item(self, file, type_, filename, disposition, cid):
- ''' Attach an item to the Mail object.'''
- attachment = Attachment()
- endoded_report = self._encode_file(file)
- attachment.content = endoded_report
- attachment.type = type_
- attachment.filename = filename
- attachment.disposition = disposition
- attachment.content_id = cid
- self.mail.add_attachment(attachment)
- def apply_subs(self, subs):
- ''' Substitute template tags in the HTML with variables.'''
- for sub in subs:
- tag, value = sub
- self.mail.personalizations[0].add_substitution(
- Substitution(tag, value)
- )
- def send(self):
- sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)
- response = sg.client.mail.send.post(request_body=self.mail.get())
- status = response._status_code
- if not 200 <= status < 300:
- raise IOError('SendGrid response is {}'.format(status))
- return status
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement