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)}')