用python去群发邮件

 经常在群里看到有群友问怎么用python发邮件,记得好最之前写过一个找了出来:

 1 #-*-coding:utf-8 -*-
 2 __author__ = 'DongJie'
 3 
 4 import MySQLdb
 5 import time
 6 import smtplib
 7 from email.mime.text import MIMEText
 8 
 9 #检测用户使用情况,如果用户超过两天未登录,发送邮件
10 
11 
12 class EmailConfig(object):
13     #邮件配置
14     HOST = "xxxxx"
15     USERNAME = "xxxxx"
16     DOMAIN = "xxxxx"
17     PASSWORD = "xxxxx"
18 
19 
20 #执行数据库操作
21 def exec_mysql(host, user, password, database, sql, port = 3306):
22     try:
23         conn = MySQLdb.connect(host = host,
24                                user = user,
25                                passwd = password,
26                                db = database,
27                                port = port,
28                                charset="utf8")
29         cur = conn.cursor()
30         if cur:
31             cur.execute(sql)
32             result = cur.fetchall()
33             return result
34     except MySQLdb.Error, e:
35         print "Mysql Error %d: %s" % (e.args[0], e.args[1])
36 
37 
38 class SendEmail(EmailConfig):
39     def __init__(self):
40         EmailConfig.__init__(self)
41 
42     def ToMail(self, mailto, subject, body, format='plain'):
43         if isinstance(body, unicode):
44             body = str(body)
45         me= u"系统管理员" + "<"+"xxxxxx"+">"
46         msg = MIMEText(body, format, 'utf-8')
47         if not isinstance(subject, unicode):
48             subject = str(subject)
49         if isinstance(mailto, list):
50             msg['To'] = ";".join(mailto)
51         else:
52             msg['To'] = mailto
53         msg['Subject'] = subject
54         msg['From'] = me
55         msg["Accept-Language"]="zh-CN"
56         msg["Accept-Charset"]="ISO-8859-1,utf-8"
57         try:
58             s = smtplib.SMTP()
59             s.connect(self.HOST)
60             s.login(self.USERNAME,self.PASSWORD)
61             s.sendmail(me, mailto, msg.as_string())
62             s.close()
63             return True
64         except Exception, e:
65             print str(e)
66             return False
67 
68 if __name__ == '__main__':
69     #获取长时间未登录人的
70     userInfo = exec_mysql("host", "user", "pwd", "db", "sql")
71     #取出邮件列表
72     emailList = [u[3] for u in userInfo if u[0]!= "admin"]
73     title = "xxxxxxxxxx"
74     comment = "xxxxx" 
75     SendEmail().ToMail(emailList, title, comment)

如果这不能满足你的要求,你可以看看这个:

http://www.cnblogs.com/xiaowuyi/archive/2012/03/17/2404015.html

posted @ 2015-06-29 10:59  流浪的如影  阅读(222)  评论(0)    收藏  举报