python處理電子郵件

來源:互聯網
上載者:User

如果你有大量郵箱要批量處理他們的郵件 如果有手工處理一定會很慢

下面用python提供的郵件庫處理,

通過這個庫可以方便的發送和接收電子郵件 代碼很短

直接上代碼

發送代碼

 #!/usr/bin/env python<br /># -*- coding: gbk -*-<br />#匯入smtplib和MIMEText<br />import smtplib<br />from email.mime.text import MIMEText<br />#############<br />#要發給誰,這裡發給2個人<br />mailto_list=["aaa@qq.com","123456789@qq.com"]<br />#####################<br />#設定伺服器,使用者名稱、口令以及郵箱的尾碼<br />mail_host="smtp.qq.com"<br />mail_user="your qq"<br />mail_pass="password"<br />mail_postfix="qq.com"<br />######################<br />def send_mail(to_list,sub,content):<br /> '''<br /> to_list:發給誰<br /> sub:主題<br /> content:內容<br /> send_mail("aaa@126.com","sub","content")<br /> '''<br /> me=mail_user+"<"+mail_user+"@"+mail_postfix+">"<br /> msg = MIMEText(content)<br /> msg['Subject'] = sub #設定主題<br /> msg['From'] = me #寄件者<br /> msg['To'] = ";".join(to_list) #收件者<br /> try:<br /> s = smtplib.SMTP()<br /> s.connect(mail_host)<br /> s.login(mail_user,mail_pass)<br /> s.sendmail(me, to_list, msg.as_string())<br /> s.close()<br /> return True<br /> except Exception, e:<br /> print str(e)<br /> return False<br />if __name__ == '__main__':<br /> if send_mail(mailto_list,"subject","content"):<br /> print "發送成功"<br /> else:<br /> print "發送失敗"<br />

 

內送郵件 根據寄件者並提取出指定郵件

import poplib<br />import string<br />from email import parser</p><p>host = 'pop.qq.com'<br />username = 'your_qq@qq.com'<br />password = 'your_password'</p><p>pop_conn = poplib.POP3_SSL(host)<br />pop_conn.user(username)<br />pop_conn.pass_(password)</p><p>#從伺服器擷取郵件清單:<br />messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]</p><p># Concat message pieces:<br />messages = ["/n".join(mssg[1]) for mssg in messages]</p><p>#解析郵件到email object:<br />messages = [parser.Parser().parsestr(mssg) for mssg in messages]<br />for message in messages:<br /> addrfrom = str(message.get('from'))<br /> try:<br /> addrfrom.index('info@kingsoft.com')<br /> start_addr = addrfrom.index('<')<br /> end_addr = addrfrom.index('>')<br /> print addrfrom[start_addr + 1 : end_addr] #如果郵件是來自金山則列印他的標題<br /> except ValueError:<br /> continue<br />pop_conn.quit()

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.