Class: Vmail::ContactsExtractor

Inherits:
Object
  • Object
show all
Defined in:
lib/vmail/contacts_extractor.rb

Instance Method Summary collapse

Constructor Details

#initialize(username, password) ⇒ ContactsExtractor

Returns a new instance of ContactsExtractor.



5
6
7
8
# File 'lib/vmail/contacts_extractor.rb', line 5

def initialize(username, password)
  puts "logging as #{username}"
  @username, @password = username, password
end

Instance Method Details

#extract(limit = 500) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/vmail/contacts_extractor.rb', line 18

def extract(limit = 500)
  open do |imap|
    mailbox = '[Gmail]/Sent Mail'
    STDERR.puts "selecting #{mailbox}"
    imap.select(mailbox)
    STDERR.puts "fetching last #{limit} sent messages"
    all_uids = imap.uid_search('ALL')
    STDERR.puts "total messages: #{all_uids.size}"
    limit = [limit, all_uids.size].min
    STDERR.puts "extracting addresses from #{limit} of them"
    uids = all_uids[-limit ,limit]
    imap.uid_fetch(uids, ["FLAGS", "ENVELOPE"]).each do |fetch_data|
      recipients = fetch_data.attr["ENVELOPE"].to
      next unless recipients
      recipients.each do |address_struct|
        email = [address_struct.mailbox, address_struct.host].join('@') 
        name = address_struct.name
        if name 
          name = Mail::Encodings.unquote_and_convert_to(name, 'UTF-8') 
          yield "#{name} <#{email}>"
        else
          yield email
        end
      end
    end
  end
end

#open {|@imap| ... } ⇒ Object

Yields:

  • (@imap)


10
11
12
13
14
15
16
# File 'lib/vmail/contacts_extractor.rb', line 10

def open
  @imap = Net::IMAP.new('imap.gmail.com', 993, true, nil, false)
  puts @imap.(@username, @password)
  yield @imap
  @imap.close 
  @imap.disconnect
end