이 기사에서는 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

2 시간 이내에 Python의 기본 프로그래밍 개념과 기술을 배울 수 있습니다. 1. 변수 및 데이터 유형을 배우기, 2. 마스터 제어 흐름 (조건부 명세서 및 루프), 3. 기능의 정의 및 사용을 이해하십시오. 4. 간단한 예제 및 코드 스 니펫을 통해 Python 프로그래밍을 신속하게 시작하십시오.

Python은 웹 개발, 데이터 과학, 기계 학습, 자동화 및 스크립팅 분야에서 널리 사용됩니다. 1) 웹 개발에서 Django 및 Flask 프레임 워크는 개발 프로세스를 단순화합니다. 2) 데이터 과학 및 기계 학습 분야에서 Numpy, Pandas, Scikit-Learn 및 Tensorflow 라이브러리는 강력한 지원을 제공합니다. 3) 자동화 및 스크립팅 측면에서 Python은 자동화 된 테스트 및 시스템 관리와 같은 작업에 적합합니다.

2 시간 이내에 파이썬의 기본 사항을 배울 수 있습니다. 1. 변수 및 데이터 유형을 배우십시오. 이를 통해 간단한 파이썬 프로그램 작성을 시작하는 데 도움이됩니다.

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...

Python 3.6에 피클 파일로드 3.6 환경 보고서 오류 : modulenotfounderror : nomodulename ...

경치 좋은 스팟 댓글 분석에서 Jieba Word 세분화 문제를 해결하는 방법은 무엇입니까? 경치가 좋은 스팟 댓글 및 분석을 수행 할 때 종종 Jieba Word 세분화 도구를 사용하여 텍스트를 처리합니다 ...

정규 표현식을 사용하여 첫 번째 닫힌 태그와 정지와 일치하는 방법은 무엇입니까? HTML 또는 기타 마크 업 언어를 다룰 때는 정규 표현식이 종종 필요합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

드림위버 CS6
시각적 웹 개발 도구

뜨거운 주제



