"""Email Generation Logic. Handles email generation and delivery via Amazon's SES email service. """ import boto from boto import exception from flask import g from auth import config from auth import response from auth.models.email import Email MESSAGE_SES_AUTH_FAILED = 'SES Auth Failed: No Amazon Credentials Found' MESSAGE_SES_DELIVERY_FAILED = 'Email Failed for %s: %s' MESSAGE_SES_UNKNON_EXCEPTION = 'Unknown Email Exception %s for: %s' EMAIL_TITLE_FORGOTTEN_PASSWORD = 'Forgotten password reset' def deliver_email(email): """Deliver an email based on the email object provided. Args: email (Email): the email to send. Returns: response (tuple): message and status code """ ses = boto.connect_ses() result = response.Response() try: ses.send_email( email.sender, email.subject, email.to, text_body=email.text_body, html_body=email.html_body) except exception.NoAuthHandlerFound: result = response.create_fatal_response(MESSAGE_SES_AUTH_FAILED) g.log.critical(MESSAGE_SES_AUTH_FAILED) except exception.BotoServerError as e: message = MESSAGE_SES_DELIVERY_FAILED % (email.to, e.error_message) result = response.create_fatal_response(message=message) g.log.error(message) except Exception as e: message = MESSAGE_SES_UNKNON_EXCEPTION % (email.to, e) result = response.create_fatal_response(message) g.log.error(message) return result def forgot_password_notification(user, token): """Generate a forgot password email based on user and token provided. Args: user (User): User object to provide user's email address, name, etc. token (str): Token to be included in password reset URL. Returns: Email: Generated Email object. """ reset_url = '%s/reset/%s' % (config.APP_URL, token) return Email( to=user.email, subject=EMAIL_TITLE_FORGOTTEN_PASSWORD, text_body=reset_url, html_body=reset_url)