python實現發送和接收郵件功能主要用到poplib和smtplib模塊。
poplib用於接收郵件,而smtplib負責發送郵件。
代碼如下:
1 #! /usr/bin/env python 2 #coding=utf-8 3 import sys 4 import time 5 import poplib 6 import smtplib 7 #郵件發送函數 8 def send_mail(): 9 try: 10 handle = smtplib.SMTP('smtp.126.com',25) 11 handle.login('[email protected]','**********') 12 msg = 'To: [email protected]\r\nFrom:[email protected]\r\nSubject:hello\r\n' 13 handle.sendmail('[email protected]','[email protected]',msg) 14 handle.close() 15 return 1 16 except: 17 return 0 18 #郵件接收函數 19 def accpet_mail(): 20 try: 21 p=poplib.POP3('pop.126.com') 22 p.user('[email protected]') 23 p.pass_('**********') 24 ret = p.stat() #返回一個元組:(郵件數,郵件尺寸) 25 #p.retr('郵件號碼')方法返回一個元組:(狀態信息,郵件,郵件尺寸) 26 except poplib.error_proto,e: 27 print "Login failed:",e 28 sys.exit(1) 29 30 #運行當前文件時,執行sendmail和accpet_mail函數 31 if __name__ == "__main__": 32 send_mail() 33 accpet_mail()
本文首發於python黑洞網,csdn同步更新