Python编程实现及时获取新邮件的方法示例
作者:liumengcheng 发布时间:2022-09-28 16:52:15
标签: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程序设计有所帮助。
来源:http://blog.csdn.net/liumengcheng/article/details/44961081
![](https://www.aspxhome.com/images/zang.png)
![](https://www.aspxhome.com/images/jiucuo.png)
猜你喜欢
- 环境:Python3.7依赖库:import datetimeimport randomimport requestsimport hash
- 下载tensorflow的代码地址:https://github.com/tensorflow/models.git然后进入目录:cd mo
- 今天发现sympy依赖的库mpmath里也有很多数学函数,其中也有在复平面绘制二维图的函数cplot,具体例子如下from mpmath i
- 假如你拥有一个庞大的网站,内容又多,那么来访者往往很难找到自己所需要的东东,这时候你就需要一个站内搜索来帮助来访者更快的找到索要的资料了!现
- 1、冒泡排序它反复访问要排序的元素列,并依次比较两个相邻的元素。如果顺序(如从大到小)错了,就交换它们。访问元素的工作是反复进行,直到没有相
- 一直以来,JS前端代码因为必须经过IE明文解析,某些加密的JS如:JScript.Encode也因为树大招风,早就被人破解了。还有些加密的手
- 本文介绍了使用XMlhttp技术来生成html页面,值得借鉴。相关函数:<% ’定义xmlhttp funct
- 引言:在Python3下运行Matplotlib之时,碰到了”No module named _tkinter“的问题,花费数小时进行研究解
- 1.下载pyinstaller并解压(可以去官网下载最新版):https://github.com/pyinstaller/pyinstal
- import webbrowser as webimport timeimport oscount=0while count<10:&
- 文件操作此为本人学习python过程中的笔记,将持续更新,欢迎提问指正。1.txt文件1.文本文件 txt2.二进制文件 图片视频操作流程打
- 我看见朋友可以把数据库的记录输出到页面表格上去,觉得很有用。这是怎么做的啊?见下:dbtable.asp<html><he
- pytest fixtures装饰器pytest中可以使用@pytest.fixture 装饰器来装饰一个方法,被装饰方法的方法名可以作为一
- 1 插件安装想要在vscode中使用jupyter,首先我们需要在vscode中安装插件Jupyter。在拓展中搜索jupyter直接安装即
- 网页情况爬取数据包含歌曲排名、歌手、歌曲名、歌曲时长python 代码import requests #请求网页获取网页数据 f
- 如下所示:#!/usr/bin/env pythonimport osimport sysclass CConsole: M_MAP_COL
- 在应用程序的开发中,有些输入信息是动态的,比如我们要注册一个员工的工作经历,比如下图如果做成死的,只能填写三个,如果是四个呢?或者更多呢,那
- 本文实例为大家分享了python地震数据可视化的具体代码,供大家参考,具体内容如下参考源码:seisplot准备工作:在windows10下
- 不得不说python的自制包的相关工具真是多且混乱,什么setuptools,什么distutils,什么wheel,什么egg!!怎么有这
- 在做数据库备份和还原数据库的时候出现"错误2812:未能找到存储过程’master.dbo.xp_fileexist’"