PythonTip >> 博文 >> chinaunix

python smtplib sendEmail example

zihua 2014-03-27 18:03:41 点击: 943 | 收藏



  1. #!/usr/bin/python
  2. import getopt
  3. import os
  4. import smtplib
  5. import sys
  6. import time
  7. from email.mime.text import MIMEText
  8. from email.header import Header
  9. version=1.0

  10. def SendEmail(fromAdd, toAdd, subject, htmlText):
  11.     strFrom = fromAdd
  12.     strTo = toAdd;
  13.     msg =MIMEText(htmlText);
  14.     msg['Content-Type'] = 'Text/HTML';
  15.     msg['Subject'] = Header(subject,'utf-8');
  16.     msg['To'] = " ".join(strTo).replace(' ',';')
  17.     msg['From'] = strFrom;

  18.     print "htmlText:[",htmlText,"]"
  19.     print "msg=[",msg,"]"
  20.     smtp = smtplib.SMTP_SSL('smtp.qq.com',465);
  21.     #smtp.set_debuglevel(1)
  22.     smtp.login('test@qq.com','123456');
  23.     try:
  24.         smtp.sendmail(strFrom,strTo,msg.as_string());
  25.     finally:
  26.         smtp.close;
  27. def usage(bin):
  28.     print bin,version
  29.     print "-v --version"
  30.     print "-h --help"
  31.     print "-s --subject=<Your Mail Title> -f --message-file=<Your Mail Content>"
  32.         
  33. if __name__ == "__main__":
  34.     if len(sys.argv) < 2:
  35.         usage(sys.argv[0])
  36.         sys.exit(1)
  37.     try:
  38.         opts, args = getopt.getopt(sys.argv[1:], "hs:m:v", ["help", "subject=","message="])
  39.     except getopt.GetoptError as err:
  40.         print "help information and exit"
  41.         print str(err) # will print something like "option -a not recognized"
  42.         usage(sys.argv[0])
  43.             sys.exit(1)
  44.     subject = None
  45.     message = None
  46.     for o, a in opts:
  47.         if o == "-v":
  48.             print version
  49.             sys.exit(1)
  50.         elif o in ("-h", "--help"):
  51.             usage(sys.argv[0])
  52.             sys.exit(1)
  53.         elif o in ("-s", "--subject"):
  54.             subject = a
  55.         elif o in ("-f", "--message-file"):
  56.             message = a
  57.         else:
  58.             assert False, "unhandled option"
  59.         if len(sys.argv) < 3:
  60.             print "Usage:",sys.argv[0],"Subject Message"
  61.             sys.exit(1)
  62.     
  63.     f = open(message,'r')
  64.     data = f.read()
  65.     f.close()
  66.     if len(data) > 0:
  67.         tolist=["xiaomin@sina.com","zhangsan@gmail.com"]
  68.         SendEmail("test@qq.com",tolist,subject,data)

原文链接:http://blog.chinaunix.net/uid-16125873-id-4174851.html

作者:zihua | 分类: chinaunix | 标签: python | 阅读: 943 | 发布于: 2014-03-27 18时 |