Class: Vmail::ImapClient
Constant Summary
ShowingHeaders::FLAGMAP
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
#reply_cc, #reply_headers, #reply_recipient, #reply_template
#convert_to_message_ids, #copy_to, #flag, #move_to
#cached_full_message?, #current_mail, #current_message, #fetch_and_cache, #format_parts_info, #show_message
#extract_address, #fetch_and_cache_headers, #format_flags, #format_header_for_list, #get_message_headers, #with_more_message_line
Methods included from Searching
#search, #search_query?
#quote_addresses
Methods included from Helpers
#divider, #number_to_human_size, #retry_if_needed
Constructor Details
#initialize(config) ⇒ ImapClient
Returns a new instance of ImapClient.
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
# File 'lib/vmail/imap_client.rb', line 32
def initialize(config)
@username, @password = config['username'], config['password']
@from = config['from'] || config['username']
@name = config['name']
@signature = config['signature']
@signature_script = config['signature_script']
@always_cc = config['always_cc']
@always_bcc = config['always_bcc']
@mailbox = nil
@logger = Logger.new(config['logfile'] || STDERR)
@logger.level = Logger::DEBUG
$logger = @logger
@imap_server = config['server'] || 'imap.gmail.com'
@imap_port = config['port'] || 993
@smtp_server = config['smtp_server'] || 'smtp.gmail.com'
@smtp_port = config['smtp_port'] || 587
@smtp_domain = config['smtp_domain'] || 'gmail.com'
@authentication = config['authentication'] || 'plain'
@width = 100
@date_formatter_this_year = config['date_format'] || '%b %d %I:%M%P'
@date_formatter_prev_years = config['date_format_previous_years'] || '%b %d %Y'
@date_width = DateTime.parse("12/12/2012 12:12:12").strftime(@date_formatter_this_year).length
mailbox_aliases_config = config['mailbox_aliases'] || {}
@default_mailbox_aliases = Vmail::Defaults::MAILBOX_ALIASES.merge(
mailbox_aliases_config)
current_message = nil
end
|
Instance Attribute Details
#max_seqno ⇒ Object
30
31
32
|
# File 'lib/vmail/imap_client.rb', line 30
def max_seqno
@max_seqno
end
|
Class Method Details
.daemon(config) ⇒ Object
538
539
540
541
542
543
544
545
546
|
# File 'lib/vmail/imap_client.rb', line 538
def self.daemon(config)
puts "Starting Vmail::ImapClient in dir #{ Dir.pwd }"
$gmail = self.start(config)
use_uri = config['drb_uri'] || nil DRb.start_service(use_uri, $gmail)
uri = DRb.uri
puts "Starting gmail service at #{ uri }"
uri
end
|
.start(config) ⇒ Object
532
533
534
535
536
|
# File 'lib/vmail/imap_client.rb', line 532
def self.start(config)
imap_client = self.new config
imap_client.open
imap_client
end
|
Instance Method Details
#append_to_file(message_ids, file) ⇒ Object
306
307
308
309
310
311
312
313
314
315
316
|
# File 'lib/vmail/imap_client.rb', line 306
def append_to_file(message_ids, file)
message_ids = message_ids.split(',')
log "Append to file uid set #{ message_ids.inspect } to file: #{ file }"
message_ids.each do |message_id|
message = show_message(message_id)
File.open(file, 'a') {|f| f.puts(divider('=') + "\n" + message + "\n\n")}
subject = (message[/^subject:(.*)/,1] || '').strip
log "Appended message '#{ subject }'"
end
"Printed #{ message_ids.size } message#{ message_ids.size == 1 ? '' : 's' } to #{ file.strip }"
end
|
#check_for_new_messages ⇒ Object
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
|
# File 'lib/vmail/imap_client.rb', line 217
def check_for_new_messages
log "Checking for new messages"
if search_query?
log "Update aborted because query is search query: #{ @query.inspect }"
return ""
end
old_num_messages = @num_messages
reload_mailbox
update_query = @query.dup
update_query[0] = "#{ old_num_messages }:#@num_messages"
ids = reconnect_if_necessary {
log "Search #update_query"
@imap.search(Vmail::Query.args2string(update_query))
}
log "- got seqnos: #{ ids.inspect }"
log "- getting seqnos > #{ self.max_seqno }"
new_ids = ids.select {|seqno| seqno.to_i > self.max_seqno}
self.max_seqno = ids.max
log "- setting max_seqno to #{ self.max_seqno }"
log "- new uids found: #{ new_ids.inspect }"
update_message_list(new_ids) if new_ids.any? && has_clientserver?
new_ids
end
|
#clear_cached_message ⇒ Object
TODO no need for this if all shown messages are stored in SQLITE3 and keyed by UID.
118
119
120
121
122
|
# File 'lib/vmail/imap_client.rb', line 118
def clear_cached_message
return unless STDIN.tty?
log "Clearing cached message"
current_message = nil
end
|
#close ⇒ Object
82
83
84
85
86
87
88
89
|
# File 'lib/vmail/imap_client.rb', line 82
def close
log "Closing connection"
Timeout::timeout(5) do
@imap.close rescue Net::IMAP::BadResponseError
@imap.disconnect rescue IOError
end
rescue Timeout::Error
end
|
#create_if_necessary(mailbox) ⇒ Object
295
296
297
298
299
300
301
302
303
304
|
# File 'lib/vmail/imap_client.rb', line 295
def create_if_necessary(mailbox)
current_mailboxes = mailboxes.map {|m| mailbox_aliases[m] || m}
if !current_mailboxes.include?(mailbox)
log "Current mailboxes: #{ current_mailboxes.inspect }"
log "Creating mailbox #{ mailbox }"
log @imap.create(mailbox)
@mailboxes = nil list_mailboxes
end
end
|
#decrement_max_seqno(num) ⇒ Object
203
204
205
206
207
|
# File 'lib/vmail/imap_client.rb', line 203
def decrement_max_seqno(num)
return unless STDIN.tty?
log "Decremented max seqno from #{ self.max_seqno } to #{ self.max_seqno - num }"
self.max_seqno -= num
end
|
#deliver(text) ⇒ Object
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
|
# File 'lib/vmail/imap_client.rb', line 379
def deliver(text)
require 'net/smtp'
prime_connection
mail = new_mail_from_input(text)
mail.delivery_method(*smtp_settings)
res = mail.deliver!
log res.inspect
log "\n"
msg = if res.is_a?(Mail::Message)
"Message '#{ mail.subject }' sent"
else
"Failed to deliver message '#{ mail.subject }'!"
end
log msg
msg
end
|
329
330
331
332
333
334
335
336
337
338
339
340
341
|
# File 'lib/vmail/imap_client.rb', line 329
def (hash)
lines = []
hash.each_pair do |key, value|
if value.nil? && key != 'to' && key != 'subject'
next
end
if value.is_a?(Array)
value = value.join(", ")
end
lines << "#{ key.gsub("_", '-') }: #{ value }"
end
lines.join("\n")
end
|
368
369
370
371
372
373
374
375
376
377
|
# File 'lib/vmail/imap_client.rb', line 368
def format_sent_message(mail)
formatter = Vmail::MessageFormatter.new(mail)
message_text = <<-EOF
Sent Message #{ self.format_parts_info(formatter.list_parts) }
#{ (formatter.) }
#{ formatter.plaintext_part }
EOF
end
|
#forward_template ⇒ Object
354
355
356
357
358
359
360
361
362
363
364
365
366
|
# File 'lib/vmail/imap_client.rb', line 354
def forward_template
original_body = current_message.plaintext.split(/\n-{20,}\n/, 2)[1]
formatter = Vmail::MessageFormatter.new(current_mail)
= formatter.
subject = ['subject']
if subject !~ /Fwd: /
subject = "Fwd: #{ subject }"
end
new_message_template(subject, false) +
"\n---------- Forwarded message ----------\n" +
original_body + signature
end
|
#get_highest_message_id ⇒ Object
124
125
126
127
128
129
130
131
132
133
134
|
# File 'lib/vmail/imap_client.rb', line 124
def get_highest_message_id
res = @imap.search(['ALL'])
if res && res[-1]
@num_messages = res[-1]
log "Highest seqno: #@num_messages"
else
@num_messages = 1
log "NO HIGHEST ID: setting @num_messages to 1"
end
end
|
#get_mailbox_status ⇒ Object
137
138
139
140
141
|
# File 'lib/vmail/imap_client.rb', line 137
def get_mailbox_status
return
@status = @imap.status(@mailbox, ["MESSAGES", "RECENT", "UNSEEN"])
log "Mailbox status: #@status.inspect"
end
|
#handle_error(error) ⇒ Object
508
509
510
|
# File 'lib/vmail/imap_client.rb', line 508
def handle_error(error)
log error
end
|
#has_clientserver? ⇒ Boolean
209
210
211
|
# File 'lib/vmail/imap_client.rb', line 209
def has_clientserver?
@has_clientserver ||= system("#{ vim } --version | grep +clientserver")
end
|
#list_mailboxes ⇒ Object
164
165
166
167
168
169
170
171
172
173
174
175
176
|
# File 'lib/vmail/imap_client.rb', line 164
def list_mailboxes
log 'loading mailboxes...'
@mailboxes ||= (@imap.list("", "*") || []).
select {|struct| struct.attr.none? {|a| a == :Noselect} }.
map {|struct|
Net::IMAP.decode_utf7(struct.name)
}.uniq
@mailboxes.delete("INBOX")
@mailboxes.unshift("INBOX")
log "Loaded mailboxes: #@mailboxes.inspect"
@mailboxes = @mailboxes.map {|name| mailbox_aliases.invert[name] || name}
@mailboxes.join("\n")
end
|
#log(string) ⇒ Object
501
502
503
504
505
506
|
# File 'lib/vmail/imap_client.rb', line 501
def log(string)
if string.is_a?(::Net::IMAP::TaggedResponse)
string = string.raw_data
end
@logger.debug string
end
|
#mailbox_aliases ⇒ Object
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
|
# File 'lib/vmail/imap_client.rb', line 179
def mailbox_aliases
return @mailbox_aliases if @mailbox_aliases
@mailbox_aliases = {}
@default_mailbox_aliases.each do |shortname, fullname_list|
fullname_list.each do |fullname|
[ "[Gmail]", "[Google Mail]" ].each do |prefix|
if self.mailboxes.include?( "#{ prefix }/#{ fullname }" )
@mailbox_aliases[shortname] = "#{ prefix }/#{ fullname }"
end
end
end
end
log "Setting aliases to #{ @mailbox_aliases.inspect }"
@mailbox_aliases
end
|
#mailboxes ⇒ Object
called internally, not by vim client
196
197
198
199
200
201
|
# File 'lib/vmail/imap_client.rb', line 196
def mailboxes
if @mailboxes.nil?
list_mailboxes
end
@mailboxes
end
|
#more_messages ⇒ Object
gets 100 messages prior to id
272
273
274
275
276
277
278
279
280
281
282
283
|
# File 'lib/vmail/imap_client.rb', line 272
def more_messages
log "Getting more_messages"
log "Old start_index: #@start_index"
max = @start_index - 1
@start_index = [(max + 1 - @limit), 1].max
log "New start_index: #@start_index"
fetch_ids = search_query? ? @ids[@start_index..max] : (@start_index..max).to_a
log fetch_ids.inspect
message_ids = fetch_and_cache_headers(fetch_ids)
res = message_ids
with_more_message_line(res)
end
|
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
|
# File 'lib/vmail/imap_client.rb', line 397
def new_mail_from_input(text)
require 'mail'
mail = Mail.new
, raw_body = *text.split(/\n\s*\n/, 2)
= {}
.split("\n").each do |line|
key, value = *line.split(/:\s*/, 2)
if key == 'references'
mail.references = value
else
next if (value.nil? || value.strip == '')
log [key, value].join(':')
if %w(from to cc bcc).include?(key)
value = quote_addresses(value)
end
[key] = value
end
end
log "Delivering message with headers: #{ .to_yaml }"
mail.from = ['from'] || @username
mail.to = ['to'] mail.cc = ['cc'] mail.bcc = ['bcc'] mail.subject = ['subject']
mail.from ||= @username
mail.charset = 'UTF-8'
if (attachments_section = raw_body.split(/\n\s*\n/, 2)[0]) =~ /^attach(ment|ments)*:/
files = attachments_section.split(/\n/).map {|line| line[/[-:]\s*(.*)\s*$/, 1]}.compact
log "Attach: #{ files.inspect }"
files.each do |file|
if File.directory?(file)
Dir.glob("#{ file }/*").each {|f| mail.add_file(f) if File.size?(f)}
else
mail.add_file(file) if File.size?(file)
end
end
mail.text_part do
body raw_body.split(/\n\s*\n/, 2)[1]
end
else
mail.text_part do
body raw_body
end
end
mail.text_part.charset = 'UTF-8'
mail
rescue
$logger.debug $!
raise
end
|
#new_message_template(subject = nil, append_signature = true) ⇒ Object
318
319
320
321
322
323
324
325
326
327
|
# File 'lib/vmail/imap_client.rb', line 318
def new_message_template(subject = nil, append_signature = true)
= {'from' => "#@name <#@from>",
'to' => nil,
'subject' => subject,
'cc' => @always_cc,
'bcc' => @always_bcc
}
() + (append_signature ? ("\n\n" + signature) : "\n\n")
end
|
#open ⇒ Object
66
67
68
69
70
71
72
|
# File 'lib/vmail/imap_client.rb', line 66
def open
@imap = Net::IMAP.new(@imap_server, @imap_port, true, nil, false)
log @imap.login(@username, @password)
list_mailboxes rescue
puts "VMAIL_ERROR: #{[$!.message, $!.backtrace].join("\n")}"
end
|
#open_html_part ⇒ Object
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
|
# File 'lib/vmail/imap_client.rb', line 468
def open_html_part
log "Open_html_part"
log current_mail.parts.inspect
multipart = current_mail.parts.detect {|part| part.multipart?}
html_part = if multipart
multipart.parts.detect {|part| part.["Content-Type"].to_s =~ /text\/html/}
elsif ! current_mail.parts.empty?
current_mail.parts.detect {|part| part.["Content-Type"].to_s =~ /text\/html/}
else
current_mail.body
end
return if html_part.nil?
outfile = 'part.html'
File.open(outfile, 'w') {|f| f.puts(html_part.decoded)}
return outfile
end
|
#prime_connection ⇒ Object
150
151
152
153
154
155
156
157
158
159
160
161
162
|
# File 'lib/vmail/imap_client.rb', line 150
def prime_connection
return if @ids.nil? || @ids.empty?
reconnect_if_necessary(4) do
log "Priming connection"
res = @imap.fetch(@ids[-1], ["ENVELOPE"])
if res.nil?
log "Priming connection didn't work, connection seems broken, but still going ahead..."
end
end
end
|
#reconnect_if_necessary(timeout = 60, &block) ⇒ Object
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
|
# File 'lib/vmail/imap_client.rb', line 512
def reconnect_if_necessary(timeout = 60, &block)
Timeout::timeout(timeout) do
block.call
end
rescue IOError, Errno::EADDRNOTAVAIL, Errno::ECONNRESET, Timeout::Error, Errno::ETIMEDOUT
log "Error: #{$!}"
log "Attempting to reconnect"
close
log(revive_connection)
reconnect_if_necessary do
block.call
end
rescue
log "Error: #{$!}"
raise
end
|
#reload_mailbox ⇒ Object
111
112
113
114
|
# File 'lib/vmail/imap_client.rb', line 111
def reload_mailbox
return unless STDIN.tty?
select_mailbox(@mailbox, true)
end
|
#revive_connection ⇒ Object
143
144
145
146
147
148
|
# File 'lib/vmail/imap_client.rb', line 143
def revive_connection
log "Reviving connection"
open
log "Reselecting mailbox #@mailbox"
@imap.select(@mailbox)
end
|
#save_attachments(dir) ⇒ Object
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
|
# File 'lib/vmail/imap_client.rb', line 451
def save_attachments(dir)
log "Save_attachments #{ dir }"
if !current_mail
log "Missing a current message"
end
return unless dir && current_mail
attachments = current_mail.attachments
`mkdir -p #{ dir }`
saved = attachments.map do |x|
path = File.join(dir, x.filename)
log "Saving #{ path }"
File.open(path, 'wb') {|f| f.puts x.decoded}
path
end
"Saved:\n" + saved.map {|x| "- #{ x }"}.join("\n")
end
|
#select_mailbox(mailbox, force = false) ⇒ Object
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
# File 'lib/vmail/imap_client.rb', line 91
def select_mailbox(mailbox, force=false)
if mailbox_aliases[mailbox]
mailbox = mailbox_aliases[mailbox]
end
log "Selecting mailbox #{ mailbox.inspect }"
reconnect_if_necessary(30) do
log @imap.select(Net::IMAP.encode_utf7(mailbox))
end
log "Done"
@mailbox = mailbox
@label = Label[name: @mailbox] || Label.create(name: @mailbox)
log "Getting mailbox status"
get_mailbox_status
log "Getting highest message id"
get_highest_message_id
return "OK"
end
|
#signature ⇒ Object
344
345
346
347
|
# File 'lib/vmail/imap_client.rb', line 344
def signature
return signature_script if @signature_script
"\n\n#@signature"
end
|
#signature_script ⇒ Object
349
350
351
352
|
# File 'lib/vmail/imap_client.rb', line 349
def signature_script
return unless @signature_script
%x{ #{ @signature_script.strip } }
end
|
#smtp_settings ⇒ Object
491
492
493
494
495
496
497
498
499
|
# File 'lib/vmail/imap_client.rb', line 491
def smtp_settings
[:smtp, {:address => @smtp_server,
:port => @smtp_port,
:domain => @smtp_domain,
:user_name => @username,
:password => @password,
:authentication => @authentication,
:enable_starttls_auto => true}]
end
|
#spawn_thread_if_tty(&block) ⇒ Object
285
286
287
288
289
290
291
292
293
|
# File 'lib/vmail/imap_client.rb', line 285
def spawn_thread_if_tty(&block)
if STDIN.tty?
Thread.new do
reconnect_if_necessary(10, &block)
end
else
block.call
end
end
|
#update ⇒ Object
256
257
258
259
260
261
262
263
264
265
266
267
268
269
|
# File 'lib/vmail/imap_client.rb', line 256
def update
prime_connection
new_ids = check_for_new_messages
if !new_ids.empty?
@ids = @ids + new_ids
message_ids = fetch_and_cache_headers(new_ids)
res = (message_ids)
res
else
''
end
rescue
puts "VMAIL_ERROR: #{$!.class}\n#{[$!.message, $!.backtrace].join("\n")}"
end
|
#update_message_list(new_ids) ⇒ Object
245
246
247
248
249
250
251
252
253
254
|
# File 'lib/vmail/imap_client.rb', line 245
def update_message_list(new_ids)
new_emails = DRbObject.new_with_uri($drb_uri).update
return if new_emails.empty?
tempfile_path = Tempfile.new('vmail-').path
File.open(tempfile_path, 'w') { |file| file.write(new_emails) }
server_name = "VMAIL:#{ @username }"
system(%[vim --servername #{ server_name } --remote-expr 'UPDATE_MESSAGE_LIST("#{ tempfile_path }")'])
end
|
#vim ⇒ Object
213
214
215
|
# File 'lib/vmail/imap_client.rb', line 213
def vim
ENV['VMAIL_VIM'] || 'vim'
end
|
#window_width=(width) ⇒ Object
486
487
488
489
|
# File 'lib/vmail/imap_client.rb', line 486
def window_width=(width)
@width = width.to_i
log "Setting window width to #{ width }"
end
|
#with_open {|_self| ... } ⇒ Object
expects a block, closes on finish
75
76
77
78
79
80
|
# File 'lib/vmail/imap_client.rb', line 75
def with_open
@imap = Net::IMAP.new(@imap_server, @imap_port, true, nil, false)
log @imap.login(@username, @password)
yield self
close
end
|