1
+ # frozen_string_literal: true
2
+
1
3
module Mail
2
4
# IMAP class patch to better manage connection and search of emails
3
5
class IMAP
4
6
attr_accessor :imap_connection
5
7
6
- # fetch emails with different flag, to make it work with icloud
7
- FETCH_EMAIL_FLAG = "BODY[]" #"RFC822"
8
-
9
8
def find_emails ( options = { } , &block ) # rubocop:disable all
10
9
options = validate_options ( options )
11
10
options [ :read_only ] ? imap_connection . examine ( options [ :mailbox ] ) : imap_connection . select ( options [ :mailbox ] )
@@ -19,8 +18,7 @@ def find_emails(options = {}, &block) # rubocop:disable all
19
18
if block_given?
20
19
uids . each do |uid |
21
20
uid = options [ :uid ] . to_i unless options [ :uid ] . nil?
22
- fetchdata = imap_connection . uid_fetch ( uid , [ 'RFC822' ] ) [ 0 ]
23
- new_message = Mail . new ( fetchdata . attr [ 'RFC822' ] )
21
+ new_message = retrieve_email_content ( uid , options [ :fetch_type ] )
24
22
new_message . mark_for_delete = true if options [ :delete_after_find ]
25
23
26
24
if block . arity == 3
@@ -39,8 +37,7 @@ def find_emails(options = {}, &block) # rubocop:disable all
39
37
40
38
uids . each do |uid |
41
39
uid = options [ :uid ] . to_i unless options [ :uid ] . nil?
42
- fetchdata = imap_connection . uid_fetch ( uid , [ FETCH_EMAIL_FLAG ] ) [ 0 ]
43
- emails << Mail . new ( fetchdata . attr [ FETCH_EMAIL_FLAG ] )
40
+ emails << retrieve_email_content ( uid , options [ :fetch_type ] )
44
41
imap_connection . uid_store ( uid , '+FLAGS' , [ Net ::IMAP ::DELETED ] ) if options [ :delete_after_find ]
45
42
break unless options [ :uid ] . nil?
46
43
end
@@ -66,5 +63,44 @@ def connect(_config = Mail::Configuration.instance) # rubocop:disable all
66
63
def disconnect
67
64
imap_connection . disconnect if defined? ( imap_connection ) && imap_connection && !imap_connection . disconnected?
68
65
end
66
+
67
+ private
68
+
69
+ # fetch emails with different flag
70
+ # to make it work with icloud
71
+ FETCH_FLAG = {
72
+ body : 'BODY[]' ,
73
+ rfc : 'RFC822' ,
74
+ envelope : 'ENVELOPE'
75
+ } . freeze
76
+
77
+ def retrieve_email_content ( uid , flag_type = :body )
78
+ case flag_type
79
+ when :body
80
+ retrieve_email_content_by_body ( uid )
81
+ when :envelope
82
+ retrieve_email_content_by_envelope ( uid )
83
+
84
+ else
85
+ retrieve_email_content_by_body ( uid )
86
+ end
87
+ end
88
+
89
+ def retrieve_email_content_by_body ( uid )
90
+ fetchdata = retrieve_fetch_type_data ( FETCH_FLAG [ :body ] , uid )
91
+ Mail . new ( fetchdata )
92
+ end
93
+
94
+ def retrieve_email_content_by_envelope ( uid )
95
+ fetchdata = retrieve_fetch_type_data ( FETCH_FLAG [ :envelope ] , uid )
96
+ mail = Mail . new
97
+ mail . subject = fetchdata . subject
98
+ mail
99
+ end
100
+
101
+ def retrieve_fetch_type_data ( fetch_type , uid )
102
+ fetchdata = imap_connection . uid_fetch ( uid , fetch_type ) [ 0 ]
103
+ fetchdata . attr [ fetch_type ]
104
+ end
69
105
end
70
106
end
0 commit comments