Skip to content

Instantly share code, notes, and snippets.

@tuck1s
Created November 20, 2018 13:17
Show Gist options
  • Save tuck1s/31d417c433c0bb54ec381736013f6b2e to your computer and use it in GitHub Desktop.
Save tuck1s/31d417c433c0bb54ec381736013f6b2e to your computer and use it in GitHub Desktop.
Example Python smtplib with STARTTLS negotiation
try:
startT = time.time()
with SMTP(cfg['smtp_host'], port=cfg['smtp_port']) as smtp:
smtp.set_debuglevel(2) # Uncomment this if you wish to see the SMTP conversation / STARTLS neg.
smtp.ehlo(name='sparkpostSMIME')
if 'starttls' in smtp.esmtp_features:
smtp.starttls() # raises an exception if it fails. If continues, we're good
smtp.ehlo(name='sparkpostSMIME')
mode_str = 'STARTTLS'
else:
mode_str = 'plain'
if cfg['smtp_user'] and cfg['smtp_password']:
smtp.login(cfg['smtp_user'], cfg['smtp_password'])
print('Opened SMTP connection ({}) to {}, port {}, user="{}", password="{}"'.format(
mode_str,
cfg['smtp_host'],
cfg['smtp_port'],
cfg['smtp_user'],
'*' * len(cfg['smtp_password'])))
print('Sending {}\tFrom: {}\tTo: {} '.format(args.emlfile, msgOut.get('From'), msgOut.get('To')))
smtp.send_message(msgOut)
endT = time.time()
print('OK - in', round(endT - startT, 3), 'seconds')
except SMTPException as e:
print(e)
exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment