473,782 Members | 2,623 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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**@s ite.com"
poppassword="se cret"

# split a message into an header- and body part
def separate(msg):
if isinstance(msg, str):
msg=msg.split(' \n')
emptyline=msg.i ndex('')
return msg[:emptyline],msg[emptyline+1:]
# return a certain headerline from the headers
def headerline(head er,tag="From: "):
for h in header:
if h.startswith(ta g):
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(m sg,extract,leve l=1,verbose=Fal se):
m=Parser().pars estr(msg)
if m.is_multipart( ):
if verbose: print '\t'*level,'mul tipart'
for part in m.get_payload() :
enummimeparts(p art.as_string() ,extract,level+ 1,verbose)
else:
t=m.get_content _type()
if verbose: print '\t'*level,t
if t=="text/plain":
if not "text/plain" in extract:
headers,body=se parate(m.as_str ing())
extract["text/plain"]='\n'.join(body )
else:
extract["others"]=True
elif t=="text/html":
if not "text/html" in extract:
headers,body=se parate(m.as_str ing())
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(m sg,extract)
return
extract.get("te xt/plain",None),ex tract.get("text/html",None),ext ract.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(l ines)
headers,body=se parate(lines)
name,fromaddres s=parseaddr(hea derline(headers ,"From:"))
subject=headerl ine(headers,"Su bject:")
logging.info(su bject+" ("+fromaddress+ ")")
(plain,html,oth ers)=extracttex t(msg)
# prefer flat text; if not present in the message, fallback to HTML
content (if any)
texttoprocess=" "
if plain:
texttoprocess=p lain
elif html:
texttoprocess=h tml
# now do something useful with the text
processtext(tex ttoprocess)
# delete message from pop server after processing
pop.dele(msgnr)
# connect to the pop server and process all messages
logging.info("C hecking pop server '%s', user '%s'" % (popserver,popu ser))
pop=poplib.POP3 (popserver)
pop.user(popuse r)
pop.pass_(poppa ssword)
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 1726

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

Similar topics

5
3131
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 code, to learn from, and also avoid re-inventing the wheel, does anyone know of any existing source that implements a (basic or complex) play-by-email system using PHP and maybe MYSQL?
2
4316
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
13686
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 the email body's bytestreams, and get back an array of AttachmentFile collections (filename, size, mime/type), as well as a HTMLBody and a TextBody*. Both HTMLBody and TextBody would be filled if it's a multipart/alternate.
0
1432
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 email. It would appear to be a simple exercise (writing a parser against a select few RFCs), but having someone write this component NIH (doing it by hand, instead of using a 3rd party component) has caused endless problems. We are hoping to right...
2
1605
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 together, nor is it in the same format in each email as the emails come from different order houses. The customer wants me to scan the email and pull the information out so that it can be used to import into their shipping software. I've been able...
2
2179
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 next thing I knew the screen was showing "the system is busy" message. So I pressed "Control-Alt-Delete" as it indicated to re-start the computer, and then once it restarted tried to re-open my Outlook Express. It took a long time, but when it...
0
203
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 Excel and perhaps Access. There should also be a DBapi extension for accessing Access through sql. Search c.l.p archives, the web, or wait for others to post.
0
167
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 .pst files in past, but you'll need some googling to match your requirements. Doesn't help if there is an instance of outlook running on the box.
0
2147
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 this error and extract emails from an exchange server. First I tried: Traceback (most recent call last): File "<interactive input>", line 1, in ? File "C:\Python24\lib\poplib.py", line 96, in __init__ raise socket.error, msg
0
9474
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10143
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10076
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7486
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6729
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5507
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4040
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3633
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2870
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.