Last active
June 3, 2020 08:15
-
-
Save jamescalam/a2771e6e6c2cc013e7305e3a65b814de 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.
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
import smtplib | |
import socket | |
def send(msg, server='smtp-mail.outlook.com', port='587'): | |
# 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