[EMAIL PROTECTED] wrote:
i want to make one program that the steps like this:
  1. download email from email account, for example: [EMAIL PROTECTED], saved
in a file, for example: downloadedEmail.txt
Can be done via the standard imaplib module. No need to use twisted.
  2. parsing the downloadedEmail.txt, get the sender, subject and the
message.if there is attachmet/s, not be taken.
Save it as an eml file. Use the standard email.Parser module for extracting headers.
  3. posting the  downloadedEmail.txt that has been parsed into nntp server.
  4. open nntp client for example 'thunderbird' to acces your nntp server.
I have no clue about it.
i attach my programs to u..
it is very important for me as final project in my study class, too
difficult for me....thanks for your help!!!
Well, I can send you some examples that show how to download and parse emails from imap server. I have never used nntp before so....
Some examples are attached, and also a code fragment:

IMAPDate.py - to convert between IMAP and datetime.date
imaputils.py - to show how to connect to IMAP server and list folders on it (you need to create your own local.py file...), also shows how to append a new message to a folder on the imap server. code_fragment.py - to show how to search for messages on the server and download them as pure data string, it is NOT a complete program!

And finally, here is how you parse and email:

   import email.Parser
   email_data = file('test2.eml','rb').read()
   parser = email.Parser.Parser()

Then you need to example "parser" and its methods.

Anyway, it is your homework, I don't think that I'm going to give more help unless you have a specific question. :-)

Best,

   Laszlo


"""Custom date class that 'knows' the date format as specified in RFC3501 IMAP4rev1"""
import datetime

class IMAPDate(datetime.date):
    MONTHNAMES = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
    def to_imapdate(self):
        """Format a date as described in RFC3501."""
        return "%d-%s-%d" % (
            self.day,
            self.MONTHNAMES[self.month-1],
            self.year
        )
    @classmethod
    def from_imapdate(cls,s):
        """Convert an IMAP style date format to an IMAPDate object."""
        if isinstance(s,basestring):
            parts = s.split('-')
            ok = False
            if len(parts) == 3:
                try:
                    day = int(parts[0])
                    month = cls.MONTHNAMES.index(parts[1])+1
                    year = int(parts[2])                    
                except:
                    pass
                return cls(year,month,day)
            if not ok:
                raise ValueError("Invalid IMAP date format. Please check RFC3501.")
        else:
            raise TypeError
            
            
        
        


if __name__ == '__main__':
    date = IMAPDate.today()
    fmt = date.to_imapdate()
    print fmt
    print IMAPDate.from_imapdate(fmt)
    print IMAPDate.from_imapdate('32-Jan-2006')
import local
import imaplib

class IMAPError(Exception):
    pass

def check_imap_error((typ,data)):
    if (typ != 'OK'):
        raise IMAPError((typ,data))
    
def getnewimapconnection():
    conn = imaplib.IMAP4_SSL(local.IMAP_HOST)
    check_imap_error(conn.LOGIN(local.IMAP_LOGIN,local.IMAP_PWD))
    return conn

def getfolders(conn,where='Public/*'):
        res = []
        typ,data = conn.list(where)
        check_imap_error((typ,data))
        for item in data:
            index = item[:-1].rfind('"')
            res.append(item[index+1:-1])
        return res

if __name__ == '__main__':

        conn = getnewimapconnection()
        #print getfolders(conn)
        typ,data = conn.select('INBOX')
        check_imap_error((typ,data))

        email = file('test.eml','rb').read()
        typ,data = conn.append('INBOX','(\\Flagged NonJunk $Label4)','',email)
        print typ

#        cnt = int(data[0])        
#        if cnt > 0:
#            typ, items = conn.fetch('1:%s'%cnt, '(UID FLAGS)')
#            check_imap_error((typ,data))
#            for item in items:
#                print item
        # \Flagged \Seen NonJunk 
        # $Label1 $Label2 $Label3 $Label4 $Label5 -> Important,Work,Personal,TODO,Later
from imaputils import *

def import_from_folder(conn,folder,datelimit):
    global cont
    
    print folder
    
    cnt_imported = 0
    cen_conn = conf.db.connect('central',True)
    try:
        cen_conn.starttransaction()
        try:    
            typ,data = conn.select(folder)
            check_imap_error((typ,data))
            cnt = int(data[0])
            if cnt > 0:
                typ,data = conn.uid('SEARCH',None,'(SINCE %s)' % datelimit.to_imapdate())
                check_imap_error((typ,data))
                uids = data[0].split()
                if uids:
                    print "    --> Found %d messages. Importing (c-COMPARE/100 s-SKIP, I-INSERT, N-NOP)"%len(uids)
                    idx = 0
                    for uid in uids:
                        idx+=1
                        #print "UID=",uid
                        typ, items = conn.uid('FETCH',uid,'RFC822')
                        check_imap_error((typ, items))
                        for item in items:
                            if isinstance(item,tuple):
                                eml_data = item[1]
                                parser = email.Parser.Parser()
                                rfc822 = parser.parsestr(eml_data,False)
                                ra = MailFilter.RCF822Analyzer(rfc822)
                                date = datetime.datetime.now()
                                for key,value in rfc822._headers:
                                    if key.lower() == 'date':
                                        tpl = email._parseaddr.parsedate(value)
                                        if tpl:
                                            try:
                                                date = datetime.datetime(*tpl[:7])
                                            except ValueError:
                                                pass
                                                
                                
                                try:
                                    if options.import_method == 'all':
                                        should_import = True
                                    else:
                                        should_import = not is_already_imported(ra,cen_conn)
                                    
                                    if should_import:
                                        cnt_imported += 1
                                        if options.import_nop:
                                            email_id = "???"
                                            mark = 'N'
                                        else:
                                            email_id = import_email(eml_data,ra,cen_conn,date)
                                            mark = 'I'
                                    else:
                                        mark = 's'
                                        email_id = None
                                    if options.import_verbose:
                                        print mark, \
                                            "ID=",email_id,\
                                            "FROM=",repr(ra.igetheader('from')),\
                                            "TO=",repr(ra.igetheader('to')),\
                                            "SUBJECT=",repr(ra.igetheader('subject'))
                                    else:
                                        sys.stdout.write(mark)
                                    if idx%100==0:
                                        sys.stdout.write(str(idx))
                                    sys.stdout.flush()
                                except UnicodeDecodeError:
                                    print "UnicodeDecodeError IGNORED!"

            cen_conn.committransaction()
            if cnt_imported>0:
                sys.stdout.write("\n")
            return cnt_imported
        except Exception,e:
            cen_conn.rollbacktransaction()
            raise
    finally:
        cen_conn.close()
        del cen_conn
                        

    

def import_from_imap(datelimit):
    conn = getnewimapconnection()
    folders = getfolders(conn,'Public/*')
    folders.sort()
    cnt_imported = {}
    cnt_imported_all = 0
    scnt_imported = []
    for folder in folders:
        #if folder >= "Public/X_Junk":
        cnt = cnt_imported[folder] = import_from_folder(conn,folder,datelimit)
        cnt_imported_all+=cnt
        scnt_imported.append("%d %s"%(cnt,folder))
    print "Summary"    
    scnt_imported.sort()
    for item in scnt_imported:
        print item
    print "---------------------"
    print "Total: ",cnt_imported_all
    
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to