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 开发Activex组件方法
Nov 08 Python
python使用三角迭代计算圆周率PI的方法
Mar 20 Python
Python基于回溯法子集树模板实现图的遍历功能示例
Sep 05 Python
pygame实现雷电游戏雏形开发
Nov 20 Python
Python 处理图片像素点的实例
Jan 08 Python
浅谈pyqt5在QMainWindow中布局的问题
Jun 21 Python
Python银行系统实战源码
Oct 25 Python
简单了解Pandas缺失值处理方法
Nov 16 Python
Python连接SQLite数据库并进行增册改查操作方法详解
Feb 18 Python
python中if及if-else如何使用
Jun 02 Python
在keras 中获取张量 tensor 的维度大小实例
Jun 10 Python
python的html标准库
Apr 29 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 生成随机验证码图片代码
2010/02/08 PHP
PHP中include()与require()的区别说明
2010/03/10 PHP
从php核心代码分析require和include的区别
2011/01/02 PHP
php通过array_merge()函数合并两个数组的方法
2015/03/18 PHP
PHP随机生成信用卡卡号的方法
2015/03/23 PHP
PHP.ini安全配置检测工具pcc简单介绍
2015/07/02 PHP
PHP正则+Snoopy抓取框架实现的抓取淘宝店信誉功能实例
2017/05/17 PHP
php的优点总结 php有哪些优点
2019/07/19 PHP
解决html按钮切换绑定不同函数后点击时执行多次函数问题
2014/05/14 Javascript
项目实践一图片上传之form表单还是base64前端图片压缩(前端图片压缩)
2016/07/28 Javascript
微信小程序 实现tabs选项卡效果实例代码
2016/10/31 Javascript
浅谈jQuery中的$.extend方法来扩展JSON对象
2017/02/12 Javascript
JS基于正则表达式实现的密码强度验证功能示例
2017/09/21 Javascript
React.Js添加与删除onScroll事件的方法详解
2017/11/03 Javascript
vue组件中实现嵌套子组件案例
2020/08/31 Javascript
vue点击Dashboard不同内容 跳转到同一表格的实例
2020/11/13 Javascript
javascript实现前端分页功能
2020/11/26 Javascript
python发送邮件示例(支持中文邮件标题)
2014/02/16 Python
python中enumerate函数用法实例分析
2015/05/20 Python
Python获取当前路径实现代码
2017/05/08 Python
Python中的__slots__示例详解
2017/07/06 Python
python装饰器-限制函数调用次数的方法(10s调用一次)
2018/04/21 Python
Python3 SSH远程连接服务器的方法示例
2018/12/29 Python
python实现文件的分割与合并
2019/08/29 Python
150行python代码实现贪吃蛇游戏
2020/04/24 Python
keras的load_model实现加载含有参数的自定义模型
2020/06/22 Python
HTML5中视频音频的使用详解
2017/07/07 HTML / CSS
竞聘书格式及范文
2014/03/31 职场文书
商铺消防安全责任书
2014/07/29 职场文书
优秀党员先进事迹材料
2014/12/18 职场文书
一年级语文下册复习计划
2015/01/17 职场文书
师德师风主题教育活动总结
2015/05/07 职场文书
孔子观后感
2015/06/08 职场文书
同学聚会致辞集锦
2015/07/28 职场文书
医生行业员工的辞职信
2019/06/24 职场文书
话题作文之学会尊重
2019/12/16 职场文书