in output/mail.py [0:0]
def send_via_sendgrid(self, transport, mail, embedded_images, config):
api_key = None
if 'apiKey' in transport:
api_key = transport['apiKey']
if os.getenv('SENDGRID_API_KEY'):
api_key = os.getenv('SENDGRID_API_KEY')
if not api_key:
raise NotConfiguredException('No Sendgrid API key configured!')
sg = sendgrid.SendGridAPIClient(api_key=api_key)
from_email = sendgrid.Email(mail['mail_from'])
to_email = sendgrid.To(mail['mail_to'])
text_content = None
if mail['text_body'] != '':
text_content = sendgrid.Content('text/plain', mail['text_body'])
sendgrid_mail = sendgrid.Mail(from_email, to_email,
mail['mail_subject'], text_content)
if 'sandbox' in transport and transport['sandbox']:
self.logger.info(
'Using Sendgrid sandbox mode (no emails will be sent).')
sendgrid_mail_settings = sendgrid.MailSettings(
sandbox_mode=SandBoxMode(True))
sendgrid_mail.mail_settings = sendgrid_mail_settings
if mail['html_body'] != '':
html_content = sendgrid.Content('text/html', mail['html_body'])
sendgrid_mail.add_content(html_content)
if len(embedded_images) > 0:
for file_name, content in embedded_images.items():
attachment = Attachment()
attachment.file_content = base64.b64encode(content).decode()
attachment.file_type = 'application/octet-stream'
attachment.file_name = file_name
attachment.disposition = 'inline'
attachment.content_id = file_name
sendgrid_mail.attachment = attachment
if 'attachments' in config['body']:
for attachment in config['body']['attachments']:
attachment_template = self.jinja_environment.from_string(
attachment)
attachment_template.name = 'attachment'
attachment_url = attachment_template.render()
self.logger.debug('Fetching attachment...',
extra={'attachment': attachment_url})
filename, content = self._get_attachment(attachment_url)
if filename:
attachment = Attachment()
attachment.file_content = base64.b64encode(content).decode()
attachment.file_type = 'application/octet-stream'
attachment.file_name = filename
attachment.disposition = 'attachment'
attachment.content_id = filename
sendgrid_mail.attachment = attachment
self.logger.debug('Attached file.',
extra={
'attachment_filename': filename,
'attachment_size': len(content)
})
self.logger.debug('Sending email through SendGrid.')
try:
response = sg.client.mail.send.post(
request_body=sendgrid_mail.get())
except exceptions.BadRequestsError as e:
self.logger.error('Failed to send via SendGrid (bad request).',
extra={'response': e.body})
raise e
if response.status_code >= 200 and response.status_code <= 299:
return True
return False