Lost Password?


Go Back   CodeCall Programming Forum > Software Development > Python

Python Discussion forum for Python, a high-level language with simple syntax, but yet powerful.

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 07-11-2008, 08:01 AM
gaffaro's Avatar   
gaffaro gaffaro is offline
Newbie
 
Join Date: Jul 2008
Posts: 10
Rep Power: 0
gaffaro is on a distinguished road
Default get mail with POP3

i have a problem
my problem is that : i can get mails from my host with pop3
here is i could get even subject and sender name even date
also my mail nums ...
when i attempt to get message's content
with another function, so an error occured in front of me !!
how do i get mail's content ??
and without html codes

is there anyone to help me about ?

in fact if i see the mail's content i will be able to
seperate from html codes..

python is very usefull for string process.
search and matches waiting for me and
my mail's content

Code:
# !/usr/bin/python
import sys,string
import poplib, email

def getMail(host, user, passwd, deletion = 0):
    pop3 = poplib.POP3(host)
    pop3.user(user)
    pop3.pass_(passwd)

    try :
        num = len(pop3.list()[1])
    except:
        print "connection error with pop3.."
        sys.exit()
        
    print user, "has", num, "messages"

    format = "%-5s %-40s %s"

    if num > 0:
        if deletion:
            print "Deleting", num, "messages",
            for i in range(1, num+1):
                pop3.dele(i)
                print ".",
            print " done."
        else:
            print format % ("Num", "From", "Subject")
            for i in range(1, num+1):
                str = string.join(pop3.top(i, 1)[1], "\n")
                msg = email.message_from_string(str)
                print format % (i, msg["From"], msg["Subject"])
            
    pop3.quit()

# the program starts heree...    
if __name__ =='__main__':
    host = "" # ur host name
    user = "" # ur username
    passwd = "" # ur password
    
    getMail(host,user,passwd) # get with my function

Last edited by gaffaro; 07-11-2008 at 08:04 AM.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

Sponsored Links
  #2 (permalink)  
Old 08-05-2008, 12:22 PM
Goeasy Goeasy is offline
Newbie
 
Join Date: Aug 2008
Posts: 4
Rep Power: 0
Goeasy is on a distinguished road
Default Re: get mail with POP3

Hi!
sory Man, I've the same probleme, I don't know how to do before get mails from my host with pop3. please if any one solve the problem, make me know.
thank...
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 08-06-2008, 03:20 AM
gaffaro's Avatar   
gaffaro gaffaro is offline
Newbie
 
Join Date: Jul 2008
Posts: 10
Rep Power: 0
gaffaro is on a distinguished road
Default Re: get mail with POP3

hey Goeasy,
i solved this problem with another python code
it is not useful as like this, and has more more line of codes

Code:
import poplib
import email
import email.parser
import os
import sys

class email_attachment:
    def __init__(self, messagenum, attachmentnum, filename, contents):
        '''
        arguments:

        messagenum - message number of this message in the Inbox
        attachmentnum - attachment number for this attachment
        filename - filename for this attachment
        contents - attachment's contents
        '''
        self.messagenum=messagenum
        self.attachmentnum=attachmentnum
        self.filename=filename
        self.contents=contents
        return

    def save(self, savepath, savefilename=None):
        '''
        Method to save the contents of an attachment to a file
        arguments:

        savepath - path where file is to be saved
        safefilename - optional name (if None will use filename of attachment
        '''

        savefilename=savefilename or self.filename
        f=open(os.path.join(savepath, savefilename),"wb")
        f.write(self.contents)
        f.close()
        return

class email_msg:
    def __init__(self, messagenum, contents):
        self.messagenum=messagenum
        self.contents=contents
        self.attachments_index=0  # Index of attachments for next method
        self.ATTACHMENTS=[]       # List of attachment objects

        self.msglines='\n'.join(contents[1])
        #
        # See if I can parse the message lines with email.Parser
        #
        self.msg=email.parser.Parser().parsestr(self.msglines)
        if self.msg.is_multipart():
            attachmentnum=0
            for part in self.msg.walk():
                # multipart/* are just containers
                mptype=part.get_content_maintype()
                filename = part.get_filename()
                if mptype == "multipart": continue
                if filename: # Attached object with filename
                    attachmentnum+=1
                    #self.ATTACHMENTS.append(email_attachment(messagenum,attachmentnum,filename,part.get_payload(decode=1)))
                    #print "Attachment filename=%s" % filename

                else: # Must be body portion of multipart
                    self.body=part.get_payload()

        else: # Not multipart, only body portion exists
            self.body=self.msg.get_payload()

        return


    def get(self, key):
        try: return self.msg.get(key)
        except:
            emsg="email_msg-Unable to get email key=%s information" % key
            print emsg
            sys.exit(emsg)

    def has_attachments(self):
        return (len(self.ATTACHMENTS) > 0)

    def __iter__(self):
        return self

    def next(self):
        #
        # Try to get the next attachment
        #
        try: ATTACHMENT=self.ATTACHMENTS[self.attachments_index]
        except:
            self.attachments_index=0
            raise StopIteration
        #
        # Increment the index pointer for the next call
        #
        self.attachments_index+=1
        return ATTACHMENT

class pop3_inbox:
    def __init__(self, server, userid, password):
        self._trace=0
        if self._trace: print "pop3_inbox.__init__-Entering"
        self.result=0             # Result of server communication
        self.MESSAGES=[]          # List for storing message objects
        self.messages_index=0     # Index of message for next method
        #
        # See if I can connect using information provided
        #
        try:
            if self._trace: print "pop3_inbox.__init__-Calling poplib.POP3(server)"
            self.connection=poplib.POP3(server)
            if self._trace: print "pop3_inbox.__init__-Calling connection.user(userid)"
            self.connection.user(userid)
            if self._trace: print "pop3_inbox.__init__-Calling connection.pass_(password)"
            self.connection.pass_(password)

        except:
            if self._trace: print "pop3_inbox.__init__-Login failure, closing connection"
            self.result=1
            self.connection.quit()

        #
        # Get count of messages and size of mailbox
        #
        if self._trace: print "pop3_inbox.__init__-Calling connection.stat()"
        self.msgcount, self.size=self.connection.stat()
        #
        # Loop over all the messages processing each one in turn
        #
        for msgnum in range(1, self.msgcount+1):
            self.MESSAGES.append(email_msg(msgnum,self.connection.retr(msgnum)))

        if self._trace: print "pop3_inbox.__init__-Leaving"
        return

    def close(self):
        self.connection.quit()
        return

    def remove(self, msgnumorlist):
        if isinstance(msgnumorlist, int): self.connection.dele(msgnumorlist)
        elif isinstance(msgnumorlist, (list, tuple)):
            map(self.connection.dele, msgnumorlist)
        else:
            emsg="pop3_inbox.remove-msgnumorlist must be type int, list, or tuple, not %s" % type(msgnumorlist)
            print emsg
            sys.exit(emsg)

        return

    def __iter__(self):
        return self

    def next(self):
        #
        # for next file
        #
        try: MESSAGE=self.MESSAGES[self.messages_index]
        except:
            self.messages_index=0
            raise StopIteration
        #
        # incr. pointer index for next..
        #
        self.messages_index+=1
        return MESSAGE
        
def getMail(server,userid,password):
    inbox=pop3_inbox(server, userid, password)
    if inbox.result:
        emsg="Connection error with pop3.."
        print emsg
        sys.exit(emsg)
    
    for m in inbox:
        print m.body
        # if u wanna get attachments.. use this..  
######################################################################################        
#                                                                                    #
#        if m.has_attachments():                                                     #
#            acounter=0                                                              #
#            for a in m:                                                             #
#                acounter+=1                                                         #
#                print "%i: %s" % (acounter, a.filename)                             #
#                a.save(r"/home/gaffaro") # select save path in ur computer          #
######################################################################################        
    #
    # See if I can delete all messages
    #
    #if inbox.msgcount: inbox.remove(range(1, inbox.msgcount+1))
    inbox.close()
    
server ="ur host ex mail.urmailhost.com"
userid ="ur username"
password ="ur password"

getMail(server,userid,password)
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Php Mail Jaan PHP Forum 4 07-17-2008 07:26 AM
Problem with mail headers ReekenX PHP Forum 4 06-14-2008 09:02 AM
Don't use mail()? bruder PHP Forum 3 01-24-2008 05:58 PM
php mail function, how to use it? falco85 PHP Forum 3 08-21-2006 05:16 PM


All times are GMT -5. The time now is 08:16 AM.

Contest Stats

WingedPanther ........ 2753.6
Xav ........ 2704
Brandon W ........ 1702.32
John ........ 1207.73
marwex89 ........ 1175.24
morefood2001 ........ 966.05
dcs ........ 655.75
Steve.L ........ 475.59
orjan ........ 418.58
Aereshaa ........ 383.54

Contest Rules

CodeCall Goal

Goal: 100,000 Posts
Complete: 100%


Complete - Celebrate!

Ads