Last active
May 1, 2016 21:29
-
-
Save andrew-azarov/dc17c1ad5d4f24f035bd0f9e63ca7563 to your computer and use it in GitHub Desktop.
Short and simple email function for python, easy to plug in into any scripts and run right away.
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 | |
# coding=utf8 | |
""" | |
Copyright (c) 2013 Azar-A Ltd., Azarov Andrew | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. | |
""" | |
import datetime | |
import smtplib | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
from email.header import Header | |
from email import Charset | |
# Add the general charset here, you can do the same in your script before | |
# running the module function to add your custom encodings for support | |
Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') | |
def send_email(messages_list, smtp_user=None, smtp_pass=None, tls=False, service_name=None, service_port=587, pre_hook=None, post_hook=None): | |
""" | |
Send plain text or text+html email | |
Keyword arguments: | |
messages_list -- required, a list of tuples in format: | |
( | |
[ | |
'To someone', - optional, nice name for To header | |
'[email protected]' - required, To header email address | |
], | |
[ | |
'From someone', - optional, nice name for From header | |
'[email protected]' - required, From header email address | |
], | |
'Subject', - required, can be empty string | |
'encoding', - required, must be preloaded with email.Charset.add_charset() function, for more information look into email module | |
[ | |
[ | |
'Text', - required, the text portion of the message, goes with text type to MIMEText function of email module | |
'encoding' - required, must be preloaded with email.Charset.add_charset() function, for more information look into email module | |
], | |
[ | |
'html', - required, the html portion of the message, goes with html type to MIMEText function of email module | |
'encoding' - required, must be preloaded with email.Charset.add_charset() function, for more information look into email module | |
] | |
] | |
) | |
smtp_user -- optional, for smtp login function | |
smtp_pass -- optional, for smtp login function | |
tls -- optional, whether establish secure connection over TLS | |
service_name -- required, server to connect to (ie mail.serverastra.com) | |
service_port -- optional, port (remember that default is 587 - submission port) | |
pre_hook -- optional, function to run before full email construction but after MIME classification, you can redefine it though, gets arguments of resulting MIME part and the input message pair. | |
post_hook -- optional, function to run after full email construction but before actual sending, same arguments as in pre_hook. | |
""" | |
failed = [] | |
try: | |
s = smtplib.SMTP(service_name, service_port) | |
s.ehlo() | |
if tls: | |
s.starttls() | |
s.ehlo() | |
if smtp_user and smtp_pass: | |
s.login(smtp_user, smtp_pass) | |
except: | |
traceback.print_exc() | |
print(x[0] + "ehlo failed") | |
failed = [x[0] for x in messages_list] | |
else: | |
for to_address, from_address, subject, encoding, mesg in messages_list: | |
try: | |
if len(mesg) == 2: | |
# 2 parts to the message - define as alternative to allow | |
# attachments | |
msg = MIMEMultipart('alternative') | |
else: | |
# 1 part - MIMEText part is applied right away | |
msg = MIMEText(mesg[0][0], 'plain', mesg[0][1]) | |
if pre_hook: | |
# Execute function before constructing email but after MIME | |
# classification, however you can redefine it or attach more | |
# parts. | |
msg = pre_hook(msg, mesg) | |
# Subject with general message encoding | |
msg['Subject'] = "%s" % Header(subject, encoding) | |
# Message address encoding | |
if len(from_address) == 2: | |
msg['From'] = "\"%s\" <%s>" % ( | |
Header(from_address[0], encoding), from_address[-1]) | |
else: | |
# No need to encode just the email address as it must be | |
# ASCII according to RFC | |
msg['From'] = from_address[-1] | |
if len(to_address) == 2: | |
msg['From'] = "\"%s\" <%s>" % ( | |
Header(to_address[0], encoding), to_address[-1]) | |
else: | |
# No need to encode just the email address as it must be | |
# ASCII according to RFC | |
msg['To'] = to_address[-1] | |
# Setting general message encoding | |
msg.set_charset(encoding) | |
if len(mesg) == 2: | |
# Preparing 2 parts - attaching both | |
part1 = MIMEText(mesg[0][0], 'plain', mesg[0][1]) | |
part2 = MIMEText(mesg[1][0], 'html', mesg[1][1]) | |
msg.attach(part1) | |
msg.attach(part2) | |
if post_hook: | |
# Execute function after constructing email and attaching | |
# parts but before sending. | |
msg = post_hook(msg, mesg) | |
# Final launch of email to the server | |
s.sendmail(from_address[-1], to_address[-1], msg.as_string()) | |
except: | |
traceback.print_exc() | |
failed.append(to_address[-1]) | |
try: | |
s.quit() | |
except: | |
# I don't care, I love it | |
pass | |
return failed | |
if __name__ == '__main__': | |
# Example use, might not work, as I did not test it and refactored | |
# blindly. Please accept my apologies and refine this GIST if you find an | |
# error, we use a bit less customizeable version which works fine from | |
# 2013. Have a nice day! | |
maillist = [] | |
maillist.append((['[email protected]'], ["Me", "[email protected]"], 'Subject', | |
'utf-8', [['text_message', 'utf-8'], ['html but you can delete this list item and it will become plain text', 'utf-8']])) | |
for k in send_email(maillist, smtp_user='[email protected]', smtp_pass='pwd', tls=True, service_name='mail-test.serverastra.com'): | |
print(k + 'not delivered') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment