Search code examples
rubyimap

Ruby IMAP library: How can I show all messages in a folder?


I need a script to fetch all my emails in all my folders and make a local backup of them together with attachments.here but it doesn't bring me further with listing all emails belongig to a folder. Also reading the RFC doesn't bring me much further.

When I issued

imap.list("", "*")

And

imap.examine("SomeFolder")

How can I use this to iterate over all emails of SomeFolder ?

And how would I further issue a query to get the messages as well as the associated attachments?


Solution

  • To get the UIDs of all emails in a mailbox, use imap.uid_search(["ALL"]). You can then fetch them all in RFC822 (.eml) format (which includes their attachments) like this:

    require "net/imap"
    require "mail"
    
    # initialize your imap object here
    imap = Net::IMAP.new(...)
    imap.login(...)
    
    imap.list("", "*").map(&:name).each do |mailbox|
        imap.examine(mailbox)
    
        # Create directory for mailbox backup
        Dir.mkdir(mailbox) unless Dir.exist? mailbox
    
        uids = imap.uid_search(["ALL"])
        uids.each_with_index do |uid, i|
            # fetch the email in RFC822 format
            raw_email = imap.uid_fetch(uid, "RFC822").first.attr["RFC822"]
    
            # use the "mail" gem to parse the raw email and extract some useful info
            email = Mail.new(raw_email)
            puts "[#{i+1}/#{uids.length}] Saving email #{mailbox}/#{uid} (#{email.subject.inspect} from #{email.from.first} at #{email.date})"
    
            # save the email to a file
            File.write(File.join(mailbox, "#{uid}.eml"), raw_email)
        end
    end