这篇文章主要介绍了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实现获取及时邮件的方法的详细内容。
