in output/mail.py [0:0]
def send_via_smtp(self, transport, mail, embedded_images, config):
if 'host' not in transport:
raise NotConfiguredException(
'No host configured for SMTP transport.')
port = int(transport['port']) if 'port' in transport else 25
self.logger.debug('Trying transport.',
extra={
'host': transport['host'],
'port': port
})
server = None
if 'verifyCertificate' in transport and transport[
'verifyCertificate'] is False:
context = ssl._create_unverified_context()
else:
context = ssl.create_default_context()
if 'ssl' in transport and transport['ssl']:
self.logger.debug('Using SSL connection for SMTP.')
server = smtplib.SMTP_SSL(transport['host'], port, context=context)
else:
server = smtplib.SMTP(transport['host'], port)
if 'starttls' in transport and transport['starttls']:
self.logger.debug('Using STARTTLS for SMTP.')
server.starttls(context=context)
if 'user' in transport and 'password' in transport:
self.logger.debug('Logging into SMTP server.')
server.login(transport['user'], transport['password'])
message = MIMEMultipart('alternative')
message['Subject'] = mail['mail_subject']
message['From'] = mail['mail_from']
message['To'] = mail['mail_to']
if mail['text_body'] != '':
text_part = MIMEText(mail['text_body'], 'plain')
message.attach(text_part)
if mail['html_body'] != '':
html_part = MIMEText(mail['html_body'], 'html')
message.attach(html_part)
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:
file_part = MIMEBase('application', 'octet-stream')
file_part.set_payload(content)
encoders.encode_base64(file_part)
file_part.add_header('Content-Disposition',
'attachment; filename="%s"' % filename)
self.logger.debug('Attached file.',
extra={
'attachment_filename': filename,
'attachment_size': len(content)
})
message.attach(file_part)
if len(embedded_images) > 0:
for file_name, content in embedded_images.items():
image = MIMEImage(content)
image.add_header('Content-ID', '<%s>' % file_name)
image.add_header(
'Content-Disposition', 'inline; filename="%s"; size="%d";' %
(file_name, len(content)))
message.attach(image)
parsed_recipients = []
try:
parsed_recipients = email.utils.getaddresses([mail['mail_to']],
strict=False)
except TypeError:
parsed_recipients = email.utils.getaddresses([mail['mail_to']])
recipients = []
for r in parsed_recipients:
recipients.append(r[1])
self.logger.debug('Sending email thru SMTP.',
extra={'recipients': recipients})
server.sendmail(mail['mail_from'], recipients, message.as_string())
server.quit()
return True