Last active
January 8, 2019 19:30
-
-
Save craigderington/d5e44d0c3fa9be150af6f3fa474ffbf2 to your computer and use it in GitHub Desktop.
Sending email with the Python standard 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 | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
# sender details | |
sender = 'alias@domain.org' | |
recipients = ['alias@domain.org', 'email2@domain.com', '3rdrecipients@outloo.com', ] | |
# create a MIME obj | |
msg = MIMEMultipart() | |
msg['From'] = sender | |
msg['To'] = ', '.join(recipients) | |
msg['Subject'] = 'Message Subject' | |
body = MIMEText('This is the body of the email message...') | |
msg.attach(body) | |
# format the message | |
text = msg.as_string() | |
# authentication | |
auth_user = 'alias@domain.org' | |
def prompt(prompt): | |
return input(prompt).strip() | |
def send_email(): | |
try: | |
s = smtplib.SMTP('smtp.gmail.com', 587) | |
s.set_debuglevel(0) | |
s.connect('smtp.gmail.com', 587) | |
s.ehlo() | |
s.starttls() | |
s.ehlo() | |
try: | |
s.login(auth_user, prompt('Enter Password:\n')) | |
print('SMTP Login successful') | |
try: | |
s.sendmail(sender, recipients, text) | |
s.quit() | |
print('Mail sent to {} successfully...'.format(str(recipients))) | |
except smtplib.SMTPRecipientsRefused as send_err: | |
print('Email recipients refused by the server: {}'.format(str(send_err))) | |
except smtplib.SMTPAuthenticationError as auth_err: | |
print('SMTP Authentication Error; {}'.format(str(auth_err))) | |
except smtplib.SMTPConnectError as smtp_err: | |
print('The server responded with an error: {}'.format(str(smtp_err))) | |
# call the function | |
send_email() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment