python mail 关于 gmail 163 实例程序 支持正文汉字 和发送附件

声明:此文档只做学习交流使用,请勿用作其他商业用途

作者:朝阳_tony

邮箱:[email protected]

2013年6月23日 17:21:59 星期日

转载请注明出处:http://blog.csdn.net/linzhaolove

文章最后程序时间: 2013年6月23日 17:22:10 星期日


学习pyton mail 模块 记录了一个实例程序,支持gmail 和163区分账户发送;支持发送多人,抄送,正文汉字不乱码,发送人汉字姓名;还支持发送附件;


说一下编写这个程序遇到的问题:

1、163 邮件不能发送

目前发送163 的邮件需要ssl加密方式登录:

因此登录时要用下面的方式登录;

  1.     smtp = smtplib.SMTP_SSL(server) #163 mail  


而登录gmail要用下面这种方式

  1.     smtp = smtplib.SMTP(server)  
  2.     smtp.starttls() #gmail mail  

2、正文汉字乱码

正文乱码,需要添加下面的信息,默认的正文编码是us-acsii 格式,我们在linux下需要设置为utf-8

  •   msg["Accept-Language"]="zh-CN"  
  •   msg["Accept-Charset"]="ISO-8859-1,utf-8"  
  •      
  •   if isinstance(text,unicode):  
  •     text = str(text)  
  •   msg.attach( MIMEText(text,'plain','utf-8'))  

  • 整个实例代码:

    #!/usr/bin/env python
    #-*- encoding: UTF-8 -*-
    #gmail_report.py
    
    import sys, smtplib, base64, StringIO, os, string, time
    import re
    
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email.MIMEText import MIMEText
    from email.Utils import COMMASPACE, formatdate
    from email import Encoders
    from email.header import Header 
    
    def send_mail(send_people, send_from, send_to, cc_to,
                  subject, text, files=[], 
                  server="localhost", user = None, password = None):
      
      assert type(send_to)==list
      assert type(files)==list
    
      msg = MIMEMultipart()
      
      if send_people :
        me= ("%s<"+send_from+">") % (Header(send_people,'utf-8'),)
        msg['From'] = me
      else :
        msg['From'] = send_from
      #print "from pepole",send_people
    
      msg['To'] = COMMASPACE.join(send_to)
      msg['Cc'] = COMMASPACE.join(cc_to)
      send_to = send_to + cc_to # add cc_to to send_to
    
      if not isinstance(subject,unicode):
        subject = unicode(subject)
      msg['Subject'] = subject
    
      msg['Date'] = formatdate(localtime=True)
      msg["Accept-Language"]="zh-CN"
      msg["Accept-Charset"]="ISO-8859-1,utf-8"
       
      if isinstance(text,unicode):
        text = str(text)
      msg.attach( MIMEText(text,'plain','utf-8'))
    
      #add attach file
      for file in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(file,"rb").read() )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
        msg.attach(part)
    
    
      print "connect to %s" % server
      # check server 
      pattern = re.compile(r'smtp.163.com')
      match = pattern.match(server)
    
      if match:
        smtp = smtplib.SMTP_SSL(server) #163 mail
      else :
        smtp = smtplib.SMTP(server)
        smtp.starttls() #gmail mail 
    
      #print server
    
      if (user != None):
        smtp.ehlo()
        smtp_userid64 = base64.encodestring(user)
        smtp.docmd("auth", "login " + smtp_userid64[:-1])
      if password != None:
        smtp_pass64 = base64.encodestring(password)
        smtp.docmd(smtp_pass64[:-1])
      
      print "send mail form %s \n to %s" % (send_from,send_to)
      smtp.sendmail(send_from, send_to, msg.as_string())
      smtp.close()
    
      print "send mail ok"
    # 
    #  try:
    #    s = smtplib.SMTP(server)
    #    #s = smtplib.SMTP_SSL(server) #163 mail
    #    s.starttls() #gmail mail
    #    s.login(user,password)
    #    s.sendmail(me, send_to, msg.as_string())
    #    s.close()
    #    return True
    #  except Exception, e:
    #    print str(e)
    #    return False
    #
    #  
    #
    
    #gmail 
    # Credentials (if needed)  
    #username = 'mymail'  
    #password = 'mypass'  
    #server='smtp.gmail.com:587'
    
    # 163
    username='mymail'
    password='mypass'
    server= 'smtp.163.com:465'
    
    
    #send_people=''
    send_people="钢铁侠"
    
    #send_from='[email protected]'
    send_from='[email protected]'
    
    # send to sb
    send_to=['[email protected]','[email protected]']
    # copy to sb
    cc_to=['[email protected]']
    
    # mail title
    subject = u'钢铁侠发送邮件gmail test report'
    
    #text = u'this my test mail, you can ignore'
    text = """
        this my test mail, you can ignore,
    
        测试中文显示部分
        """
    # add file
    #file=[r'gmail_report.py',r'readme']
    file=[]
    
    send_mail(send_people, send_from,send_to,cc_to,
              subject, text, file,
              server, username, password)



  • 你可能感兴趣的:(linux,python,实例,Gmail)