Created
November 20, 2018 13:17
-
-
Save tuck1s/31d417c433c0bb54ec381736013f6b2e to your computer and use it in GitHub Desktop.
Example Python smtplib with STARTTLS negotiation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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