Skip to content

Instantly share code, notes, and snippets.

@dldinternet
Forked from jamescalam/notify_smtp.py
Created May 18, 2020 16:16
Show Gist options
  • Save dldinternet/412cbeb130809eae790a6f3103b38987 to your computer and use it in GitHub Desktop.
Save dldinternet/412cbeb130809eae790a6f3103b38987 to your computer and use it in GitHub Desktop.
Function used to send a MIMEMultipart email object (msg) to your own email using Python's smtplib library.
import smtplib
import socket
def send(server='smtp-mail.outlook.com', port='587', msg):
# contain following in try-except in case of momentary network errors
try:
# initialise connection to email server, the default is Outlook
smtp = smtplib.SMTP(server, port)
# this is the 'Extended Hello' command, essentially greeting our SMTP or ESMTP server
smtp.ehlo()
# this is the 'Start Transport Layer Security' command, tells the server we will
# be communicating with TLS encryption
smtp.starttls()
# read email and password from file
with open('../data/email.txt', 'r') as fp:
email = fp.read()
with open('../data/password.txt', 'r') as fp:
pwd = fp.read()
# login to outlook server
smtp.login(email, pwd)
# send notification to self
smtp.sendmail(email, email, msg.as_string())
# disconnect from the server
smtp.quit()
except socket.gaierror:
print("Network connection error, email not sent.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment