Last active
December 21, 2015 18:49
-
-
Save davidlonjon/6350081 to your computer and use it in GitHub Desktop.
Python: Send Email
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
def send_mail(sender='', recipients='', subject='', body='', server='localhost', port=25, username='', password=''): | |
if len(sender) == 0: | |
return { | |
'error': True, | |
'message': "Missing sender email address" | |
} | |
if len(recipients) == 0: | |
return { | |
'error': True, | |
'message': "Missing recipient email address(es)" | |
} | |
if len(subject) == 0: | |
return { | |
'error': True, | |
'message': "Missing email subject" | |
} | |
if len(body) == 0: | |
return { | |
'error': True, | |
'message': "Missing email body" | |
} | |
body = "" + body + "" | |
headers = ["From: " + sender, | |
"Subject: " + subject, | |
"To: " + recipients, | |
"MIME-Version: 1.0", | |
"Content-Type: text/html"] | |
headers = "\r\n".join(headers) | |
try: | |
smtp_session = smtplib.SMTP(server, port) | |
if port == 587 and len(username) > 0 and len(password) > 0: | |
smtp_session.ehlo() | |
smtp_session.starttls() | |
smtp_session.ehlo | |
smtp_session.login(username, password) | |
smtp_session.sendmail(sender, recipients, headers + "\r\n\r\n" + body) | |
smtp_session.close() | |
return { | |
'error': False, | |
'message': "email sent successfully" | |
} | |
except Exception, e: | |
raise |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment