Skip to content

Instantly share code, notes, and snippets.

@davidlenz
Created July 25, 2018 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidlenz/60f565fcfd415121e16ddeb5f3562df8 to your computer and use it in GitHub Desktop.
Save davidlenz/60f565fcfd415121e16ddeb5f3562df8 to your computer and use it in GitHub Desktop.
Send Emails using python.
#!/usr/bin/env python
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from smtplib import SMTP
import smtplib
subject = 'Example header'
message = 'Subject: Happy Australia Day!\nHi Everyone! Happy Australia Day! Cheers, Julian'
file = # some file on your disk
sender = '' # xxx@gmail.com
sender_pw = '' # your gmail pw
targets = [''] # list of comma-seperated email addresses
# When you get authentification error you might need to allow less secure apps in gmail:
# https://stackoverflow.com/questions/26852128/smtpauthenticationerror-when-sending-mail-using-gmail-and-python
def send_mail_with_attach(sender, sender_pw, targets, subject, message, file = None):
emaillist = [elem.strip().split(',') for elem in targets]
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender #'xxx@gmail.com'
msg['Reply-to'] = sender
msg.preamble = 'Multipart message.\n'
part = MIMEText(message)
msg.attach(part)
if file:
part = MIMEApplication(open(str(file),"rb").read())
part.add_header('Content-Disposition', 'attachment', filename=str(file))
msg.attach(part)
server = smtplib.SMTP("smtp.gmail.com:587")
server.ehlo()
server.starttls()
server.login(sender, sender_pw)
server.sendmail(msg['From'], emaillist , msg.as_string())
print('Successfully send email to {} with attachement {}'.format(emaillist, file))
send_mail_with_attach(sender, sender_pw, targets, subject, message, file = file)
send_mail_with_attach(sender, sender_pw, targets, subject, message, file = None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment