diff --git a/email/__init__.py b/email/__init__.py new file mode 100644 index 0000000..cc88c38 --- /dev/null +++ b/email/__init__.py @@ -0,0 +1,52 @@ +from __future__ import print_function +from flask import current_app +from googleapiclient.discovery import build +from apiclient import errors +import os +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText +import base64 +from google.oauth2 import service_account +from exceptions import EmailFailedException + + +def _login(): + """Logs in to the google API for emails""" + scopes = ['https://www.googleapis.com/auth/gmail.send'] + service_account_file = os.path.abspath(os.path.join(os.path.dirname(__file__), 'service-key.json')) + creds = service_account.Credentials.from_service_account_file(service_account_file, scopes=scopes) + delegated_creds = creds.with_subject(current_app.config['MAIL_USERNAME']) + service = build('gmail', 'v1', credentials=delegated_creds) + return service + + +def _create_message(subject, sender, recipient, txt_body, html_body): + message = MIMEMultipart('alternative') + message['To'] = recipient + message['From'] = sender + message['Subject'] = subject + message.attach(MIMEText(txt_body, 'plain')) + message.attach(MIMEText(html_body, 'html')) + return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode('utf-8')} + + +def send_email(subject, sender, recipient, txt_body, html_body): + """ + Sends an email using the google email API. + + Arguments: + subject (`str`): The subject text for the email. + sender (`str`): The email address of the sender. + recipient (`str`): The email address to send the email to. + txt_body (`str`): The plain text of the email. + html_body (`str`): The HTML of the email. + """ + service = _login() + message = _create_message(subject, sender, recipient, txt_body, html_body) + + try: + msg = (service.users().messages().send(userId='me', body=message).execute()) + print(f'Message ID: {msg["id"]}') + return msg + except errors.HttpError as error: + raise EmailFailedException(message=f'Failed to send message: {str(error)}') diff --git a/email/exceptions.py b/email/exceptions.py new file mode 100644 index 0000000..7581097 --- /dev/null +++ b/email/exceptions.py @@ -0,0 +1,5 @@ + +class EmailFailedException(Exception): + def __init__(self, message='Unable to send email', errors=None): + super().__init__(message) + self.errors = errors