Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select mailbox "sent mail" or "all mail" in Ruby Net::IMAP

Tags:

ruby

gmail

imap

I'm trying to use Net::IMAP in Ruby to search all mail sent by me, but I'm having trouble selecting anything other than INBOX.

imap.select('INBOX')

works fine, but

imap.select('Mail/sent-mail')

as shown on the Net::IMAP documentation gives me "Unknown Mailbox".

Incidentally, this is to be used with gmail.

I also tried adding "in", "anywhere" to my imap.search(), but that didn't parse.

Current code:

imap.select('INBOX')
now = Time.now.localtime - 1209600 #two weeks
since = now.day.to_s() + "-" + Date::MONTHNAMES[now.month] + "-" + now.year.to_s()
puts "since"
puts since
begin
  mail_ids = imap.search(["FROM", "me", "SINCE", since])
  mail_ids.each do |id|
    text = imap.fetch(id, 'BODY[HEADER.FIELDS (SUBJECT)]').to_s.split("{").second.chop
    puts text
  end
end
like image 621
Eli Albért Avatar asked Mar 03 '11 21:03

Eli Albért


3 Answers

The "sent mail" folder will differ from provider to provider. Gmail's "sent mail" folder is named "[Gmail]/Sent Mail". Select that instead and it'll work.

imap.select('[Gmail]/Sent Mail')

FYI, Gmail's system folders are the following:

  • INBOX
  • [Gmail]/All Mail
  • [Gmail]/Drafts
  • [Gmail]/Sent Mail
  • [Gmail]/Spam
  • [Gmail]/Starred
  • [Gmail]/Trash
like image 125
dkarp Avatar answered Nov 24 '22 00:11

dkarp


You can find the names of all folders with:

imap.list('*', '*') 

The Gmail folders name's will change depending on the user selected language. So in Spanish for example:

"[Gmail]/All" Mail will be "[Gmail]/Todos"

like image 44
Jose Antonio Pio Gil Avatar answered Nov 24 '22 00:11

Jose Antonio Pio Gil


I found the following to be helpful (ruby 2.0.0-p195)

# list all folders
imap.list '', '%'
like image 38
maček Avatar answered Nov 23 '22 23:11

maček