python中的smtplib模組可以使用SMTP協議寄送電子郵件,
只要設定好郵件發送方,收件者,主題(可以為空白)和訊息(可以為空白),就可以把訊息發送到指定郵箱。
經過測試,比較方便。
測試代碼:
# MailClient class from smtplib import SMTPfrom time import *class MailClient: def __init__(self): self.SMTPServer = 'smtp.qq.com' #send server self.SvrSuffix = 'qq.com' self.user = 'username' #user name pnum = '12345678' #password self.sendSvr = SMTP(self.SMTPServer) self.log = self.sendSvr.login(self.user,pnum)#login the server #print 'connect to Mail Server successfully.' def SendMail(self,des, subj=None,info=None,PrintResult=False): ''' mail info to des through default server des: user@server.com subj:mail subject info:list or tuple of information to send PrintResult: whether print the send result ''' SrcInfo = 'From: '+self.user+'@'+self.SvrSuffix To = 'To: '+str(des) Sub = 'Subject: '+str(subj) Header = [SrcInfo,To,Sub] #mail header Msg = '\r\n\r\n'.join(['\r\n'.join(Header),'\r\n'.join(info)]) self.errs = self.sendSvr.sendmail(self.user+'@'+self.SvrSuffix,des,Msg) #self.sendSvr.quit() if PrintResult==False: return if(len(self.errs)!=0): print "error info : " for e in self.errs: print e," ",self.errs[e] return -1 else: print "send to ",des,":" for e in info: print " ",e print "successfully." return 0 def __del__(self): #print 'deconstructor' self.sendSvr.quit() #print 'MailClient disconnected.'if __name__=='__main__': b = time() mc = MailClient() s = 'null subject 2' Text = ('Hello from your friend ','Best wishes.') e = time() print 'time 1 ',e-b b=e mc.SendMail('xxx@qq.com',s,Text,True) e = time() print 'time 2 ',e-b b=e mc.SendMail('yyy@qq.com',s,Text*2,True) e = time() del mc print 'time cost ',e-b,'s.'
使用時先建立一個MailClient對象,然後調用該對象的SendMail方法(參數有:接收方,主題,訊息列表,列印發送結果開關)。
發送給不同的地址時只需要多次調用該方法。
【其實一次發送過程,內送郵件列表中接收地址也可以是多個,但是在測試時有一些問題,列表比較少(只有幾個)時沒問題,幾十個的時候伺服器就拒絕發送了。】
下面是一個測試代碼:
from time import *begin = time()##################################revr=[]##reveiveer listrevr.append('666666666@qq.com') #just for test start = 666666667num = 10while num>0: revr.append(str(start)+'@qq.com') start = start+1 num = num-1#for e in revr:# print efrom MailClient import *mc = MailClient()errmail=[]for user in revr: s = 'null subject' Text = ('Hello from your friend ','Best wishes.') try: mc.SendMail(user,s,Text) except: #print "exception at ",user errmail.append(user)del mcprint "Failed list(",len(errmail),"):"for e in errmail: print eend = time()print "time cost: ",(end-begin)," s."#sleep(10)
修改發送郵件個數,就可以給某個區段的所有QQ號碼發送郵件。手機垃圾簡訊、垃圾郵件,大致就是這個道理吧。