Python收发邮件示例(imaplib,smtplib)

时间:2022-12-24 18:10:30
 1 #-*- encoding: gbk -*-
 2 
 3 import imaplib
 4 import base64
 5 import email
 6 import globle_mysql
 7 import datetime
 8 # from email.mime.text import MIMEText 
 9 # import os, sys, string
10 import smtplib
11 from email.MIMEText import MIMEText
12 
13 mail_host="smtp.exmail.qq.com"            #使用的邮箱的smtp服务器地址,这里是163的smtp地址  
14 mail_user="username@domain"                           #用户名  
15 mail_pass="password"                             #密码  
16 mail_postfix="domain"  
17 def send_mail(to_list,sub,content):

19     msg = MIMEText(content,'plain',"utf-8")
20     msg['Subject'] = sub
21     msg['From'] = mail_user
22     msg['To'] = ";".join(to_list)                #将收件人列表以‘;’分隔  
23     try:
24         server = smtplib.SMTP()
25         server.connect(mail_host)                            #连接服务器  
26         server.login(mail_user,mail_pass)               #登录操作  
27         server.sendmail(mail_user, to_list, msg.as_string())
28         server.close()
29         return True
30     except Exception, e:
31         print str(e)
32         return False
33 def get_first_unread_email_title_body():  
34 
35     conn = imaplib.IMAP4_SSL("imap.exmail.qq.com")  
36     conn.login('username','password')  
37     t=conn.select('INBOX')  
38 
39     typ, data = conn.search(None,'ALL')
40     allMails=data[0].split(' ')
41     recentMails60=allMails[len(allMails)-200:]
42     recentMails60.sort(reverse=True) 
43     flag=0
44     for mailNum in recentMails60:
45 
46         typ, msg_data = conn.fetch(int(mailNum), '(RFC822)') 
47 
48         for response_part in msg_data:  
49             if isinstance(response_part, tuple):  
50                 msg = email.message_from_string(response_part[1]) #获取息体  
51                 
52                 if '0.2.0' in msg["Subject"] :
53                     flag+=1
54                     subject=msg["Subject"]
55                     msgDate=msg["Date"]
56                     payload=msg.get_payload()
57                     content=base64.decodestring(payload)
58                     if flag==1:
59                         content1=content
60                         msgDate1=msgDate
61                     elif flag==2:
62                         content2=content
63                         msgDate2=msgDate
64         if flag==2:
65             break
66 
67     print "finished!"
68     conn.close()
69     conn.logout()
70     return content1,msgDate1,content2,msgDate2
71 
72 msgText1,mailDate1,msgText2,mailDate2=get_first_unread_email_title_body()
73 mysql=globle_mysql.MysqlDao({"user":"username","pwd":"password","host":"ipaddr","name":"dbname","port":3306})
74 nowTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
75 for tablename in ('t1','t2'):
76     cids=mysql.select("SELECT GROUP_CONCAT(DISTINCT cid) FROM tablename WHERE create_user='monitor' AND create_time>TIMESTAMPADD(MINUTE ,-600,'%s') AND tablename='%s'"%(nowTime,tabname))
77     
78     info='%s\n'%tablename
79     if cid in cids:
80         cids=cids[0][0].split(',')
81     for cid in cids:
82         cid=cid.encode('gb18030')
83 
84         if cid in msgText1:        
85             info1=datetime.datetime.strptime(mailDate1[:-6],'%a,%d %b %Y %H:%M:%S')+' '+msgText1[msgText1.find(cid):]
86             info=info+info1[:info1.find('\n')]+'\n'
87         elif cid in msgText2:
88             info1=datetime.datetime.strptime(mailDate2[:-6],'%a,%d %b %Y %H:%M:%S')+' '+msgText2[msgText2.find(cid):]
89             info=info+info1[:info1.find('\n')]+'\n' 
90 
91 print info
92 mysql.release()
93 to_list=['username']
94 send_mail(to_list, 'mailSubject', info)