#!/usr/bin/env python
+""" A common used mail sender wrapper"""
+
import os
import smtplib
import base64
from email.mime.text import MIMEText
-from email.MIMEMultipart import MIMEMultipart
-from email.MIMEBase import MIMEBase
-from email import Encoders
-from email.Header import Header
-from email.Utils import parseaddr, formataddr
-
-def prepare_mail(env_filename, subject, body, mail_from, mail_to, mail_cc = [], mail_bcc = [], attachment = None):
+from email.mime.multipart import MIMEMultipart
+from email.mime.base import MIMEBase
+from email import encoders as Encoders
+from email.header import Header
+from email.utils import parseaddr, formataddr
+
+def prepare_mail(env_filename, subject, body, mail_from, mail_to, mail_cc = '',
+ mail_bcc = '', attachment = None):
""" Prepare a parameter inject file for mail sender job """
if type(mail_to) != list:
mail_to = mail_to.split(',')
mail_env = {}
- message = makemail(subject, body, from_email = mail_from, to = mail_to, cc = mail_cc, bcc = mail_bcc, attachment = attachment)
+ message = makemail(subject, body, from_email = mail_from, to_who = mail_to,
+ cc_who = mail_cc, bcc = mail_bcc, attachment = attachment)
mail_env['FROM'] = mail_from
mail_env['TO'] = ','.join(mail_to + mail_cc + mail_bcc)
mail_env['MESSAGE'] = base64.b64encode(message.as_string())
- with open(env_filename,'w') as f:
+ with open(env_filename,'w') as env_file:
for key in mail_env.keys():
- f.write('%s=%s\n' %(key, mail_env[key]))
+ env_file.write('%s=%s\n' %(key, mail_env[key]))
-def sendmail(from_email, to, msg, smtp_server):
+def sendmail(from_email, to_who, msg, smtp_server):
+ """The main sender method"""
- if type(to) != list:
- to = [to]
+ if type(to_who) != list:
+ to_who = [to_who]
try:
- s = smtplib.SMTP(smtp_server)
- s.sendmail(from_email, to, msg)
- s.quit()
- print "Email to %s sent succeeded" %(to)
- except smtplib.SMTPException, e:
- raise Exception, "Error: unable to send email: %s" % ( e )
+ smtp = smtplib.SMTP(smtp_server)
+ smtp.sendmail(from_email, to_who, msg)
+ smtp.quit()
+ print "Email to %s sent succeeded" % to_who
+ except smtplib.SMTPException, smtpe:
+ raise Exception, "Error: unable to send email: %s" % smtpe
-def makemail(subject = '', body = '', from_email = None, to = [],
- cc = [], bcc = [], attachment = None, extra_headers = None):
+def makemail(subject = '', body = '', from_email = None, to_who = (),
+ cc_who = (), bcc = (), attachment = None, extra_headers = None):
"""Send an email.
All arguments should be Unicode strings (plain ASCII works as well).
and UTF-8 that can represent all the characters occurring in the email.
"""
- def normalize_addr_header(hd):
+ def normalize_addr_header(hdsf):
""" Helper routine to normalize the charset of headersf """
# Header class is smart enough to try US-ASCII, then the charset we
header_charset = 'ISO-8859-1'
# Split real name (which is optional) and email address parts
- name, addr = parseaddr(hd)
+ name, addr = parseaddr(hdsf)
if name:
# We must always pass Unicode strings to Header, otherwise it will
return formataddr((name, addr))
# We must choose the body charset manually
- for body_charset in 'US-ASCII', 'UTF-8':
+ body_charset, charsets = '', ('US-ASCII', 'UTF-8')
+
+ for charset in charsets:
try:
- body.decode(body_charset)
+ body.decode(charset)
except UnicodeError:
pass
else:
+ body_charset = charset
break
- if type(to) != list:
- to = [to]
- if type(cc) != list:
- cc = [cc]
+ if type(to_who) != list:
+ to_who = [to_who]
+ if type(cc_who) != list:
+ cc_who = [cc_who]
if type(bcc) != list:
bcc = [bcc]
attach = MIMEBase('application',"octet-stream")
attach.set_payload(open(attachment, "rb").read())
Encoders.encode_base64(attach)
- attach.add_header("Content-Disposition", 'attachment; filename="%s"' %(os.path.basename(attachment)))
+ attach.add_header("Content-Disposition", 'attachment; filename="%s"' %
+ (os.path.basename(attachment)))
msg.attach(attach)
else:
msg = MIMEText(body, 'plain', body_charset)
# Normalize all headers
msg['Subject'] = Header(unicode(subject), 'ISO-8859-1')
msg['From'] = normalize_addr_header(from_email)
- msg['To'] = ','.join(map(normalize_addr_header, to))
- msg['Cc'] = ','.join(map(normalize_addr_header, cc))
- msg['Bcc'] = ','.join(map(normalize_addr_header, bcc))
+ msg['To'] = ','.join([normalize_addr_header(hdsf) for hdsf in to_who])
+ msg['Cc'] = ','.join([normalize_addr_header(hdsf) for hdsf in cc_who])
+ msg['Bcc'] = ','.join([normalize_addr_header(hdsf) for hdsf in bcc])
if extra_headers and isinstance(extra_headers, dict):
for k in extra_headers: