473,322 Members | 1,401 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

Re: parsing incoming emails

Ahmed wrote...
I am working on a project where I need to parse incoming emails
(Microsoft outlook)
I'm not sure if you are able to bypass Outlook (and have Python fetch the
mail itself using poplib), but if you are, the following code might be
useful. I use this to pry apart emails which might contain multiple MIME parts.

from email.Parser import Parser
from rfc822 import parseaddr
import poplib
import smtplib

popserver="pop.site.com"
popuser="us**@site.com"
poppassword="secret"

# split a message into an header- and body part
def separate(msg):
if isinstance(msg,str):
msg=msg.split('\n')
emptyline=msg.index('')
return msg[:emptyline],msg[emptyline+1:]
# return a certain headerline from the headers
def headerline(header,tag="From: "):
for h in header:
if h.startswith(tag):
return h[len(tag)+1:]
return ""
# enumerate recursively the contents of a MIME message
# remember the first text/plain and text/html part(s) that is found
# also remember if any other parts were found (like attachments)
#
def enummimeparts(msg,extract,level=1,verbose=False):
m=Parser().parsestr(msg)
if m.is_multipart():
if verbose: print '\t'*level,'multipart'
for part in m.get_payload():
enummimeparts(part.as_string(),extract,level+1,ver bose)
else:
t=m.get_content_type()
if verbose: print '\t'*level,t
if t=="text/plain":
if not "text/plain" in extract:
headers,body=separate(m.as_string())
extract["text/plain"]='\n'.join(body)
else:
extract["others"]=True
elif t=="text/html":
if not "text/html" in extract:
headers,body=separate(m.as_string())
extract["text/html"]='\n'.join(body)
else:
extract["others"]=True
else:
extract["others"]=True
# extract the first 'text/plain' and 'text/html' mime-parts from a message
def extracttext(msg):
extract={}
enummimeparts(msg,extract)
return
extract.get("text/plain",None),extract.get("text/html",None),extract.get("ot
hers",False)
def processmessage(msgnr):
# get a message from the POP server, extract the parts
response,lines,bytes=pop.retr(msgnr)
msg='\n'.join(lines)
headers,body=separate(lines)
name,fromaddress=parseaddr(headerline(headers,"Fro m:"))
subject=headerline(headers,"Subject:")
logging.info(subject+" ("+fromaddress+")")
(plain,html,others)=extracttext(msg)
# prefer flat text; if not present in the message, fallback to HTML
content (if any)
texttoprocess=""
if plain:
texttoprocess=plain
elif html:
texttoprocess=html
# now do something useful with the text
processtext(texttoprocess)
# delete message from pop server after processing
pop.dele(msgnr)
# connect to the pop server and process all messages
logging.info("Checking pop server '%s', user '%s'" % (popserver,popuser))
pop=poplib.POP3(popserver)
pop.user(popuser)
pop.pass_(poppassword)
stat=pop.stat()
if stat[0]:
for n in range(stat[0]):
processmessage(n+1)
pop.quit()
--
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html

Jul 10 '08 #1
0 1677

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: simonc | last post by:
I've been programming in assembler and C/C++ for a number of years, but I'm only just starting down the road of PHP & MYSQL. I have a couple of questions: (1) Before I start writing my own...
2
by: Bob | last post by:
Hi Everybody A tough one!!! Is there any way that incoming eMails (MailItems) into Ms Outlook can be used to automatically create records in a ms Access table or sub table. Smiley Bob
2
by: Li-fan Chen | last post by:
Hi, We find ourselves in the unenviable position of creating an email reader, may I ask how we best parse incoming messages? Ideally we would point the parser at a email stored in a POP3--grab...
0
by: Li-fan Chen | last post by:
Hi, We work with email in a large CRM solution and one of the email-related tasks that has plagued us is our decision to make use of a 3rd-party local-sourcer to work on the parsing of inbound...
2
by: Terry Olsen | last post by:
I have a very interesting request. A customer receives orders via email. The email contains the shipping address, shipping method, email address and phone number. This information is not all...
2
by: =?Utf-8?B?RGFuY2Vy?= | last post by:
Hi, I was attempting to check my new incoming emails through Outlook Express (I have Windows 98, 2nd Edition). My computer seemed to be having a problem accessing and opening the emails, and the...
0
by: Terry Reedy | last post by:
You should be able to give Outlook a rule to call a program (your Python one) when the subject matches whatever. From Python, use the mail module to parse and the windows extensions to access...
0
by: Maric Michaud | last post by:
Le Monday 18 August 2008 12:43:02 Gabriel Genellina, vous avez écrit : escribió: Three options here : - dealing directly with outlook mailboxes files, I used some open source code to parse...
0
by: Ahmed, Shakir | last post by:
Thanks everyone who tried to help me to parse incoming email from an exchange server: Now, I am getting following error; I am not sure where I am doing wrong. I appreciate any help how to resolve...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.