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

发布时间 - 2026-01-11 02:44:02    点击率:

本文实例讲述了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实现读取邮箱中的邮件功能示例【含文本及附件】  # 在Python中使用poplib模块收取邮件的教程  # 简单实现python收发邮件功能  # Python实现发送与接收邮件的方法详解  # Python获取邮件地址的方法  # 详解python实现读取邮件数据并下载附件的实例  # Python读取指定日期邮件的实例  # 进阶  # 操作技巧  # 运行环境  # 相关内容  # 数据结构  # 就把  # 给大家  # 更多关于  # 所述  # 程序设计  # 使用技巧  # 已读  # 库中  # 连接数据库  # 电子邮件  # 编程技巧  # 讲述了  # utf8_to_gbk  # _queryQuick 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: javascript日期怎么处理_如何格式化输出  Android自定义listview布局实现上拉加载下拉刷新功能  详解CentOS6.5 安装 MySQL5.1.71的方法  零基础网站服务器架设实战:轻量应用与域名解析配置指南  英语简历制作免费网站推荐,如何将简历翻译成英文?  如何在万网自助建站平台快速创建网站?  Laravel如何生成URL和重定向?(路由助手函数)  Win11怎么恢复误删照片_Win11数据恢复工具使用【推荐】  浅谈Javascript中的Label语句  潮流网站制作头像软件下载,适合母子的网名有哪些?  如何实现建站之星域名转发设置?  Laravel控制器是什么_Laravel MVC架构中Controller的作用与实践  javascript读取文本节点方法小结  浅谈redis在项目中的应用  Windows Hello人脸识别突然无法使用  rsync同步时出现rsync: failed to set times on “xxxx”: Operation not permitted  Laravel怎么发送邮件_Laravel Mail类SMTP配置教程  Java类加载基本过程详细介绍  SQL查询语句优化的实用方法总结  如何在阿里云通过域名搭建网站?  济南网站建设制作公司,室内设计网站一般都有哪些功能?  Laravel请求验证怎么写_Laravel Validator自定义表单验证规则教程  php嵌入式断网后怎么恢复_php检测网络重连并恢复硬件控制【操作】  如何为不同团队 ID 动态生成多个“认领值班”按钮  浅谈javascript alert和confirm的美化  什么是JavaScript解构赋值_解构赋值有哪些实用技巧  Laravel如何记录日志_Laravel Logging系统配置与自定义日志通道  JavaScript常见的五种数组去重的方式  Laravel如何使用Guzzle调用外部接口_Laravel发起HTTP请求与JSON数据解析【详解】  谷歌浏览器如何更改浏览器主题 Google Chrome主题设置教程  如何在局域网内绑定自建网站域名?  jquery插件bootstrapValidator表单验证详解  JavaScript模板引擎Template.js使用详解  Python面向对象测试方法_mock解析【教程】  网站制作公司哪里好做,成都网站制作公司哪家做得比较好,更正规?  品牌网站制作公司有哪些,买正品品牌一般去哪个网站买?  购物网站制作费用多少,开办网上购物网站,需要办理哪些手续?  Android Socket接口实现即时通讯实例代码  夸克浏览器网页跳转延迟怎么办 夸克浏览器跳转优化  手机钓鱼网站怎么制作视频,怎样拦截钓鱼网站。怎么办?  Laravel Session怎么存储_Laravel Session驱动配置详解  Laravel如何处理跨站请求伪造(CSRF)保护_Laravel表单安全机制与令牌校验  Laravel如何使用Service Provider服务提供者_Laravel依赖注入与容器绑定【深度】  哪家制作企业网站好,开办像阿里巴巴那样的网络公司和网站要怎么做?  美食网站链接制作教程视频,哪个教做美食的网站比较专业点?  Laravel如何配置任务调度?(Cron Job示例)  Laravel怎么配置.env环境变量_Laravel生产环境敏感数据保护与读取【方法】  如何在云主机快速搭建网站站点?  JS去除重复并统计数量的实现方法  Laravel怎么防止CSRF攻击_Laravel CSRF保护中间件原理与实践