473,473 Members | 2,097 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

how to retrieve attachment in a mail ?

i need to retrieve every day an email and to save his attachments for later
processing.
i found some piece of code in the documentation like

import poplib
pop = poplib.POP3(Host)
pop.user(User)
pop.pass(Pwd)
nbMsg, nbOctet = pop.stat()
for n in range(nbMsg):
response, lines, bytes = pop.retr(n+1)

which retrieve email from a pop3 account and

import email.Parser
import os
import sys

mailFile=open(File,"rb")
p=email.Parser.Parser()
msg=p.parse(mailFile)
mailFile.close()

partCounter=1
for part in msg.walk():
if part.get_main_type()=="multipart":
continue
name=part.get_param("name")
if name==None:
name="part-%i" % partCounter
partCounter+=1
# In real life, make sure that name is a reasonable
# filename on your OS.
f=open(name,"wb")
f.write(part.get_payload(decode=1))
f.close()
print name
wich extract every part of a mailFile

BUT i don't understand how to migrate from
response, lines, bytes = pop.retr(n+1)
where lines is a list to a msg object
for part in msg.walk():

thanks to help me and many pologize for my poor english
Didier

Jul 18 '05 #1
2 12343
On Wed, 29 Oct 2003 09:35:03 +0100, "Didier FRAISSE"
<df******@free.fr> wrote:

BUT i don't understand how to migrate from
response, lines, bytes = pop.retr(n+1)
where lines is a list to a msg object
for part in msg.walk():


The example code you've posted for parsing the message:

msg=p.parse(mailFile)

assumes that the message is coming from a file-like object (e.g. if
you're reading the message from a file on disk.)

Because you're reading the message from a POP server what you probably
want to do is join the lines together into a single string:

messagetext = string.join(lines, "\n")

and then use parsestr rather than parse to get your message object:

msg = p.parsestr(messagetext)

-Michael
Jul 18 '05 #2

"Didier FRAISSE" <df******@free.fr> wrote in message
news:3f*********************@news.free.fr...
i need to retrieve every day an email and to save his attachments for later processing.
i found some piece of code in the documentation like

import poplib
pop = poplib.POP3(Host)
pop.user(User)
pop.pass(Pwd)
nbMsg, nbOctet = pop.stat()
for n in range(nbMsg):
response, lines, bytes = pop.retr(n+1)

which retrieve email from a pop3 account and

import email.Parser
import os
import sys

mailFile=open(File,"rb")
p=email.Parser.Parser()
msg=p.parse(mailFile)
mailFile.close()

partCounter=1
for part in msg.walk():
if part.get_main_type()=="multipart":
continue
name=part.get_param("name")
if name==None:
name="part-%i" % partCounter
partCounter+=1
# In real life, make sure that name is a reasonable
# filename on your OS.
f=open(name,"wb")
f.write(part.get_payload(decode=1))
f.close()
print name
wich extract every part of a mailFile

BUT i don't understand how to migrate from
response, lines, bytes = pop.retr(n+1)
where lines is a list to a msg object
for part in msg.walk():

thanks to help me and many pologize for my poor english
Didier
I found that the last example in the documentation for the email
module (12.2.13 in the Python 2.2.3 Library doc) did exactly
what I wanted. I think I've got slightly different requirements:
I keep the antivirus settings on Outlook Express set high enough
that I can't save attachements directly, so I save the entire
e-mail to a processing directory, and then use the code in the
example to unpack it. After it's unpacked, I do whatever I need to
with it.

This is the code; I don't remember if I modified the example
or not...

-------------------------------------------------------------

#!/usr/bin/env python

"""Unpack a MIME message into a directory of files.

Usage: unpackmail [options] msgfile

Options:
-h / --help
Print this message and exit.

-d directory
--directory=directory
Unpack the MIME message into the named directory, which will be
created if it doesn't already exist.

msgfile is the path to the file containing the MIME message.
"""

import sys
import os
import getopt
import errno
import mimetypes
import email
def usage(code, msg=''):
print >> sys.stderr, __doc__
if msg:
print >> sys.stderr, msg
sys.exit(code)
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], 'hd:', ['help',
'directory='])
except getopt.error, msg:
usage(1, msg)

dir = os.curdir
for opt, arg in opts:
if opt in ('-h', '--help'):
usage(0)
elif opt in ('-d', '--directory'):
dir = arg

try:
msgfile = args[0]
except IndexError:
usage(1)

try:
os.mkdir(dir)
except OSError, e:
# Ignore directory exists error
if e.errno <> errno.EEXIST: raise

fp = open(msgfile)
msg = email.message_from_file(fp)
fp.close()

counter = 1
for part in msg.walk():
# multipart/* are just containers
if part.get_content_maintype() == 'multipart':
continue
# Applications should really sanitize the given filename so that an
# email message can't be used to overwrite important files
filename = part.get_filename()
if not filename:
ext = mimetypes.guess_extension(part.get_type())
if not ext:
# Use a generic bag-of-bits extension
ext = '.bin'
filename = 'part-%03d%s' % (counter, ext)
counter += 1
fp = open(os.path.join(dir, filename), 'wb')
fp.write(part.get_payload(decode=1))
fp.close()
if __name__ == '__main__':
main()

-------------------------------------------------------------

I also use the following command to process each email
I want to unpack:

----------------------------

python unpackmail.py -d outdir %1

---------------------------------

There are obviously lots of ways this could be improved, but
it suits my needs.

John Roth

Jul 18 '05 #3

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

Similar topics

1
by: abracad | last post by:
I'd like to add a form that will email a file attachment to me. Can anyone recommend a decent free script? Thanks
2
by: knoak | last post by:
Hi there, I've found a script at these great Google fora. a script to send emails with attachments. The script is below this message, name etc. aren't mine, but from the original post. My...
2
by: Cutlass | last post by:
Hello I'm using the following code to send mail from VB.NET 2003 Imports System.Web.Mail .. .. Dim oMail as System.Web.Mail.SmtpMail Dim Attachment as System.Web.Mail.MailAttachment Dim...
2
by: m_evergreen | last post by:
Errors: An unhandled exception of type 'System.Web.HttpException' occurred in system.web.dll Additional information: Could not access 'CDO.Message' object. innerexception is "Exception has...
1
by: theWizard1 | last post by:
The following sends my email, but the attachment is empty. The attachment should contain the data that is in the string that was created from the xmlReader. I have a stored procedure written...
3
by: TomislaW | last post by:
I am sending word document with e-mail from asp.net 2.0 application. I read doc file like this:FileStream fs = System.IO.File.Open(docPath,FileMode.Open,FileAccess.Read,FileShare.Read); Then...
6
by: Watermark | last post by:
i got problem with this i m implementing web based mail system. i want to access mbox and retrieve mail from it and display it on web page.. can anybody help me.
1
by: nukephp | last post by:
Hello Guys would you know about php email with his attachment Working on linux platform................................................... The code as below: mail.php <?php //define the...
2
by: Mathew Coleman | last post by:
Hi All, I would like to send emails through an application. Body and attachment have to be encrypted as well as digitally signed. I could able to sign it and send when it does not...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
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...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.