Python编程实现及时获取新邮件的方法示例


Posted in Python onAugust 10, 2017

本文实例讲述了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相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Python入门篇之字符串
Oct 17 Python
Python爬取读者并制作成PDF
Mar 10 Python
Python下的Softmax回归函数的实现方法(推荐)
Jan 26 Python
Python简单的制作图片验证码实例
May 31 Python
详解用python实现基本的学生管理系统(文件存储版)(python3)
Apr 25 Python
详解python函数的闭包问题(内部函数与外部函数详述)
May 17 Python
Python从list类型、range()序列简单认识类(class)【可迭代】
May 31 Python
Python代码实现http/https代理服务器的脚本
Aug 12 Python
python网络编程之多线程同时接受和发送
Sep 03 Python
Django cookie和session的应用场景及如何使用
Apr 29 Python
Python爬虫基础初探selenium
May 31 Python
详解Python描述符的工作原理
Jun 11 Python
Python中函数eval和ast.literal_eval的区别详解
Aug 10 #Python
Python基础之getpass模块详细介绍
Aug 10 #Python
Python中字典(dict)合并的四种方法总结
Aug 10 #Python
详解Python 模拟实现生产者消费者模式的实例
Aug 10 #Python
Python 操作文件的基本方法总结
Aug 10 #Python
Python 模拟登陆的两种实现方法
Aug 10 #Python
Python 网页解析HTMLParse的实例详解
Aug 10 #Python
You might like
PHP中的函数嵌套层数限制分析
2011/06/13 PHP
PHP文件注释标记及规范小结
2012/04/01 PHP
PHP计算数组中值的和与乘积的方法(array_sum与array_product函数)
2016/04/01 PHP
PHP生成可点击刷新的验证码简单示例
2016/05/13 PHP
学习PHP Cookie处理函数
2016/08/09 PHP
php mysql procedure实现获取多个结果集的方法【基于thinkPHP】
2016/11/09 PHP
深入理解PHP的远程多会话调试
2017/09/21 PHP
Laravel框架基于ajax实现二级联动功能示例
2019/01/17 PHP
微信公众平台开发教程⑥ 微信开发集成类的使用图文详解
2019/04/10 PHP
Laravel5.7 Eloquent ORM快速入门详解
2019/04/12 PHP
如何用javascript控制上传文件的大小
2006/10/26 Javascript
Javascript 判断函数类型完美解决方案
2009/09/02 Javascript
js 实现复制到粘贴板的功能代码
2010/05/13 Javascript
深入理解JavaScript定时机制
2010/10/29 Javascript
jQuery提示插件alertify使用指南
2015/04/21 Javascript
JS实现霓虹灯文字效果的方法
2015/08/06 Javascript
HTML5 Shiv完美解决IE(IE6/IE7/IE8)不兼容HTML5标签的方法
2015/11/25 Javascript
jQuery设置Cookie及删除Cookie实例分析
2016/04/15 Javascript
实例讲解JavaScript中call、apply、bind方法的异同
2016/09/13 Javascript
浅谈Vue-cli 命令行工具分析
2017/11/22 Javascript
JS实现的进制转换,浮点数相加,数字判断操作示例
2019/11/09 Javascript
nodejs对mongodb数据库的增加修删该查实例代码
2020/01/05 NodeJs
Python实现求两个csv文件交集的方法
2017/09/06 Python
Python设计模式之观察者模式原理与用法详解
2019/01/16 Python
python读取word 中指定位置的表格及表格数据
2019/10/23 Python
Python如何使用27行代码绘制星星图
2020/07/20 Python
解决Pymongo insert时会自动添加_id的问题
2020/12/05 Python
各大浏览器 CSS3 和 HTML5 兼容速查表 图文
2010/04/01 HTML / CSS
深入浅出CSS3 background-clip,background-origin和border-image教程
2011/01/27 HTML / CSS
使用canvas压缩图片上传的方法示例
2020/02/07 HTML / CSS
Square Off美国/加拿大:世界上最聪明的国际象棋棋盘
2018/12/06 全球购物
Microsoft Advertising美国:微软搜索广告
2019/05/01 全球购物
.NET remoting的两种通道是什么
2016/05/31 面试题
国贸类专业毕业生的求职信分享
2013/12/08 职场文书
给校长的建议书300字
2014/05/16 职场文书
车辆年检委托书范本
2014/10/14 职场文书