Code example of how to get new emails in time in Python
This article mainly introduces the method of Python programming to achieve timely acquisition of new emails, involving Python real-time query mailbox and email acquisition related operation skills. Friends in need can refer to the following
The examples of this article describe the implementation of Python programming A way to get new emails in a timely manner. Share it with everyone for your reference, the details are as follows:
#-*- 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
The above is the detailed content of Code example of how to get new emails in time in Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
