Pylint for common/send_mail.py
authorLingchaox Xin <lingchaox.xin@intel.com>
Sun, 9 Jun 2013 03:17:07 +0000 (11:17 +0800)
committerLingchaox Xin <lingchaox.xin@intel.com>
Sun, 9 Jun 2013 05:49:48 +0000 (13:49 +0800)
The various uppercase names were renamed in Python 2.5. The base email
package's __init__.py does some tricks to make the old names work in
python, but because pylint has its own separate method of doing imports,
those tricks don't work in pylint. So obey pylint.

Change-Id: If03641ae94e7f1da34a2593913f80c2e5bc7034a

common/send_mail.py

index ce82295..5e15690 100644 (file)
@@ -1,17 +1,20 @@
 #!/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(',')
@@ -22,31 +25,33 @@ def prepare_mail(env_filename, subject, body, mail_from, mail_to, mail_cc = [],
 
     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).
@@ -61,7 +66,7 @@ def makemail(subject = '', body = '', from_email = None, to = [],
     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
@@ -69,7 +74,7 @@ def makemail(subject = '', body = '', from_email = None, to = [],
         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
@@ -82,18 +87,21 @@ def makemail(subject = '', body = '', from_email = None, to = [],
         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]
 
@@ -105,7 +113,8 @@ def makemail(subject = '', body = '', from_email = None, to = [],
         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)
@@ -113,9 +122,9 @@ def makemail(subject = '', body = '', from_email = None, to = [],
     # 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: