Class: CARPS::IMAP

Inherits:
Object
  • Object
show all
Defined in:
lib/carps/email/imap.rb

Overview

Administer IMAP connections

Instance Method Summary collapse

Constructor Details

#initialize(settings, password) ⇒ IMAP

Initialize with a hash of IMAP settings and password

Uh, poorly documented. See source.



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/carps/email/imap.rb', line 40

def initialize settings, password
   @port = settings["port"]
   @server = settings["server"]
   @tls = settings["tls"]
   @username = settings["user"]
   @cert = settings["certificate"]
   @verify = settings["verify"]
   @login = settings["login"]
   @cram_md5 = settings["cram_md5"]
   @password = password
end

Instance Method Details

#ok?Boolean

Are the settings okay?

Returns:

  • (Boolean)


53
54
55
56
57
58
59
60
61
62
# File 'lib/carps/email/imap.rb', line 53

def ok?
   good = false
   begin
      attempt_connection
      good = true
   rescue StandardError => e
      UI::put_error e.to_s
   end
   good
end

#readObject

Return the a list of email message bodies

Blocks until messages become available



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/carps/email/imap.rb', line 67

def read
   if $DEBUG
      puts "Reading mail."
   end
   mails = []
   # Block 'till we get one
   while mails.empty?
      with_connection do |imap|
         imap.select("inbox")
         # Get all mails
         messages = imap.search(["ALL"])
         if messages.empty?
            sleep delay
         else
            mails = imap.fetch messages, "BODY[TEXT]"
            mails = mails.map do |mail|
               from_mail mail.attr["BODY[TEXT]"]
            end
            # Delete all mails
            messages.each do |message_id|
               imap.store(message_id, "+FLAGS", [:Deleted])
            end
            imap.expunge
         end
      end
   end
   mails
end

#with_connectionObject

Perform an action with an IMAP connection



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/carps/email/imap.rb', line 97

def with_connection
   imap = nil
   begin
      imap = attempt_connection
      yield imap
   rescue Net::IMAP::NoResponseError => e
      if e.message =~ /(A|a)uthentication failed/
         UI::put_error e.message, false
         @password = UI::secret "Enter IMAP password for #{@username}" 
      else
         warn_delay
      end
      UI::put_error e.message, false
   rescue StandardError => e
      warn_delay
      UI::put_error e.message, false
   ensure
      if imap
         imap.logout
         imap.disconnect
      end
   end 
end