Created
July 25, 2018 09:40
-
-
Save davidlenz/60f565fcfd415121e16ddeb5f3562df8 to your computer and use it in GitHub Desktop.
Send Emails using python.
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
#!/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