因为软工项目可能用到自动发邮件这个功能,所以先用python实现了一下,先不说别的,上代码。
EmailSender.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| import smtplib import sys import email.mime.text class GmailSender: def __init__(self,username,password): self.mail_username=username self.mail_password=password def sendEmail(self,to_addresslist,subject,content): HOST = 'smtp.gmail.com' PORT = 25 smtp = smtplib.SMTP() print 'connecting ...' try: print smtp.connect(HOST,PORT) except: print 'CONNECT ERROR ' smtp.starttls() try: print 'Loginning...' smtp.login(self.mail_username,self.mail_password) except: print 'Login Error' message=email.mime.text.MIMEText(""+content) message['From']=self.mail_username message['To']=';'.join(to_addresslist) message['subject']=""+subject print 'You message is '+message.as_string() smtp.sendmail(self.mail_username,to_addresslist,message.as_string()) smtp.quit()
|
接下来就是main.py了,执行发邮件的命令
1 2 3 4 5 6
| from EmailSender import* gs=GmailSender('***@gmail.com','***') to_list=('***@qq.com',) subject="haha" content="haha" gs.sendEmail(to_list,subject,content)
|
但是想查询自己的未读邮件怎么办呢?这里要注意一个问题,smtp协议是发送和接收的协议,pop和imap是查询邮件的协议,有的邮箱服务提供商不一定都支持pop和imap,但至少支持一个,现在一般都是imap。若是和我一样用的Gmail,那么最好是用imap协议查询,使用pop需要自己改很多东西。
支持Gmail的代码如下:
EmailChecker.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| import imaplib import email import string class GmailChecker: def __init__(self,username,password): self.username=username self.password=password def checkmail(self): server=imaplib.IMAP4_SSL('imap.gmail.com','993') try: print 'logining...' server.login(self.username,self.password) print '###login success###' except: print 'login fail' server.close() result,message=server.select() typ,data=server.search(None,'unseen') print ''+data[0] for num in string.split(data[0]): try: typ,dat=server.fetch(num,'(RFC822)') msg=email.message_from_string(dat[0][1]) print msg['From'] print msg['subject'] print msg['Date'] print '____________________________________' except Exception, e: print e gc=GmailChecker('***@gmail.com','*********') gc.checkmail()
|