Last active
April 17, 2021 11:12
-
-
Save austinwk/fdb7d6596183b6371a3b64871cc3fef7 to your computer and use it in GitHub Desktop.
Send an email using python builtins
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 | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
def main(): | |
# Sender's info | |
# Will vary depending on the client (gmail, outlook, etc) | |
address = '[email protected]' | |
host = 'smtp.office365.com' | |
port = 587 | |
password = 'password' | |
# Message and recipient info | |
to = '[email protected]' | |
subject = 'Test message' | |
text = 'This is a test message' | |
try: | |
# Establish a connection to the email server | |
connection = make_connection( | |
address=address, | |
host=host, | |
port=port, | |
password=password) | |
# Compose the email message | |
message = comopose_message( | |
sfrom=connection.user, | |
cc='', | |
bcc='', | |
to=to, | |
subject=subject, | |
text=text) | |
# Send the email messaage | |
send_message(connection, message) | |
except Exception as e: | |
print(e) | |
finally: | |
# Close the connection | |
connection.close() | |
# Establish a connection to the email server | |
def make_connection(address, host, port, password): | |
try: | |
connection = smtplib.SMTP(host=host, port=port) | |
connection.starttls() | |
connection.login(address, password) | |
return connection | |
# See smtplib documentation for possible error types | |
except Exception as e: | |
raise e | |
# Compose the email message | |
def comopose_message(sfrom, cc, bcc, to, subject, text): | |
try: | |
# Basic MIMEMultipart properties. See documentation for more details. | |
message = MIMEMultipart() | |
message['from'] = sfrom | |
message['cc'] = cc | |
message['bcc'] = bcc | |
message['to'] = to | |
message['subject'] = subject | |
# The body of the email is actually an attachment of a MIMEText object. | |
message.attach(MIMEText(text)) | |
return message | |
# See MIMEMultipart and MIMEText documentationn for possible error types | |
except Exception as e: | |
raise e | |
# Send the email message | |
def send_message(connection, message): | |
try: | |
connection.send_message(message) | |
# See smtplib documentation for possible error types | |
except Exception as e: | |
raise e | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment