Python中及時取得新郵件實作方法的程式碼案例
這篇文章主要介紹了Python編程實現及時獲取新郵件的方法,涉及Python實時查詢郵箱及郵件獲取相關操作技巧,需要的朋友可以參考下
本文實例講述了Python編程實現及時取得新郵件的方法。分享給大家參考,具體如下:
#-*- encoding: utf-8 -*- import sys import locale import poplib from email import parser import email import string import mysql.connector import traceback import datetime from mysql.connector import errorcode import time import re reload(sys); sys.setdefaultencoding('utf8'); # 确定运行环境的encoding __g_codeset = sys.getdefaultencoding() if "ascii"==__g_codeset: __g_codeset = 'utf8'; # def object2double(obj): if(obj==None or obj==""): return 0 else: return float(obj) #end if # def getMailIndex(): file = open('mailindex.txt',"r"); lines = file.readlines(); file.close(); return int(lines[0]); # def setMailIndex(index): f = open('mailindex.txt', 'w'); f.write(index); f.close(); # def utf8_to_mbs(s): return s.decode("utf-8").encode(__g_codeset) # def utf8_to_gbk(s): return s.decode("utf-8").encode('gb2312') # def mbs_to_utf8(s): return s.decode(__g_codeset).encode("utf-8") # def gbk_to_utf8(s): return s.decode('gb2312').encode("utf-8") # def _queryQuick(cu,sql,tuple): try: cu.execute(sql,tuple); rows = [] for row in cu: rows.append(row) # return rows except: print(traceback.format_exc()) #end # #获取信息 def _queryRows(cu,sql): try: cu.execute(sql) rows = [] for row in cu: rows.append(row) # return rows except: print(traceback.format_exc()) #end # #是否有新邮件 global hasNewMail; hasNewMail=True; #全局已读的邮件数量 global globalMailReaded; globalMailReaded=getMailIndex()+1; #获取新邮件 def getNewMail(conn2,cur2): try: global hasNewMail; global globalMailReaded; conn2.commit(); rows=_queryRows(cur2,"select count(*) as message_count from hm_messages where messageaccountid=1"); message_count=rows[0][0]; if(hasNewMail): print('read mailindex.txt') globalMailReaded=getMailIndex()+1; #end if if(message_count<=globalMailReaded): hasNewMail=False; #print('Did not receive new mail,continue wait...') return None;#没新邮件,直接返回 #end if #登陆邮箱 host = '127.0.0.1' username = 'username@myserver.net' password = 'password' pop_conn = poplib.POP3(host) #print pop_conn.getwelcome() pop_conn.user(username); pop_conn.pass_(password); #Get messages from server: messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)] # Concat message pieces: messages = ["\n".join(mssg[1]) for mssg in messages] #Parse message intom an email object: messages = [parser.Parser().parsestr(mssg) for mssg in messages] print("get new mail!"); print pop_conn.stat() print('%s readed mail count is %d,all mail count is: %d'%(datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S"),globalMailReaded,len(messages))) message = messages[globalMailReaded]; subject = message.get('subject') h = email.Header.Header(subject) dh = email.Header.decode_header(h) #subject = unicode(dh[0][0], dh[0][1]).encode('utf8') #print >> f, "Date: ", message["Date"] #print >> f, "From: ", email.utils.parseaddr(message.get('from'))[1] #print >> f, "To: ", email.utils.parseaddr(message.get('to'))[1] #print >> f, "Subject: ", subject j = 0 for part in message.walk(): j = j + 1 fileName = part.get_filename() contentType = part.get_content_type() mycode=part.get_content_charset(); # 保存附件 if fileName: pass; elif contentType == 'text/plain':# or contentType == 'text/html': #保存正文 data = part.get_payload(decode=True) content=str(data); if mycode=='gb2312': content= gbk_to_utf8(content) #end if content=content.replace(u'\u200d',''); setMailIndex(str(globalMailReaded)); hasNewMail=True; pop_conn.quit(); return (content,email.utils.parseaddr(message.get('from'))[1]); #end if #end for except: print("search hmailserver fail,try again"); return None; finally: pass; #end try #end def #连接数据库 conn2 = mysql.connector.connect(user='root', password='password',host='127.0.0.1',database='hmailserver',charset='gb2312'); cur2 = conn2.cursor(); #只要收到电子邮件,就把这个事件记录在事件库中 #现在就是循环查询邮箱,如果有新邮件就读取,并查询关键词库 while(True): mailtuple=getNewMail(conn2,cur2); if(mailtuple==None): #print('Did not search MySQL,continue loop...') time.sleep(0.5) continue; #end if (article,origin)=mailtuple; #end while
以上是Python中及時取得新郵件實作方法的程式碼案例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

VS Code可以在Windows 8上運行,但體驗可能不佳。首先確保系統已更新到最新補丁,然後下載與系統架構匹配的VS Code安裝包,按照提示安裝。安裝後,注意某些擴展程序可能與Windows 8不兼容,需要尋找替代擴展或在虛擬機中使用更新的Windows系統。安裝必要的擴展,檢查是否正常工作。儘管VS Code在Windows 8上可行,但建議升級到更新的Windows系統以獲得更好的開發體驗和安全保障。

VS Code 可用於編寫 Python,並提供許多功能,使其成為開發 Python 應用程序的理想工具。它允許用戶:安裝 Python 擴展,以獲得代碼補全、語法高亮和調試等功能。使用調試器逐步跟踪代碼,查找和修復錯誤。集成 Git,進行版本控制。使用代碼格式化工具,保持代碼一致性。使用 Linting 工具,提前發現潛在問題。

在 Notepad 中運行 Python 代碼需要安裝 Python 可執行文件和 NppExec 插件。安裝 Python 並為其添加 PATH 後,在 NppExec 插件中配置命令為“python”、參數為“{CURRENT_DIRECTORY}{FILE_NAME}”,即可在 Notepad 中通過快捷鍵“F6”運行 Python 代碼。

VS Code 擴展存在惡意風險,例如隱藏惡意代碼、利用漏洞、偽裝成合法擴展。識別惡意擴展的方法包括:檢查發布者、閱讀評論、檢查代碼、謹慎安裝。安全措施還包括:安全意識、良好習慣、定期更新和殺毒軟件。
