Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / 通过Python群发邮件并支持模板

需求:公司使用SVN,建立用户,密码,分配权限,为了保证安全性,密码随机生成并通过邮件发送给每个人资源:1、会一份表格,中有如下字段:mail, passwd, name, team, rank邮箱,密码,姓名,部门,职位2、邮件的模板:%s,您好:
系统为您分配了SVN用户名和密码
用户名:%s(即您的邮箱地址)
密  码:%s(系统自动分配,不能修改,系统将定期修改并发邮件给大家)....主要要带进去,姓名,邮箱地址,密码上代码:
  1. #! /usr/bin/env python      
  2. # -*- coding: utf-8 -*-      
  3. #@author jinqinghua@gmail.com     
  4. #@version 2012-02-22 09:20   
  5.   
  6. import time  
  7. import csv  
  8. import smtplib  
  9. from email.MIMEText import MIMEText  
  10. from email.MIMEMultipart import MIMEMultipart  
  11. from email.Header import Header  
  12.   
  13. mail_host = "smtp.xxx.cn"  
  14. mail_from = "from@xxx.cn"  
  15. mail_user = mail_from  
  16. mail_password = "不告诉你"  
  17. mail_subject = "[SVN密码通知]重要!此邮件请不要删除!"  
  18.   
  19. mail_template_file = "邮件模板.txt"  
  20. mail_password_file = "SVN密码.csv"  
  21.   
  22. def send_mail(mail_to, subject, body):  
  23.     msg = MIMEMultipart()  
  24.     msg["subject"] = Header(subject,"utf-8")   
  25.     msg["from"] = mail_from  
  26.     msg["to"] = mail_to  
  27.     msg["date"] = time.ctime()  
  28.     txt = MIMEText(body, "plain""utf-8")  
  29.     msg.attach(txt)  
  30.       
  31.     try:  
  32.         s = smtplib.SMTP()  
  33.         s.connect(mail_host)  
  34.         s.login(mail_user, mail_password)  
  35.         s.sendmail(mail_from, mail_to, msg.as_string())  
  36.         s.close()  
  37.         return True  
  38.     except Exception, e:  
  39.         print str(e)  
  40.         return False  
  41.       
  42. if __name__ == "__main__":  
  43.     subject = mail_subject  
  44.     content = open(mail_template_file).read()  
  45.     reader = csv.reader(open(mail_password_file))  
  46.     for mail, passwd, name, team, rank in reader:  
  47.         print mail, passwd, name.decode("utf-8"), team.decode("utf-8")  
  48.         body = content %(name, mail, passwd)  
  49.           
  50.         print "DEBUG:sending mail to %s" %(mail)  
  51.         if send_mail(mail, subject, body):  
  52.             print "INFO:success to send mail to %s" %(mail)  
  53.         else:  
  54.             print "ERROR:fail to send mail to %s" %(mail)  
  55.     print "done...python is great!"