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
0
投稿
猜你喜欢
- python全代码如下import reimport csvimport matplotlib.pyplot as pltx=[]y=[]m
- Javascript刷新页面的几种方法: 1. history.go(0) 2. location.reload() 3. location
- __init__ 方法是什么?使用Python写过面向对象的代码的同学,可能对 __init__ 方法已经非常熟悉了,__init__ 方法
- 还是决定冠上ajax的头衔,毕竟很多人会用这个关键词搜索。虽然我认为这只是个炒作的概念,不过不得不承认ajax叫起来要方便多了。ajax的意
- 前言最近在研究怎么对图片资源进行无损压缩,网上也找了一些资料。总而言之,收获不少,所以想对最近的学习做个总结。无损压缩其实是相对而言的,目的
- 在之前的一篇文章我们已经介绍过替换python字典中的key值方法 ,本篇文章将作为那篇文章的补充。使用 dict.update() 方法替
- 本文实例为大家分享了使用countdown插件实现倒计时的具体代码,供大家参考,具体内容如下实现的效果如下:这里实现的是一个活动倒计时,获取
- Python for 循环语句Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。语法:for循环的语法格
- 一个SELECT查询中的LIKE语句来执行这种查询,尽管这种方法可行,但对于全文查找而言,这是一种效率极端低下的方法,尤其在处理大量数据的时
- 前言:SQLite属于轻型数据库,遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中。在很多嵌入式产品中使用了它,它占用资源非常
- Jupyter平台默认开发的字体为宋体,在高分屏下视觉效果差在 C:\User\用户名\.jupyter\custom下面的custom.c
- 在一众有趣的Python库中,TQDW也算是独树一帜了,原因主要是因为自身所存在的功能效果,比如我们如果在写项目,往往会忘记我们要完成多少量
- 工作需要开始学Perl,下载个Window版(5.16)的: 下载链接 http://www.activestate.com/activep
- 本章将覆盖所有在Python中使用的基本I/O功能。有关更多函数,请参考标准Python文档。打印到屏幕上:产生输出最简单的方法
- 如今WEB的安全问题影响着整个安全界,SQL注入,跨站脚本攻击等攻击受到了关注。 网络安全问题日益变的更加重要,国内依然有很多主机受到此类安
- 代码如下:---ntext数据类型字符替换 create table tt ( sid INT IDENTITY(1,1), c
- 一、前言三目运算符,又称条件运算符,是计算机语言(c,c++,java等)的重要组成部分。它是唯一有3个操作数的运算符,有时又称为三元运算符
- 本文实例讲述了Python列表切片操作。分享给大家供大家参考,具体如下:切片指的是列表的一部分。1 基本用法指定第一个元素和最后一个元素的索
- 我就废话不多说了,直接上代码吧!import cv2img = cv2.imread("1.jpg")b, g, r =
- 本文实例讲述了python求crc32值的方法。分享给大家供大家参考。具体实现方法如下:要想求CRC值,前面要import binascii