猿问
下载APP

如何从Gmail下载所有带有附件的电子邮件?

如何连接到Gmail并确定哪些邮件带有附件?然后,我想下载每个附件,并在处理邮件时打印出主题:和发件人:。



慕圣8478803
浏览 272回答 3
3回答

慕的地8271018

硬一个:-)import email, getpass, imaplib, osdetach_dir = '.' # directory where to save attachments (default: current)user = raw_input("Enter your GMail username:")pwd = getpass.getpass("Enter your password: ")# connecting to the gmail imap serverm = imaplib.IMAP4_SSL("imap.gmail.com")m.login(user,pwd)m.select("[Gmail]/All Mail") # here you a can choose a mail box like INBOX instead# use m.list() to get all the mailboxesresp, items = m.search(None, "ALL") # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp)items = items[0].split() # getting the mails idfor emailid in items:    resp, data = m.fetch(emailid, "(RFC822)") # fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc    email_body = data[0][1] # getting the mail content    mail = email.message_from_string(email_body) # parsing the mail content to get a mail object    #Check if any attachments at all    if mail.get_content_maintype() != 'multipart':        continue    print "["+mail["From"]+"] :" + mail["Subject"]    # we use walk to create a generator so we can iterate on the parts and forget about the recursive headach    for part in mail.walk():        # multipart are just containers, so we skip them        if part.get_content_maintype() == 'multipart':            continue        # is this part an attachment ?        if part.get('Content-Disposition') is None:            continue        filename = part.get_filename()        counter = 1        # if there is no filename, we create one with a counter to avoid duplicates        if not filename:            filename = 'part-%03d%s' % (counter, 'bin')            counter += 1        att_path = os.path.join(detach_dir, filename)        #Check if its already there        if not os.path.isfile(att_path) :            # finally write the stuff            fp = open(att_path, 'wb')            fp.write(part.get_payload(decode=True))            fp.close()哇!就是那样 ;-)但是,在Java中尝试相同的做法只是为了好玩!顺便说一句,我在外壳中进行了测试,因此可能仍然存在一些错误。请享用编辑:因为邮箱名称可以从一个国家更改为另一个国家,所以我建议您先在m.list()其中选择一个项目,m.select("the mailbox name")以免发生此错误:imaplib.error:命令搜索在状态AUTH中是非法的,仅在选择状态中才允许

慕码人2483693

#!/usr/bin/env python"""Save all attachments for given gmail account."""import os, sysfrom libgmail import GmailAccountga = GmailAccount("your.account@gmail.com", "pA$$w0Rd_")ga.login()# folders: inbox, starred, all, drafts, sent, spamfor thread in ga.getMessagesByFolder('all', allPages=True):    for msg in thread:        sys.stdout.write('.')        if msg.attachments:           print "\n", msg.id, msg.number, msg.subject, msg.sender           for att in msg.attachments:               if att.filename and att.content:                  attdir = os.path.join(thread.id, msg.id)                  if not os.path.isdir(attdir):                     os.makedirs(attdir)                                  with open(os.path.join(attdir, att.filename), 'wb') as f:                       f.write(att.content)未经测试确保TOS允许此类脚本,否则您的帐户将被暂停可能会有更好的选择:GMail离线模式,Thunderbird + ExtractExtensions,GmailFS,Gmail云端硬盘等。

翻翻过去那场雪

看看Mail :: Webmail :: Gmail:获取附件有两种获取附件的方法:1->通过发送对由...返回的特定附件的引用 get_indv_email# Creates an array of references to every attachment in your accountmy $messages = $gmail->get_messages();my @attachments;foreach ( @{ $messages } ) {    my $email = $gmail->get_indv_email( msg => $_ );    if ( defined( $email->{ $_->{ 'id' } }->{ 'attachments' } ) ) {        foreach ( @{ $email->{ $_->{ 'id' } }->{ 'attachments' } } ) {            push( @attachments, $gmail->get_attachment( attachment => $_ ) );            if ( $gmail->error() ) {                print $gmail->error_msg();            }        }    }}2->或通过发送附件ID和邮件ID#retrieve specific attachmentmy $msgid = 'F000000000';my $attachid = '0.1';my $attach_ref = $gmail->get_attachment( attid => $attachid, msgid => $msgid );(返回对包含附件中数据的标量的引用。)
打开App,查看更多内容
随时随地看视频慕课网APP
我要回答