Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to extract email content in Python

Shulou Source: shulou.com Published: 2022-06-02 08:15:25 10月03日 Update

This article will explain in detail how to extract email content in Python. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

Basic information preparation

Import imaplib, email,re,requests,time,pymysqlimapserver = 'smtp.office365.com'emailuser = "qa.notice@shangri-la.com" emailpasswd = "test123"

# beta environment Zen address beta_loginhost= "http://zen.beta.com/index.php?m=user&f=login"beta_add_bughost="http://zen.beta.com/index.php?m=bug&f=create&productID=10&branch=0&extra=moduleID=0"

# live environment Zen address live_loginhost= "https://zen.live.com/index.php?m=user&f=login"live_add_bughost="https://zen.live.com/index.php?m=bug&f=create&productID=10&branch=0&extra=moduleID=0"

Envs= "live" # defines the environment to use

Database connection information

# Information related to connecting to the database: beta_dicts= {"HOST": '10.8.2.3 databases, "PORT": 3306, "USER":' zentao', "PASSWORD": 'test123', "NAME": "zentao"} live_dicts= {"HOST":' 10.7.1.7 records, "PORT": 3306, "USER": 'zentao', "PASSWORD":' test123', "NAME": "zentao"}

Database query

# Database query operation def executesql (query,envs): try: if (envs== "beta"): conn = pymysql.connect (beta_dicts ['HOST'], beta_dicts [' USER'], beta_dicts ['PASSWORD'], beta_dicts [' NAME'], int (beta_dicts ['PORT']), charset='utf8') print (beta_dicts) else: conn = pymysql.connect (live_dicts [' HOST'], live_dicts ['USER'], live_dicts [' PASSWORD'] Live_dicts ['NAME'], int (live_dicts [' PORT']), charset='utf8') print (live_dicts) cursor = conn.cursor () cursor.execute (query) result = cursor.fetchall () print If (len (result) = = 0): return 0 else: return result [0] [0] except Exception as e: print (e) print ("execute failed") finally: cursor.close () conn.close ()

Establish connection and retrieval

# email def search (): print ("start to connect") conn = imaplib.IMAP4_SSL (imapserver) conn.login (emailuser, emailpasswd) conn.select ('INBOX') # Select inbox (default) print (conn) now = time.localtime () nowt = time.strftime ("% d-%b-%Y", now) print (nowt) results, data = conn.search (None,' (FROM "Liang.Wu")' '(ON "+ str (nowt) +'") mailidlist = data [0] .split () print (mailidlist) try: for id in mailidlist: print (id) resultss, data = conn.fetch (id,'(RFC822)') # get the message through email id Data is the specific content of the message from fetch to e = email.message_from_bytes (data [0] [1])

Explanation and print

'' Header () class: email.header.Header (s=None, charset=None, maxlinelen=None, header_name=None, continuation_ws='', errors='strict') where the meaning of the parameter is understood as follows: s: the value of the header, that is, the value corresponding to From, To, Subject; charset: character set format, default is ASCII, but generally specify UTF-8 format to be compatible with more characters; header_name: header name, that is, From, To, Subject, Time, etc. '' subject = email.header.make_header (email.header.decode_header (e ['SUBJECT'])) mail_from = email.header.make_header (email.header.decode_header (e [From'])) print ("message subject is% s"% subject) print ("message from% s"% mail_from) body = str (get_body (e) Encoding='ISO-8859-1') # utf-8 gb2312 GB18030 parses Chinese, Japanese and English print ("email content is% s"% body) parse1 (body) print ("good job") except Exception as e: print ("we catch an errorcodes!", e) finally: print ("logout is success") print ("the finally of operationalization!") Conn.logout ()

Get message body information

# get email body information def get_body (msg): if msg.is_multipart (): # Return True if the message's payload is a list of sub-Message objects, otherwise return False. When is_multipart () returns False, the payload should be a string object. Return get_body (msg.get_payload (0)) else:''Return the current payload, which will be a list of Message objects when is_multipart () is True, or a string when is_multipart () is False. If the payload is a list and you mutate the list object, you modify the message's payload in place.''' Return msg.get_payload (None, decode=True)

Parse the content of the email and submit it to Zen

# parse email content and call Zen submission (combined with previous article) def parse1 (body): pattern = re.compile ('Dear Colleagues)

(. *) Thanks and Regards

', re.S) pattern1 = re.compile (' black "> (. *?), re.S) pattern2=re.compile (';" >\ r (. *?);\ r\ r'in resultlist [8] and';\ r

Tags: Email content information data database article more environment article body address character format knowledge previous query retrieval yes that is parameters Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Linux Docker OPPO Reno Shulou Information