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类继承用法实例分析
May 27 Python
python实现判断数组是否包含指定元素的方法
Jul 15 Python
Mac中升级Python2.7到Python3.5步骤详解
Apr 27 Python
Python补齐字符串长度的实例
Nov 15 Python
python实现趣味图片字符化
Apr 30 Python
python中使用ctypes调用so传参设置遇到的问题及解决方法
Jun 19 Python
如何基于Python批量下载音乐
Nov 11 Python
python如何基于redis实现ip代理池
Jan 17 Python
django 实现手动存储文件到model的FileField
Mar 30 Python
Python开发.exe小工具的详细步骤
Jan 27 Python
Python Spyder 调出缩进对齐线的操作
Feb 26 Python
python3 sqlite3限制条件查询的操作
Apr 07 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 cookie 登录验证示例代码
2009/03/16 PHP
配置Apache2.2+PHP5+CakePHP1.2+MySQL5运行环境
2009/04/25 PHP
php猜单词游戏
2015/09/29 PHP
php验证码生成代码
2015/11/11 PHP
CI框架的安全性分析
2016/05/18 PHP
windows环境下使用Composer安装ThinkPHP5
2018/05/18 PHP
基于Laravel 多个中间件的执行顺序详解
2019/10/21 PHP
laravel 创建命令行命令的图文教程
2019/10/23 PHP
js弹出层(jQuery插件形式附带reLoad功能)
2013/04/12 Javascript
动态创建script标签实现跨域资源访问的方法介绍
2014/02/28 Javascript
JavaScript使用focus()设置焦点失败的解决方法
2014/09/03 Javascript
JavaScript实现自动弹出窗口并自动关闭窗口的方法
2015/08/06 Javascript
javascript图片预加载完整实例
2015/12/10 Javascript
JS实现焦点图轮播效果的方法详解
2016/12/19 Javascript
微信小程序 slider的简单实例
2017/04/19 Javascript
基于Vue+element-ui 的Table二次封装的实现
2018/07/20 Javascript
详解一个小实例理解js原型和继承
2019/04/24 Javascript
微信小程序实现折线图的示例代码
2019/06/07 Javascript
Vue 使用typescript如何优雅的调用swagger API
2020/09/01 Javascript
Python本地与全局命名空间用法实例
2015/06/16 Python
python基本语法练习实例
2017/09/19 Python
python复制列表时[:]和[::]之间有什么区别
2018/10/16 Python
python执行CMD指令,并获取返回的方法
2018/12/19 Python
PyQT实现菜单中的复制,全选和清空的功能的方法
2019/06/17 Python
浅谈Python协程
2020/06/17 Python
详解CSS3的图层阴影和文字阴影效果使用
2016/06/09 HTML / CSS
2014年3.15团委活动总结
2014/03/16 职场文书
求职信范文大全
2014/05/26 职场文书
保护地球的标语
2014/06/17 职场文书
不服从上级领导安排的检讨书
2014/09/14 职场文书
购房协议书范本
2014/10/02 职场文书
民事撤诉申请书范本
2015/05/18 职场文书
入党宣誓仪式主持词
2015/06/29 职场文书
排球赛新闻稿
2015/07/17 职场文书
springboot+WebMagic+MyBatis爬虫框架的使用
2021/08/07 Java/Android
深入理解mysql事务隔离级别和存储引擎
2022/04/12 MySQL