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 相关文章推荐
pytyon 带有重复的全排列
Aug 13 Python
Python 中 Virtualenv 和 pip 的简单用法详解
Aug 18 Python
Python学习之用pygal画世界地图实例
Dec 07 Python
numpy返回array中元素的index方法
Jun 27 Python
python解析含有重复key的json方法
Jan 22 Python
强悍的Python读取大文件的解决方案
Feb 16 Python
Python读取stdin方法实例
May 24 Python
详解利用OpenCV提取图像中的矩形区域(PPT屏幕等)
Jul 01 Python
使用pytorch搭建AlexNet操作(微调预训练模型及手动搭建)
Jan 18 Python
tensorflow 实现打印pb模型的所有节点
Jan 23 Python
Python 3.10 的首个 PEP 诞生,内置类型 zip() 迎来新特性(推荐)
Jul 03 Python
pycharm debug 断点调试心得分享
Apr 16 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
Codeigniter检测表单post数据的方法
2015/03/21 PHP
新浪微博OAuth认证和储存的主要过程详解
2015/03/27 PHP
关于php支持的协议与封装协议总结(推荐)
2017/11/17 PHP
浅谈PHP中的Trait使用方法
2019/03/22 PHP
Javascript里使用Dom操作Xml
2007/01/22 Javascript
window.location.hash 使用说明
2010/11/08 Javascript
Js+Flash实现访问剪切板操作
2012/11/20 Javascript
Node.js实现简单聊天服务器
2014/06/20 Javascript
JavaScript解析json格式数据简单示例
2014/12/09 Javascript
javascript数据类型示例分享
2015/01/19 Javascript
canvas红包照片实例分享
2017/02/28 Javascript
js实现颜色阶梯渐变效果(Gradient算法)
2017/03/21 Javascript
JS基于递归实现网页版计算器的方法分析
2017/12/20 Javascript
微信小程序实现简单表格
2019/02/14 Javascript
Vue插槽原理与用法详解
2019/03/05 Javascript
JS画布动态实现黑客帝国背景效果
2020/11/08 Javascript
在vue中给后台接口传的值为数组的格式代码
2020/11/12 Javascript
python定时检查启动某个exe程序适合检测exe是否挂了
2013/01/21 Python
Python编写生成验证码的脚本的教程
2015/05/04 Python
详解Python文本操作相关模块
2017/06/22 Python
Python实现的简单模板引擎功能示例
2017/09/02 Python
Python中__slots__属性介绍与基本使用方法
2018/09/05 Python
Python爬虫:Request Payload和Form Data的简单区别说明
2020/04/30 Python
Python环境搭建过程从安装到Hello World
2021/02/05 Python
css3实现圆锥渐变conic-gradient效果
2020/02/12 HTML / CSS
使用Vue.js和MJML创建响应式电子邮件
2021/03/23 Vue.js
研究生毕业鉴定
2014/01/29 职场文书
体现团队精神的口号
2014/06/06 职场文书
市场营销专业毕业生求职信
2014/07/21 职场文书
平安建设汇报材料
2014/12/29 职场文书
辩护词格式
2015/05/22 职场文书
指导老师鉴定意见
2015/06/05 职场文书
住房公积金贷款工资证明
2015/06/12 职场文书
迎国庆主题班会
2015/08/17 职场文书
解决python3安装pandas出错的问题
2021/05/20 Python
springboot + mongodb 通过经纬度坐标匹配平面区域的方法
2021/11/01 MongoDB