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的print用法示例
Feb 11 Python
Python学习小技巧之利用字典的默认行为
May 20 Python
Python实现多并发访问网站功能示例
Jun 19 Python
Python中的defaultdict与__missing__()使用介绍
Feb 03 Python
Python正则表达式指南 推荐
Oct 09 Python
python将txt文件读入为np.array的方法
Oct 30 Python
django+echart绘制曲线图的方法示例
Nov 26 Python
python根据url地址下载小文件的实例
Dec 18 Python
python学习--使用QQ邮箱发送邮件代码实例
Apr 16 Python
Python+Django+MySQL实现基于Web版的增删改查的示例代码
May 13 Python
使用Django搭建网站实现商品分页功能
May 22 Python
python之django路由和视图案例教程
Jul 26 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长网址与短网址的实现方法
2017/10/13 PHP
javascript string字符串优化问题
2011/07/31 Javascript
Js注册协议倒计时的小例子
2013/06/24 Javascript
JS调试必备的5个debug技巧
2014/03/07 Javascript
Jquery性能优化详解
2014/05/15 Javascript
js实例属性和原型属性示例详解
2014/11/23 Javascript
理解javascript中的with关键字
2016/02/15 Javascript
深入理解JavaScript中为什么string可以拥有方法
2016/05/24 Javascript
学习Angular中作用域需要注意的坑
2016/08/17 Javascript
防止重复发送 Ajax 请求
2017/02/15 Javascript
jQuery实现获取选中复选框的值实例详解
2018/06/28 jQuery
微信小程序自定义底部弹出框
2020/11/16 Javascript
SVG实现时钟效果
2018/07/17 Javascript
vue集成百度UEditor富文本编辑器使用教程
2018/09/21 Javascript
一文快速详解前端框架 Vue 最强大的功能
2019/05/21 Javascript
详解node登录接口之密码错误限制次数(含代码)
2019/10/25 Javascript
原生JS利用transform实现banner的无限滚动示例代码
2020/06/15 Javascript
python实现图片批量剪切示例
2014/03/25 Python
Python实现批量修改文件名实例
2015/07/08 Python
pandas DataFrame数据转为list的方法
2018/04/11 Python
Python Tornado核心及相关原理详解
2020/06/24 Python
利用keras使用神经网络预测销量操作
2020/07/07 Python
python 列表推导和生成器表达式的使用
2021/02/01 Python
Html5+JS实现手机摇一摇功能
2015/04/24 HTML / CSS
Europcar葡萄牙:葡萄牙汽车和货车租赁
2017/10/13 全球购物
澳大利亚Rockwear官网:女子瑜伽、健身和运动服
2021/01/26 全球购物
Perfume’s Club美国官网:西班牙第一家在线美容店
2020/06/10 全球购物
Why do we need Unit test
2013/01/03 面试题
师范应届生语文教师求职信
2013/10/29 职场文书
团日活动策划书
2014/02/01 职场文书
创意婚礼策划方案
2014/05/18 职场文书
学校感恩节活动策划方案
2014/10/06 职场文书
2014年打非治违工作总结
2014/11/13 职场文书
2014年学校禁毒工作总结
2014/12/23 职场文书
OpenCV-Python实现轮廓拟合
2021/06/08 Python
springboot应用服务启动事件的监听实现
2022/04/06 Java/Android