1Mail::IMAPTalk(3) User Contributed Perl Documentation Mail::IMAPTalk(3)
2
3
4
6 Mail::IMAPTalk - IMAP client interface with lots of features
7
9 use Mail::IMAPTalk;
10
11 $IMAP = Mail::IMAPTalk->new(
12 Server => $IMAPServer,
13 Username => 'foo',
14 Password => 'bar',
15 ) || die "Failed to connect/login to IMAP server";
16
17 # Append message to folder
18 open(my $F, 'rfc822msg.txt');
19 $IMAP->append($FolderName, $F) || die $@;
20 close($F);
21
22 # Select folder and get first unseen message
23 $IMAP->select($FolderName) || die $@;
24 $MsgId = $IMAP->search('not', 'seen')->[0];
25
26 # Get message envelope and print some details
27 $MsgEV = $IMAP->fetch($MsgId, 'envelope')->{$MsgId}->{envelope};
28 print "From: " . $MsgEv->{From};
29 print "To: " . $MsgEv->{To};
30 print "Subject: " . $MsgEv->{Subject};
31
32 # Get message body structure
33 $MsgBS = $IMAP->fetch($MsgId, 'bodystructure')->{$MsgId}->{bodystructure};
34
35 # Find imap part number of text part of message
36 $MsgTxtHash = Mail::IMAPTalk::find_message($MsgBS);
37 $MsgPart = $MsgTxtHash->{text}->{'IMAP-Partnum'};
38
39 # Retrieve message text body
40 $MsgTxt = $IMAP->fetch($MsgId, "body[$MsgPart]")->{$MsgId}->{body};
41
42 $IMAP->logout();
43
45 This module communicates with an IMAP server. Each IMAP server command
46 is mapped to a method of this object.
47
48 Although other IMAP modules exist on CPAN, this has several advantages
49 over other modules.
50
51 · It parses the more complex IMAP structures like envelopes and body
52 structures into nice Perl data structures.
53
54 · It correctly supports atoms, quoted strings and literals at any
55 point. Some parsers in other modules aren't fully IMAP compatiable
56 and may break at odd times with certain messages on some servers.
57
58 · It allows large return values (eg. attachments on a message) to be
59 read directly into a file, rather than into memory.
60
61 · It includes some helper functions to find the actual text/plain or
62 text/html part of a message out of a complex MIME structure. It
63 also can find a list of attachements, and CID links for HTML
64 messages with attached images.
65
66 · It supports decoding of MIME headers to Perl utf-8 strings
67 automatically, so you don't have to deal with MIME encoded headers
68 (enabled optionally).
69
70 While the IMAP protocol does allow for asynchronous running of
71 commands, this module is designed to be used in a synchronous manner.
72 That is, you issue a command by calling a method, and the command will
73 block until the appropriate response is returned. The method will then
74 return the parsed results from the given command.
75
77 The object methods have been broken in several sections.
78
79 Sections
80 CONSTANTS
81 Lists the available constants the class uses.
82
83 CONSTRUCTOR
84 Explains all the options available when constructing a new instance
85 of the "Mail::IMAPTalk" class.
86
87 CONNECTION CONTROL METHODS
88 These are methods which control the overall IMAP connection object,
89 such as logging in and logging out, how results are parsed, how
90 folder names and message id's are treated, etc.
91
92 IMAP FOLDER COMMAND METHODS
93 These are methods to inspect, add, delete and rename IMAP folders
94 on the server.
95
96 IMAP MESSAGE COMMAND METHODS
97 These are methods to retrieve, delete, move and add messages
98 to/from IMAP folders.
99
100 HELPER METHODS
101 These are extra methods that users of this class might find useful.
102 They generally do extra parsing on returned structures to provide
103 higher level functionality.
104
105 INTERNAL METHODS
106 These are methods used internally by the "Mail::IMAPTalk" object to
107 get work done. They may be useful if you need to extend the class
108 yourself. Note that internal methods will always 'die' if they
109 encounter any errors.
110
111 INTERNAL SOCKET FUNCTIONS
112 These are functions used internally by the "Mail::IMAPTalk" object
113 to read/write data to/from the IMAP connection socket. The class
114 does its own buffering so if you want to read/write to the IMAP
115 socket, you should use these functions.
116
117 INTERNAL PARSING FUNCTIONS
118 These are functions used to parse the results returned from the
119 IMAP server into Perl style data structures.
120
121 Method results
122 All methods return undef on failure. There are four main modes of
123 failure:
124
125 1. An error occurred reading/writing to a socket. Maybe the server
126 closed it, or you're not connected to any server.
127 2. An error occurred parsing the response of an IMAP command. This is
128 usually only a problem if your IMAP server returns invalid data.
129 3. An IMAP command didn't return an 'OK' response.
130 4. The socket read operation timed out waiting for a response from the
131 server.
132
133 In each case, some readable form of error text is placed in $@, or you
134 can call the "get_last_error()" method. For commands which return
135 responses (e.g. fetch, getacl, etc), the result is returned. See each
136 command for details of the response result. For commands with no
137 response but which succeed (e.g. setacl, rename, etc) the result 'ok'
138 is generally returned.
139
140 Method parameters
141 All methods which send data to the IMAP server (e.g. "fetch()",
142 "search()", etc) have their arguments processed before they are sent.
143 Arguments may be specified in several ways:
144
145 scalar
146 The value is first checked and quoted if required. Values
147 containing [\000\012\015] are turned into literals, values
148 containing [\000-\040\{\} \%\*\"] are quoted by surrounding with a
149 "..." pair (any " themselves are turned into \"). undef is turned
150 into NIL
151
152 file ref
153 The contents of the file is sent as an IMAP literal. Note that
154 because IMAPTalk has to know the length of the file being sent,
155 this must be a true file reference that can be seeked and not just
156 some stream. The entire file will be sent regardless of the current
157 seek point.
158
159 scalar ref
160 The string/data in the referenced item should be sent as is, no
161 quoting will occur, and the data won't be sent as quoted or as a
162 literal regardless of the contents of the string/data.
163
164 array ref
165 Emits an opening bracket, and then each item in the array separated
166 by a space, and finally a closing bracket. Each item in the array
167 is processed by the same methods, so can be a scalar, file ref,
168 scalar ref, another array ref, etc.
169
170 hash ref
171 The hash reference should contain only 1 item. The key is a text
172 string which specifies what to do with the value item of the hash.
173
174 · 'Literal'
175
176 The string/data in the value is sent as an IMAP literal
177 regardless of the actual data in the string/data.
178
179 · 'Quote'
180
181 The string/data in the value is sent as an IMAP quoted string
182 regardless of the actual data in the string/data.
183
184 Examples:
185
186 # Password is automatically quoted to "nasty%*\"passwd"
187 $IMAP->login("joe", 'nasty%*"passwd');
188 # Append $MsgTxt as string
189 $IMAP->append("inbox", { Literal => $MsgTxt })
190 # Append MSGFILE contents as new message
191 $IMAP->append("inbox", \*MSGFILE ])
192
194 These constants relate to the standard 4 states that an IMAP connection
195 can be in. They are passed and returned from the "state()" method. See
196 RFC 3501 for more details about IMAP connection states.
197
198 Unconnected
199 Current not connected to any server.
200
201 Connected
202 Connected to a server, but not logged in.
203
204 Authenticated
205 Connected and logged into a server, but not current folder.
206
207 Selected
208 Connected, logged in and have 'select'ed a current folder.
209
211 Mail::IMAPTalk->new(%Options)
212 Creates new Mail::IMAPTalk object. The following options are
213 supported.
214
215 Connection Options
216 Server
217 The hostname or IP address to connect to. This must be supplied
218 unless the Socket option is supplied.
219
220 Port
221 The port number on the host to connect to. Defaults to 143 if
222 not supplied or 993 if not supplied and UseSSL is true.
223
224 UseSSL
225 If true, use an IO::Socket::SSL connection. All other SSL_*
226 arguments are passed to the IO::Socket::SSL constructor.
227
228 Socket
229 An existing socket to use as the connection to the IMAP server.
230 If you supply the Socket option, you should not supply a Server
231 or Port option.
232
233 This is useful if you want to create an SSL socket connection
234 using IO::Socket::SSL and then pass in the connected socket to
235 the new() call.
236
237 It's also useful in conjunction with the "release_socket()"
238 method described below for reusing the same socket beyond the
239 lifetime of the IMAPTalk object. See a description in the
240 section "release_socket()" method for more information.
241
242 You must have write flushing enabled for any socket you pass in
243 here so that commands will actually be sent, and responses
244 received, rather than just waiting and eventually timing out.
245 you can do this using the Perl "select()" call and $|
246 ($AUTOFLUSH) variable as shown below.
247
248 my $ofh = select($Socket); $| = 1; select ($ofh);
249
250 UseBlocking
251 For historical reasons, when reading from a socket, the module
252 sets the socket to non-blocking and does a select(). If you're
253 using an SSL socket that doesn't work, so you have to set
254 UseBlocking to true to use blocking reads instead.
255
256 State
257 If you supply a "Socket" option, you can specify the IMAP state
258 the socket is currently in, namely one of 'Unconnected',
259 'Connected', 'Authenticated' or 'Selected'. This defaults to
260 'Connected' if not supplied and the "Socket" option is
261 supplied.
262
263 ExpectGreeting
264 If supplied and true, and a socket is supplied via the "Socket"
265 option, checks that a greeting line is supplied by the server
266 and reads the greeting line.
267
268 PreserveINBOX
269 For historical reasons, the special name "INBOX" is rewritten
270 as Inbox because it looks nicer on the way out, and back on the
271 way in. If you want to preserve the name INBOX on the outside,
272 set this flag to true.
273
274 UseCompress
275 If you have the Compress::Zlib package installed, and the
276 server supports compress, then setting this flag to true will
277 cause compression to be enabled immediately after login.
278
279 Login Options
280 Username
281 The username to connect to the IMAP server as. If not supplied,
282 no login is attempted and the IMAP object is left in the
283 CONNECTED state. If supplied, you must also supply the
284 Password option and a login is attempted. If the login fails,
285 the connection is closed and undef is returned. If you want to
286 do something with a connection even if the login fails, don't
287 pass a Username option, but instead use the login method
288 described below.
289
290 Password
291 The password to use to login to the account.
292
293 AsUser
294 If the server supports it, access the server as this user
295 rather than the authenticate user.
296
297 See the "login" method for more information.
298
299 IMAP message/folder options
300 Uid Control whether message ids are message uids or not. This is 1
301 (on) by default because generally that's how most people want
302 to use it. This affects most commands that require/use/return
303 message ids (e.g. fetch, search, sort, etc)
304
305 RootFolder
306 If supplied, sets the root folder prefix. This is the same as
307 calling "set_root_folder()" with the value passed. If no value
308 is supplied, "set_root_folder()" is called with no value. See
309 the "set_root_folder()" method for more details.
310
311 Separator
312 If supplied, sets the folder name text string separator
313 character. Passed as the second parameter to the
314 "set_root_folder()" method.
315
316 AltRootRegexp
317 If supplied, passed along with RootFolder to the
318 "set_root_folder()" method.
319
320 Examples:
321
322 $imap = Mail::IMAPTalk->new(
323 Server => 'foo.com',
324 Port => 143,
325 Username => 'joebloggs',
326 Password => 'mypassword',
327 Separator => '.',
328 RootFolder => 'INBOX',
329 ) || die "Connection to foo.com failed. Reason: $@";
330
331 $imap = Mail::IMAPTalk->new(
332 Socket => $SSLSocket,
333 State => Mail::IMAPTalk::Authenticated,
334 Uid => 0
335 ) || die "Could not query on existing socket. Reason: $@";
336
338 login($User, $Password, [$AsUser])
339 Attempt to login user specified username and password.
340
341 The actual authentication may be done using the "LOGIN" or
342 "AUTHENTICATE" commands, depending on what the server advertises
343 support for.
344
345 If $AsUser is supplied, an attempt will be made to login on behalf
346 of that user.
347
348 logout()
349 Log out of IMAP server. This usually closes the servers connection
350 as well.
351
352 state(optional $State)
353 Set/get the current IMAP connection state. Returned or passed value
354 should be one of the constants (Unconnected, Connected,
355 Authenticated, Selected).
356
357 uid(optional $UidMode)
358 Get/set the UID status of all UID possible IMAP commands. If set
359 to 1, all commands that can take a UID are set to 'UID Mode', where
360 any ID sent to IMAPTalk is assumed to be a UID.
361
362 capability()
363 This method returns the IMAP servers capability command results.
364 The result is a hash reference of (lc(Capability) => 1) key value
365 pairs. This means you can do things like:
366
367 if ($IMAP->capability()->{quota}) { ... }
368
369 to test if the server has the QUOTA capability. If you just want a
370 list of capabilities, use the Perl 'keys' function to get a list of
371 keys from the returned hash reference.
372
373 namespace()
374 Returns the result of the IMAP servers namespace command.
375
376 noop()
377 Perform the standard IMAP 'noop' command which does nothing.
378
379 enable($option)
380 Enabled the given imap extension
381
382 is_open()
383 Returns true if the current socket connection is still open (e.g.
384 the socket hasn't been closed this end or the other end due to a
385 timeout).
386
387 set_root_folder($RootFolder, $Separator, $AltRootRegexp)
388 Change the root folder prefix. Some IMAP servers require that all
389 user folders/mailboxes live under a root folder prefix (current
390 versions of cyrus for example use 'INBOX' for personal folders and
391 'user' for other users folders). If no value is specified, it sets
392 it to ''. You might want to use the namespace() method to find out
393 what roots are available.
394
395 Setting this affects all commands that take a folder argument.
396 Basically if the foldername begins with root folder prefix, it's
397 left as is, otherwise the root folder prefix and separator char are
398 prefixed to the folder name.
399
400 The AltRootRegexp is a regexp that if the start of the folder name
401 matches, does not have $RootFolder preprended. You can use this to
402 protect other namespaces in your IMAP server.
403
404 Examples:
405
406 # This is what cyrus uses
407 $IMAP->set_root_folder('INBOX', '.', qr/^user/);
408
409 # Selects 'Inbox' (because 'Inbox' eq 'inbox' case insensitive)
410 $IMAP->select('Inbox');
411 # Selects 'INBOX.blah'
412 $IMAP->select('blah');
413 # Selects 'INBOX.Inbox.fred'
414 #IMAP->select('Inbox.fred');
415 # Selects 'user.john' (because 'user' is alt root)
416 #IMAP->select('user.john'); # Selects 'user.john'
417
418 _set_separator($Separator)
419 Checks if the given separator is the same as the one we used
420 before. If not, it calls set_root_folder to recreate the settings
421 with the new Separator.
422
423 literal_handle_control(optional $FileHandle)
424 Sets the mode whether to read literals as file handles or scalars.
425
426 You should pass a filehandle here that any literal will be read
427 into. To turn off literal reads into a file handle, pass a 0.
428
429 Examples:
430
431 # Read rfc822 text of message 3 into file
432 # (note that the file will have /r/n line terminators)
433 open(F, ">messagebody.txt");
434 $IMAP->literal_handle_control(\*F);
435 $IMAP->fetch(3, 'rfc822');
436 $IMAP->literal_handle_control(0);
437
438 release_socket($Close)
439 Release IMAPTalk's ownership of the current socket it's using so
440 it's not disconnected on DESTROY. This returns the socket, and
441 makes sure that the IMAPTalk object doesn't hold a reference to it
442 any more and the connection state is set to "Unconnected".
443
444 This means you can't call any methods on the IMAPTalk object any
445 more.
446
447 If the socket is being released and being closed, then $Close is
448 set to true.
449
450 get_last_error()
451 Returns a text string which describes the last error that occurred.
452
453 get_last_completion_response()
454 Returns the last completion response to the tagged command.
455
456 This is either the string "ok", "no" or "bad" (always lower case)
457
458 get_response_code($Response)
459 Returns the extra response data generated by a previous call. This
460 is most often used after calling select which usually generates
461 some set of the following sub-results.
462
463 · permanentflags
464
465 Array reference of flags which are stored permanently.
466
467 · uidvalidity
468
469 Whether the current UID set is valid. See the IMAP RFC for more
470 information on this. If this value changes, then all UIDs in
471 the folder have been changed.
472
473 · uidnext
474
475 The next UID number that will be assigned.
476
477 · exists
478
479 Number of messages that exist in the folder.
480
481 · recent
482
483 Number of messages that are recent in the folder.
484
485 Other possible responses are alert, newname, parse, trycreate,
486 appenduid, etc.
487
488 The values are stored in a hash keyed on the $Response item.
489 They're kept until either overwritten by a future response, or
490 explicitly cleared via clear_response_code().
491
492 Examples:
493
494 # Select inbox and get list of permanent flags, uidnext and number
495 # of message in the folder
496 $IMAP->select('inbox');
497 my $NMessages = $IMAP->get_response_code('exists');
498 my $PermanentFlags = $IMAP->get_response_code('permanentflags');
499 my $UidNext = $IMAP->get_response_code('uidnext');
500
501 clear_response_code($Response)
502 Clears any response code information. Response code information is
503 not normally cleared between calls.
504
505 parse_mode(ParseOption => $ParseMode)
506 Changes how results of fetch commands are parsed. Available options
507 are:
508
509 BodyStructure
510 Parse bodystructure into more Perl-friendly structure See the
511 FETCH RESULTS section.
512
513 Envelope
514 Parse envelopes into more Perl-friendly structure See the FETCH
515 RESULTS section.
516
517 Annotation
518 Parse annotation (from RFC 5257) into more Perl-friendly
519 structure See the FETCH RESULTS section.
520
521 EnvelopeRaw
522 If parsing envelopes, create To/Cc/Bcc and
523 Raw-To/Raw-Cc/Raw-Bcc entries which are array refs of 4 entries
524 each as returned by the IMAP server.
525
526 DecodeUTF8
527 If parsing envelopes, decode any MIME encoded headers into Perl
528 UTF-8 strings.
529
530 For this to work, you must have 'used' Mail::IMAPTalk with:
531
532 use Mail::IMAPTalk qw(:utf8support ...)
533
534 set_tracing($Tracer)
535 Allows you to trace both IMAP input and output sent to the server
536 and returned from the server. This is useful for debugging. Returns
537 the previous value of the tracer and then sets it to the passed
538 value. Possible values for $Tracer are:
539
540 0 Disable all tracing.
541
542 1 Print to STDERR.
543
544 Code ref
545 Call code ref for each line input and output. Pass line as
546 parameter.
547
548 Glob ref
549 Print to glob.
550
551 Scalar ref
552 Appends to the referenced scalar.
553
554 Note: literals are never passed to the tracer.
555
556 set_unicode_folders($Unicode)
557 $Unicode should be 1 or 0
558
559 Sets whether folder names are expected and returned as perl unicode
560 strings.
561
562 The default is currently 0, BUT YOU SHOULD NOT ASSUME THIS, because
563 it will probably change in the future.
564
565 If you want to work with perl unicode strings for folder names, you
566 should call
567 $ImapTalk->set_unicode_folders(1) and IMAPTalk will automatically
568 encode the unicode strings into IMAP-UTF7 when sending to the IMAP
569 server, and will also decode IMAP-UTF7 back into perl unicode
570 strings when returning results from the IMAP server.
571
572 If you want to work with folder names in IMAP-UTF7 bytes, then call
573 $ImapTalk->set_unicode_folders(0) and IMAPTalk will leave folder
574 names as bytes when sending to and returning results from the IMAP
575 server.
576
578 Note: In all cases where a folder name is used, the folder name is
579 first manipulated according to the current root folder prefix as
580 described in "set_root_folder()".
581
582 select($FolderName, @Opts)
583 Perform the standard IMAP 'select' command to select a folder for
584 retrieving/moving/adding messages. If $Opts{ReadOnly} is true, the
585 IMAP EXAMINE verb is used instead of SELECT.
586
587 Mail::IMAPTalk will cache the currently selected folder, and if you
588 issue another ->select("XYZ") for the folder that is already
589 selected, it will just return immediately. This can confuse code
590 that expects to get side effects of a select call. For that case,
591 call ->unselect() first, then ->select().
592
593 unselect()
594 Performs the standard IMAP unselect command.
595
596 examine($FolderName)
597 Perform the standard IMAP 'examine' command to select a folder in
598 read only mode for retrieving messages. This is the same as
599 "select($FolderName, 1)". See "select()" for more details.
600
601 create($FolderName)
602 Perform the standard IMAP 'create' command to create a new folder.
603
604 delete($FolderName)
605 Perform the standard IMAP 'delete' command to delete a folder.
606
607 localdelete($FolderName)
608 Perform the IMAP 'localdelete' command to delete a folder (doesn't
609 delete subfolders even of INBOX, is always immediate.
610
611 rename($OldFolderName, $NewFolderName)
612 Perform the standard IMAP 'rename' command to rename a folder.
613
614 list($Reference, $Name)
615 Perform the standard IMAP 'list' command to return a list of
616 available folders.
617
618 xlist($Reference, $Name)
619 Perform the IMAP 'xlist' extension command to return a list of
620 available folders and their special use attributes.
621
622 id($key = $value, ...)>
623 Perform the IMAP extension command 'id'
624
625 lsub($Reference, $Name)
626 Perform the standard IMAP 'lsub' command to return a list of
627 subscribed folders
628
629 subscribe($FolderName)
630 Perform the standard IMAP 'subscribe' command to subscribe to a
631 folder.
632
633 unsubscribe($FolderName)
634 Perform the standard IMAP 'unsubscribe' command to unsubscribe from
635 a folder.
636
637 check()
638 Perform the standard IMAP 'check' command to checkpoint the current
639 folder.
640
641 setacl($FolderName, $User, $Rights)
642 Perform the IMAP 'setacl' command to set the access control list
643 details of a folder/mailbox. See RFC 4314 for more details on the
644 IMAP ACL extension. $User is the user name to set the access rights
645 for. $Rights is either a list of absolute rights to set, or a list
646 prefixed by a - to remove those rights, or a + to add those rights.
647
648 l - lookup (mailbox is visible to LIST/LSUB commands)
649 r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL,
650 SEARCH, COPY from mailbox)
651 s - keep seen/unseen information across sessions (STORE SEEN flag)
652 w - write (STORE flags other than SEEN and DELETED)
653 i - insert (perform APPEND, COPY into mailbox)
654 p - post (send mail to submission address for mailbox, not enforced
655 by IMAP4 itself)
656 k - create mailboxes (CREATE new sub-mailboxes in any
657 implementation-defined hierarchy, parent mailbox for the new
658 mailbox name in RENAME)
659 x - delete mailbox (DELETE mailbox, old mailbox name in RENAME)
660 t - delete messages (set or clear \DELETED flag via STORE, set
661 \DELETED flag during APPEND/COPY)
662 e - perform EXPUNGE and expunge as a part of CLOSE
663 a - administer (perform SETACL)
664
665 Due to ambiguity in RFC 2086, some existing RFC 2086 server
666 implementations use the "c" right to control the DELETE command.
667 Others chose to use the "d" right to control the DELETE command.
668 See the 2.1.1. Obsolete Rights in RFC 4314 for more details.
669
670 c - create (CREATE new sub-mailboxes in any implementation-defined
671 hierarchy)
672 d - delete (STORE DELETED flag, perform EXPUNGE)
673
674 The standard access control configurations for cyrus are
675
676 read = "lrs"
677 post = "lrsp"
678 append = "lrsip"
679 write = "lrswipcd"
680 all = "lrswipcda"
681
682 Examples:
683
684 # Get full access for user 'joe' on his own folder
685 $IMAP->setacl('user.joe', 'joe', 'lrswipcda') || die "IMAP error: $@";
686 # Remove write, insert, post, create, delete access for user 'andrew'
687 $IMAP->setacl('user.joe', 'andrew', '-wipcd') || die "IMAP error: $@";
688 # Add lookup, read, keep unseen information for user 'paul'
689 $IMAP->setacl('user.joe', 'paul', '+lrs') || die "IMAP error: $@";
690
691 getacl($FolderName)
692 Perform the IMAP 'getacl' command to get the access control list
693 details of a folder/mailbox. See RFC 4314 for more details on the
694 IMAP ACL extension. Returns an array of pairs. Each pair is a
695 username followed by the access rights for that user. See setacl
696 for more information on access rights.
697
698 Examples:
699
700 my $Rights = $IMAP->getacl('user.joe') || die "IMAP error : $@";
701 $Rights = [
702 'joe', 'lrs',
703 'andrew', 'lrswipcda'
704 ];
705
706 $IMAP->setacl('user.joe', 'joe', 'lrswipcda') || die "IMAP error : $@";
707 $IMAP->setacl('user.joe', 'andrew', '-wipcd') || die "IMAP error : $@";
708 $IMAP->setacl('user.joe', 'paul', '+lrs') || die "IMAP error : $@";
709
710 $Rights = $IMAP->getacl('user.joe') || die "IMAP error : $@";
711 $Rights = [
712 'joe', 'lrswipcd',
713 'andrew', 'lrs',
714 'paul', 'lrs'
715 ];
716
717 deleteacl($FolderName, $Username)
718 Perform the IMAP 'deleteacl' command to delete all access control
719 information for the given user on the given folder. See setacl for
720 more information on access rights.
721
722 Examples:
723
724 my $Rights = $IMAP->getacl('user.joe') || die "IMAP error : $@";
725 $Rights = [
726 'joe', 'lrswipcd',
727 'andrew', 'lrs',
728 'paul', 'lrs'
729 ];
730
731 # Delete access information for user 'andrew'
732 $IMAP->deleteacl('user.joe', 'andrew') || die "IMAP error : $@";
733
734 $Rights = $IMAP->getacl('user.joe') || die "IMAP error : $@";
735 $Rights = [
736 'joe', 'lrswipcd',
737 'paul', 'lrs'
738 ];
739
740 setquota($FolderName, $QuotaDetails)
741 Perform the IMAP 'setquota' command to set the usage quota details
742 of a folder/mailbox. See RFC 2087 for details of the IMAP quota
743 extension. $QuotaDetails is a bracketed list of limit item/value
744 pairs which represent a particular type of limit and the value to
745 set it to. Current limits are:
746
747 STORAGE - Sum of messages' RFC822.SIZE, in units of 1024 octets
748 MESSAGE - Number of messages
749
750 Examples:
751
752 # Set maximum size of folder to 50M and 1000 messages
753 $IMAP->setquota('user.joe', '(storage 50000)') || die "IMAP error: $@";
754 $IMAP->setquota('user.john', '(messages 1000)') || die "IMAP error: $@";
755 # Remove quotas
756 $IMAP->setquota('user.joe', '()') || die "IMAP error: $@";
757
758 getquota($FolderName)
759 Perform the standard IMAP 'getquota' command to get the quota
760 details of a folder/mailbox. See RFC 2087 for details of the IMAP
761 quota extension. Returns an array reference to quota limit
762 triplets. Each triplet is made of: limit item, current value,
763 maximum value.
764
765 Note that this only returns the quota for a folder if it actually
766 has had a quota set on it. It's possible that a parent folder might
767 have a quota as well which affects sub-folders. Use the
768 getquotaroot to find out if this is true.
769
770 Examples:
771
772 my $Result = $IMAP->getquota('user.joe') || die "IMAP error: $@";
773 $Result = [
774 'STORAGE', 31, 50000,
775 'MESSAGE', 5, 1000
776 ];
777
778 getquotaroot($FolderName)
779 Perform the IMAP 'getquotaroot' command to get the quota details of
780 a folder/mailbox and possible root quota as well. See RFC 2087 for
781 details of the IMAP quota extension. The result of this command is
782 a little complex. Unfortunately it doesn't map really easily into
783 any structure since there are several different responses.
784
785 Basically it's a hash reference. The 'quotaroot' item is the
786 response which lists the root quotas that apply to the given
787 folder. The first item is the folder name, and the remaining items
788 are the quota root items. There is then a hash item for each quota
789 root item. It's probably easiest to look at the example below.
790
791 Examples:
792
793 my $Result = $IMAP->getquotaroot('user.joe.blah') || die "IMAP error: $@";
794 $Result = {
795 'quotaroot' => [
796 'user.joe.blah', 'user.joe', ''
797 ],
798 'user.joe' => [
799 'STORAGE', 31, 50000,
800 'MESSAGES', 5, 1000
801 ],
802 '' => [
803 'MESSAGES', 3498, 100000
804 ]
805 };
806
807 message_count($FolderName)
808 Return the number of messages in a folder. See also "status()" for
809 getting more information about messages in a folder.
810
811 status($FolderName, $StatusList)
812 Perform the standard IMAP 'status' command to retrieve status
813 information about a folder/mailbox.
814
815 The $StatusList is a bracketed list of folder items to obtain the
816 status of. Can contain: messages, recent, uidnext, uidvalidity,
817 unseen.
818
819 The return value is a hash reference of lc(status-item) => value.
820
821 Examples:
822
823 my $Res = $IMAP->status('inbox', '(MESSAGES UNSEEN)');
824
825 $Res = {
826 'messages' => 8,
827 'unseen' => 2
828 };
829
830 multistatus($StatusList, @FolderNames)
831 Performs many IMAP 'status' commands on a list of folders. Sends
832 all the commands at once and wait for responses. This speeds up
833 latency issues.
834
835 Returns a hash ref of folder name => status results.
836
837 If an error occurs, the annotation result is a scalar ref to the
838 completion response string (eg 'bad', 'no', etc)
839
840 getannotation($FolderName, $Entry, $Attribute)
841 Perform the IMAP 'getannotation' command to get the annotation(s)
842 for a mailbox. See imap-annotatemore extension for details.
843
844 Examples:
845
846 my $Result = $IMAP->getannotation('user.joe.blah', '/*' '*') || die "IMAP error: $@";
847 $Result = {
848 'user.joe.blah' => {
849 '/vendor/cmu/cyrus-imapd/size' => {
850 'size.shared' => '5',
851 'content-type.shared' => 'text/plain',
852 'value.shared' => '19261'
853 },
854 '/vendor/cmu/cyrus-imapd/lastupdate' => {
855 'size.shared' => '26',
856 'content-type.shared' => 'text/plain',
857 'value.shared' => '26-Mar-2004 13:31:56 -0800'
858 },
859 '/vendor/cmu/cyrus-imapd/partition' => {
860 'size.shared' => '7',
861 'content-type.shared' => 'text/plain',
862 'value.shared' => 'default'
863 }
864 }
865 };
866
867 getmetadata($FolderName, [ \%Options ], @Entries)
868 Perform the IMAP 'getmetadata' command to get the metadata items
869 for a mailbox. See RFC 5464 for details.
870
871 If $Options is passed, it is a hashref of options to set.
872
873 If foldername is the empty string, gets server annotations
874
875 Examples:
876
877 my $Result = $IMAP->getmetadata('user.joe.blah', {depth => 'infinity'}, '/shared') || die "IMAP error: $@";
878 $Result = {
879 'user.joe.blah' => {
880 '/shared/vendor/cmu/cyrus-imapd/size' => '19261',
881 '/shared/vendor/cmu/cyrus-imapd/lastupdate' => '26-Mar-2004 13:31:56 -0800',
882 '/shared/vendor/cmu/cyrus-imapd/partition' => 'default',
883 }
884 };
885
886 my $Result = $IMAP->getmetadata('', "/shared/comment");
887 $Result => {
888 '' => {
889 '/shared/comment' => "Shared comment",
890 }
891 };
892
893 multigetmetadata(\@Entries, @FolderNames)
894 Performs many IMAP 'getmetadata' commands on a list of folders.
895 Sends all the commands at once and wait for responses. This speeds
896 up latency issues.
897
898 Returns a hash ref of folder name => metadata results.
899
900 If an error occurs, the annotation result is a scalar ref to the
901 completion response string (eg 'bad', 'no', etc)
902
903 setannotation($FolderName, $Entry, [ $Attribute, $Value ])
904 Perform the IMAP 'setannotation' command to get the annotation(s)
905 for a mailbox. See imap-annotatemore extension for details.
906
907 Examples:
908
909 my $Result = $IMAP->setannotation('user.joe.blah', '/comment', [ 'value.priv' 'A comment' ])
910 || die "IMAP error: $@";
911
912 setmetadata($FolderName, $Name, $Value, $Name2, $Value2)
913 Perform the IMAP 'setmetadata' command. See RFC 5464 for details.
914
915 Examples:
916
917 my $Result = $IMAP->setmetadata('user.joe.blah', '/comment', 'A comment')
918 || die "IMAP error: $@";
919
920 close()
921 Perform the standard IMAP 'close' command to expunge deleted
922 messages from the current folder and return to the Authenticated
923 state.
924
925 idle(\&Callback, [ $Timeout ])
926 Perform an IMAP idle call. Call given callback for each IDLE event
927 received.
928
929 If the callback returns 0, the idle continues. If the callback
930 returns 1, the idle is finished and this call returns.
931
932 If no timeout is passed, will continue to idle until the callback
933 returns 1 or the server disconnects.
934
935 If a timeout is passed (including a 0 timeout), the call will
936 return if no events are received within the given time. It will
937 return the result of the DONE command, and set
938 $Self->get_response_code('timeout') to true.
939
940 If the server closes the connection with a "bye" response, it will
941 return undef and $@ =~ /bye/ will be true with the remainder of the
942 bye line following.
943
945 fetch([ \%ParseMode ], $MessageIds, $MessageItems)
946 Perform the standard IMAP 'fetch' command to retrieve the specified
947 message items from the specified message IDs.
948
949 The first parameter can be an optional hash reference that
950 overrides particular parse mode parameters just for this fetch. See
951 "parse_mode" for possible keys.
952
953 $MessageIds can be one of two forms:
954
955 1. A text string with a comma separated list of message ID's or
956 message ranges separated by colons. A '*' represents the
957 highest message number.
958
959 Examples:
960
961 · '1' - first message
962
963 · '1,2,5'
964
965 · '1:*' - all messages
966
967 · '1,3:*' - all but message 2
968
969 Note that , separated lists and : separated ranges can be
970 mixed, but to make sure a certain hack works, if a '*' is used,
971 it must be the last character in the string.
972
973 2. An array reference with a list of message ID's or ranges. The
974 array contents are "join(',', ...)"ed together.
975
976 Note: If the "uid()" state has been set to true, then all message
977 ID's must be message UIDs.
978
979 $MessageItems can be one of, or a bracketed list of:
980
981 · uid
982
983 · flags
984
985 · internaldate
986
987 · envelope
988
989 · bodystructure
990
991 · body
992
993 · body[section]<partial>
994
995 · body.peek[section]<partial>
996
997 · rfc822
998
999 · rfc822.header
1000
1001 · rfc822.size
1002
1003 · rfc822.text
1004
1005 · fast
1006
1007 · all
1008
1009 · full
1010
1011 It would be a good idea to see RFC 3501 for what all these means.
1012
1013 Examples:
1014
1015 my $Res = $IMAP->fetch('1:*', 'rfc822.size');
1016 my $Res = $IMAP->fetch([1,2,3], '(bodystructure envelope)');
1017
1018 Return results:
1019
1020 The results returned by the IMAP server are parsed into a Perl
1021 structure. See the section FETCH RESULTS for all the interesting
1022 details.
1023
1024 Note that message can disappear on you, so you may not get back all
1025 the entries you expect in the hash
1026
1027 There is one piece of magic. If your request is for a single uid,
1028 (eg "123"), and no data is return, we return undef, because it's
1029 easier to handle as an error condition.
1030
1031 copy($MsgIds, $ToFolder)
1032 Perform standard IMAP copy command to copy a set of messages from
1033 one folder to another.
1034
1035 append($FolderName, optional $MsgFlags, optional $MsgDate,
1036 $MessageData)
1037 Perform standard IMAP append command to append a new message into a
1038 folder.
1039
1040 The $MessageData to append can either be a Perl scalar containing
1041 the data, or a file handle to read the data from. In each case, the
1042 data must be in proper RFC 822 format with \r\n line terminators.
1043
1044 Any optional fields not needed should be removed, not left blank.
1045
1046 Examples:
1047
1048 # msg.txt should have \r\n line terminators
1049 open(F, "msg.txt");
1050 $IMAP->append('inbox', \*F);
1051
1052 my $MsgTxt =<<MSG;
1053 From: blah\@xyz.com
1054 To: whoever\@whereever.com
1055 ...
1056 MSG
1057
1058 $MsgTxt =~ s/\n/\015\012/g;
1059 $IMAP->append('inbox', { Literal => $MsgTxt });
1060
1061 search($MsgIdSet, @SearchCriteria)
1062 Perform standard IMAP search command. The result is an array
1063 reference to a list of message IDs (or UIDs if in Uid mode) of
1064 messages that are in the $MsgIdSet and also meet the search
1065 criteria.
1066
1067 @SearchCriteria is a list of search specifications, for example to
1068 look for ASCII messages bigger than 2000 bytes you would set the
1069 list to be:
1070
1071 my @SearchCriteria = ('CHARSET', 'US-ASCII', 'LARGER', '2000');
1072
1073 Examples:
1074
1075 my $Res = $IMAP->search('1:*', 'NOT', 'DELETED');
1076 $Res = [ 1, 2, 5 ];
1077
1078 store($MsgIdSet, $FlagOperation, $Flags)
1079 Perform standard IMAP store command. Changes the flags associated
1080 with a set of messages.
1081
1082 Examples:
1083
1084 $IMAP->store('1:*', '+flags', '(\\deleted)');
1085 $IMAP->store('1:*', '-flags.silent', '(\\read)');
1086
1087 expunge()
1088 Perform standard IMAP expunge command. This actually deletes any
1089 messages marked as deleted.
1090
1091 uidexpunge($MsgIdSet)
1092 Perform IMAP uid expunge command as per RFC 2359.
1093
1094 sort($SortField, $CharSet, @SearchCriteria)
1095 Perform extension IMAP sort command. The result is an array
1096 reference to a list of message IDs (or UIDs if in Uid mode) in
1097 sorted order.
1098
1099 It would probably be a good idea to look at the sort RFC 5256
1100 details at somewhere like : http://www.ietf.org/rfc/rfc5256.txt
1101
1102 Examples:
1103
1104 my $Res = $IMAP->sort('(subject)', 'US-ASCII', 'NOT', 'DELETED');
1105 $Res = [ 5, 2, 3, 1, 4 ];
1106
1107 thread($ThreadType, $CharSet, @SearchCriteria)
1108 Perform extension IMAP thread command. The $ThreadType should be
1109 one of 'REFERENCES' or 'ORDEREDSUBJECT'. You should check the
1110 "capability()" of the server to see if it supports one or both of
1111 these.
1112
1113 Examples
1114
1115 my $Res = $IMAP->thread('REFERENCES', 'US-ASCII', 'NOT', 'DELETED');
1116 $Res = [ [10, 15, 20], [11], [ [ 12, 16 ], [13, 17] ];
1117
1118 fetch_flags($MessageIds)
1119 Perform an IMAP 'fetch flags' command to retrieve the specified
1120 flags for the specified messages.
1121
1122 This is just a special fast path version of "fetch".
1123
1124 fetch_meta($MessageIds, @MetaItems)
1125 Perform an IMAP 'fetch' command to retrieve the specified meta
1126 items. These must be simple items that return only atoms (eg no
1127 flags, bodystructure, body, envelope, etc)
1128
1129 This is just a special fast path version of "fetch".
1130
1132 Methods provided by extensions to the cyrus IMAP server
1133
1134 Note: In all cases where a folder name is used, the folder name is
1135 first manipulated according to the current root folder prefix as
1136 described in "set_root_folder()".
1137
1138 xrunannotator($MessageIds)
1139 Run the xannotator command on the given message id's
1140
1141 xconvfetch($CIDs, $ChangedSince, $Items)
1142 Use the server XCONVFETCH command to fetch information about
1143 messages in a conversation.
1144
1145 CIDs can be a single CID or an array ref of CIDs.
1146
1147 my $Res = $IMAP->xconvfetch('2fc2122a109cb6c8', 0, '(uid cid envelope)')
1148 $Res = {
1149 state => { CID => [ HighestModSeq ], ... }
1150 folders => [ [ FolderName, UidValidity ], ..., ],
1151 found => [ [ FolderIndex, Uid, { Details } ], ... ],
1152 }
1153
1154 Note: FolderIndex is an integer index into the folders list
1155
1156 xconvmeta($CIDs, $Items)
1157 Use the server XCONVMETA command to fetch information about a
1158 conversation.
1159
1160 CIDs can be a single CID or an array ref of CIDs.
1161
1162 my $Res = $IMAP->xconvmeta('2fc2122a109cb6c8', '(senders exists unseen)')
1163 $Res = {
1164 CID1 => { senders => { name => ..., email => ... }, exists => ..., unseen => ..., ... },
1165 CID2 => { ... },
1166 }
1167
1168 xconvsort($Sort, $Window, $Charset, @SearchParams)
1169 Use the server XCONVSORT command to fetch exemplar conversation
1170 messages in a mailbox.
1171
1172 my $Res = $IMAP->xconvsort( [ qw(reverse arrival) ], [ 'conversations', position => [1, 10] ], 'utf-8', 'ALL')
1173 $Res = {
1174 sort => [ Uid, ... ],
1175 position => N,
1176 highestmodseq => M,
1177 uidvalidity => V,
1178 uidnext => U,
1179 total => R,
1180 }
1181
1182 xconvupdates($Sort, $Window, $Charset, @SearchParams)
1183 Use the server XCONVUPDATES command to find changed exemplar
1184 messages
1185
1186 my $Res = $IMAP->xconvupdates( [ qw(reverse arrival) ], [ 'conversations', changedsince => [ $mod_seq, $uid_next ] ], 'utf-8', 'ALL');
1187 $Res = {
1188 added => [ [ Uid, Pos ], ... ],
1189 removed => [ Uid, ... ],
1190 changed => [ CID, ... ],
1191 highestmodseq => M,
1192 uidvalidity => V,
1193 uidnext => U,
1194 total => R,
1195 }
1196
1197 xconvmultisort($Sort, $Window, $Charset, @SearchParams)
1198 Use the server XCONVMULTISORT command to fetch messages across all
1199 mailboxes
1200
1201 my $Res = $IMAP->xconvmultisort( [ qw(reverse arrival) ], [ 'conversations', postion => [1,10] ], 'utf-8', 'ALL')
1202 $Res = {
1203 folders => [ [ FolderName, UidValidity ], ... ],
1204 sort => [ FolderIndex, Uid ], ... ],
1205 position => N,
1206 highestmodseq => M,
1207 total => R,
1208 }
1209
1210 Note: FolderIndex is an integer index into the folders list
1211
1212 xsnippets($Items, $Charset, @SearchParams)
1213 Use the server XSNIPPETS command to fetch message search snippets
1214
1215 my $Res = $IMAP->xsnippets( [ [ FolderName, UidValidity, [ Uid, ... ] ], ... ], 'utf-8', 'ALL')
1216 $Res = {
1217 folders => [ [ FolderName, UidValidity ], ... ],
1218 snippets => [
1219 [ FolderIndex, Uid, Location, Snippet ],
1220 ...
1221 ]
1222 ]
1223
1224 Note: FolderIndex is an integer index into the folders list
1225
1227 get_body_part($BodyStruct, $PartNum)
1228 This is a helper function that can be used to further parse the
1229 results of a fetched bodystructure. Given a top level body
1230 structure, and a part number, it returns the reference to the
1231 bodystructure sub part which that part number refers to.
1232
1233 Examples:
1234
1235 # Fetch body structure
1236 my $FR = $IMAP->fetch(1, 'bodystructure');
1237 my $BS = $FR->{1}->{bodystructure};
1238
1239 # Parse further to find particular sub part
1240 my $P12 = $IMAP->get_body_part($BS, '1.2');
1241 $P12->{'IMAP->Partnum'} eq '1.2' || die "Unexpected IMAP part number";
1242
1243 find_message($BodyStruct)
1244 This is a helper function that can be used to further parse the
1245 results of a fetched bodystructure. It returns a hash reference
1246 with the following items.
1247
1248 text => $best_text_part
1249 html => $best_html_part (optional)
1250 textlist => [ ... text/html (if no alt text bits)/image (if inline) parts ... ]
1251 htmllist => [ ... text (if no alt html bits)/html/image (if inline) parts ... ]
1252 att => [ {
1253 bs => $part, text => 0/1, html => 0/1, msg => 1/0,
1254 }, { ... }, ... ]
1255
1256 For instance, consider a message with text and html pages that's
1257 then gone through a list software manager that attaches a
1258 header/footer
1259
1260 multipart/mixed
1261 text/plain, cd=inline - A
1262 multipart/mixed
1263 multipart/alternative
1264 multipart/mixed
1265 text/plain, cd=inline - B
1266 image/jpeg, cd=inline - C
1267 text/plain, cd=inline - D
1268 multipart/related
1269 text/html - E
1270 image/jpeg - F
1271 image/jpeg, cd=attachment - G
1272 application/x-excel - H
1273 message/rfc822 - J
1274 text/plain, cd=inline - K
1275
1276 In this case, we'd have the following list items
1277
1278 text => B
1279 html => E
1280 textlist => [ A, B, C, D, K ]
1281 htmllist => [ A, E, K ]
1282 att => [
1283 { bs => C, text => 1, html => 1 },
1284 { bs => F, text => 1, html => 0 },
1285 { bs => G, text => 1, html => 1 },
1286 { bs => H, text => 1, html => 1 },
1287 { bs => J, text => 0, html => 0, msg => 1 },
1288 ]
1289
1290 Examples:
1291
1292 # Fetch body structure
1293 my $FR = $IMAP->fetch(1, 'bodystructure');
1294 my $BS = $FR->{1}->{bodystructure};
1295
1296 # Parse further to find message components
1297 my $MC = $IMAP->find_message($BS);
1298 $MC = { 'plain' => ... text body struct ref part ...,
1299 'html' => ... html body struct ref part (if present) ...
1300 'htmllist' => [ ... html body struct ref parts (if present) ... ] };
1301
1302 # Now get the text part of the message
1303 my $MT = $IMAP->fetch(1, 'body[' . $MC->{text}->{'IMAP-Part'} . ']');
1304
1305 generate_cid( $Token, $PartBS )
1306 This method generates a ContentID based on $Token and $PartBS.
1307
1308 The same value should always be returned for a given $Token and
1309 $PartBS
1310
1311 build_cid_map($BodyStruct, [ $IMAP, $Uid, $GenCidToken ])
1312 This is a helper function that can be used to further parse the
1313 results of a fetched bodystructure. It recursively parses the
1314 bodystructure and returns a hash of Content-ID to bodystruct part
1315 references. This is useful when trying to determine CID links from
1316 an HTML message.
1317
1318 If you pass a Mail::IMAPTalk object as the second parameter, the
1319 CID map built may be even more detailed. It seems some stupid
1320 versions of exchange put details in the Content-Location header
1321 rather than the Content-Type header. If that's the case, this will
1322 try and fetch the header from the message
1323
1324 Examples:
1325
1326 # Fetch body structure
1327 my $FR = $IMAP->fetch(1, 'bodystructure');
1328 my $BS = $FR->{1}->{bodystructure};
1329
1330 # Parse further to get CID links
1331 my $CL = build_cid_map($BS);
1332 $CL = { '2958293123' => ... ref to body part ..., ... };
1333
1334 obliterate($CyrusName)
1335 Given a username (optionally username\@domain) immediately delete
1336 all messages belonging to this user. Uses LOCALDELETE. Quite
1337 FastMail Patchd Cyrus specific.
1338
1340 By default, these methods do nothing, but you can dervice from
1341 Mail::IMAPTalk and override these methods to trap any things you want
1342 to catch
1343
1344 cb_switch_folder($CurrentFolder, $NewFolder)
1345 Called when the currently selected folder is being changed (eg
1346 'select' called and definitely a different folder is being
1347 selected, or 'unselect' methods called)
1348
1349 cb_folder_changed($Folder)
1350 Called when a command changes the contents of a folder (eg copy,
1351 append, etc). $Folder is the name of the folder that's changing.
1352
1354 The 'fetch' operation is probably the most common thing you'll do with
1355 an IMAP connection. This operation allows you to retrieve information
1356 about a message or set of messages, including header fields, flags or
1357 parts of the message body.
1358
1359 "Mail::IMAPTalk" will always parse the results of a fetch call into a
1360 Perl like structure, though 'bodystructure', 'envelope' and 'uid'
1361 responses may have additional parsing depending on the "parse_mode"
1362 state and the "uid" state (see below).
1363
1364 For an example case, consider the following IMAP commands and responses
1365 (C is what the client sends, S is the server response).
1366
1367 C: a100 fetch 5,6 (flags rfc822.size uid)
1368 S: * 1 fetch (UID 1952 FLAGS (\recent \seen) RFC822.SIZE 1150)
1369 S: * 2 fetch (UID 1958 FLAGS (\recent) RFC822.SIZE 110)
1370 S: a100 OK Completed
1371
1372 The fetch command can be sent by calling:
1373
1374 my $Res = $IMAP->fetch('1:*', '(flags rfc822.size uid)');
1375
1376 The result in response will look like this:
1377
1378 $Res = {
1379 1 => {
1380 'uid' => 1952,
1381 'flags' => [ '\\recent', '\\seen' ],
1382 'rfc822.size' => 1150
1383 },
1384 2 => {
1385 'uid' => 1958,
1386 'flags' => [ '\\recent' ],
1387 'rfc822.size' => 110
1388 }
1389 };
1390
1391 A couple of points to note:
1392
1393 1. The message IDs have been turned into a hash from message ID to
1394 fetch response result.
1395
1396 2. The response items (e.g. uid, flags, etc) have been turned into a
1397 hash for each message, and also changed to lower case values.
1398
1399 3. Other bracketed (...) lists have become array references.
1400
1401 In general, this is how all fetch responses are parsed. There is one
1402 major difference however when the IMAP connection is in 'uid' mode. In
1403 this case, the message IDs in the main hash are changed to message
1404 UIDs, and the 'uid' entry in the inner hash is removed. So the above
1405 example would become:
1406
1407 my $Res = $IMAP->fetch('1:*', '(flags rfc822.size)');
1408
1409 $Res = {
1410 1952 => {
1411 'flags' => [ '\\recent', '\\seen' ],
1412 'rfc822.size' => 1150
1413 },
1414 1958 => {
1415 'flags' => [ '\\recent' ],
1416 'rfc822.size' => 110
1417 }
1418 };
1419
1420 Bodystructure
1421 When dealing with messages, we need to understand the MIME structure of
1422 the message, so we can work out what is the text body, what is
1423 attachments, etc. This is where the 'bodystructure' item from an IMAP
1424 server comes in.
1425
1426 C: a101 fetch 1 (bodystructure)
1427 S: * 1 fetch (BODYSTRUCTURE ("TEXT" "PLAIN" NIL NIL NIL "QUOTED-PRINTABLE" 255 11 NIL ("INLINE" NIL) NIL))
1428 S: a101 OK Completed
1429
1430 The fetch command can be sent by calling:
1431
1432 my $Res = $IMAP->fetch(1, 'bodystructure');
1433
1434 As expected, the resultant response would look like this:
1435
1436 $Res = {
1437 1 => {
1438 'bodystructure' => [
1439 'TEXT', 'PLAIN', undef, undef, undef, 'QUOTED-PRINTABLE',
1440 255, 11, UNDEF, [ 'INLINE', undef ], undef
1441 ]
1442 }
1443 };
1444
1445 However, if you set the "parse_mode(BodyStructure =" 1)>, then the
1446 result would be:
1447
1448 $Res = {
1449 '1' => {
1450 'bodystructure' => {
1451 'MIME-Type' => 'text',
1452 'MIME-Subtype' => 'plain',
1453 'MIME-TxtType' => 'text/plain',
1454 'Content-Type' => {},
1455 'Content-ID' => undef,
1456 'Content-Description' => undef,
1457 'Content-Transfer-Encoding' => 'QUOTED-PRINTABLE',
1458 'Size' => '3569',
1459 'Lines' => '94',
1460 'Content-MD5' => undef,
1461 'Disposition-Type' => 'inline',
1462 'Content-Disposition' => {},
1463 'Content-Language' => undef,
1464 'Remainder' => [],
1465 'IMAP-Partnum' => ''
1466 }
1467 }
1468 };
1469
1470 A couple of points to note here:
1471
1472 1. All the positional fields from the bodystructure list response have
1473 been turned into nicely named key/value hash items.
1474
1475 2. The MIME-Type and MIME-Subtype fields have been made lower case.
1476
1477 3. An IMAP-Partnum item has been added. The value in this field can be
1478 passed as the 'section' number of an IMAP body fetch call to
1479 retrieve the text of that IMAP section.
1480
1481 In general, the following items are defined for all body structures:
1482
1483 · MIME-Type
1484
1485 · MIME-Subtype
1486
1487 · Content-Type
1488
1489 · Disposition-Type
1490
1491 · Content-Disposition
1492
1493 · Content-Language
1494
1495 For all bodystructures EXCEPT those that have a MIME-Type of
1496 'multipart', the following are defined:
1497
1498 · Content-ID
1499
1500 · Content-Description
1501
1502 · Content-Transfer-Encoding
1503
1504 · Size
1505
1506 · Content-MD5
1507
1508 · Remainder
1509
1510 · IMAP-Partnum
1511
1512 For bodystructures where MIME-Type is 'text', an extra item 'Lines' is
1513 defined.
1514
1515 For bodystructures where MIME-Type is 'message' and MIME-Subtype is
1516 'rfc822', the extra items 'Message-Envelope', 'Message-Bodystructure'
1517 and 'Message-Lines' are defined. The 'Message-Bodystructure' item is
1518 itself a reference to an entire bodystructure hash with all the format
1519 information of the contained message. The 'Message-Envelope' item is a
1520 hash structure with the message header information. See the Envelope
1521 entry below.
1522
1523 For bodystructures where MIME-Type is 'multipart', an extra item
1524 'MIME-Subparts' is defined. The 'MIME-Subparts' item is an array
1525 reference, with each item being a reference to an entire bodystructure
1526 hash with all the format information of each MIME sub-part.
1527
1528 For further processing, you can use the find_message() function. This
1529 will analyse the body structure and find which part corresponds to the
1530 main text/html message parts to display. You can also use the
1531 find_cid_parts() function to find CID links in an html message.
1532
1533 Envelope
1534 The envelope structure contains most of the addressing header fields
1535 from an email message. The following shows an example envelope fetch
1536 (the response from the IMAP server has been neatened up here)
1537
1538 C: a102 fetch 1 (envelope)
1539 S: * 1 FETCH (ENVELOPE
1540 ("Tue, 7 Nov 2000 08:31:21 UT" # Date
1541 "FW: another question" # Subject
1542 (("John B" NIL "jb" "abc.com")) # From
1543 (("John B" NIL "jb" "abc.com")) # Sender
1544 (("John B" NIL "jb" "abc.com")) # Reply-To
1545 (("Bob H" NIL "bh" "xyz.com") # To
1546 ("K Jones" NIL "kj" "lmn.com"))
1547 NIL # Cc
1548 NIL # Bcc
1549 NIL # In-Reply-To
1550 NIL) # Message-ID
1551 )
1552 S: a102 OK Completed
1553
1554 The fetch command can be sent by calling:
1555
1556 my $Res = $IMAP->fetch(1, 'envelope');
1557
1558 And you get the idea of what the resultant response would be. Again if
1559 you change "parse_mode(Envelope =" 1)>, you get a neat structure as
1560 follows:
1561
1562 $Res = {
1563 '1' => {
1564 'envelope' => {
1565 'Date' => 'Tue, 7 Nov 2000 08:31:21 UT',
1566 'Subject' => 'FW: another question',
1567 'From' => '"John B" <jb@abc.com>',
1568 'Sender' => '"John B" <jb@abc.com>',
1569 'Reply-To' => '"John B" <jb@abc.com>',
1570 'To' => '"Bob H" <bh@xyz.com>, "K Jones" <kj@lmn.com>',
1571 'Cc' => '',
1572 'Bcc' => '',
1573 'In-Reply-To' => undef,
1574 'Message-ID' => undef,
1575
1576 'From-Raw' => [ [ 'John B', undef, 'jb', 'abc.com' ] ],
1577 'Sender-Raw' => [ [ 'John B', undef, 'jb', 'abc.com' ] ],
1578 'Reply-To-Raw' => [ [ 'John B', undef, 'jb', 'abc.com' ] ],
1579 'To-Raw' => [
1580 [ 'Bob H', undef, 'bh', 'xyz.com' ],
1581 [ 'K Jones', undef, 'kj', 'lmn.com' ],
1582 ],
1583 'Cc-Raw' => [],
1584 'Bcc-Raw' => [],
1585 }
1586 }
1587 };
1588
1589 All the fields here are from straight from the email headers. See RFC
1590 822 for more details.
1591
1592 Annotation
1593 If the server supports RFC 5257 (ANNOTATE Extension), then you can
1594 fetch per-message annotations.
1595
1596 Annotation responses would normally be returned as a a nested set of
1597 arrays. However it's much easier to access the results as a nested set
1598 of hashes, so the results are so converted if the Annotation parse mode
1599 is enabled, which is on by default.
1600
1601 Part of an example from the RFC
1602
1603 S: * 12 FETCH (UID 1123 ANNOTATION
1604 (/comment (value.priv "My comment"
1605 size.priv "10")
1606 /altsubject (value.priv "Rhinoceroses!"
1607 size.priv "13")
1608
1609 So the fetch command:
1610
1611 my $Res = $IMAP->fetch(1123, 'annotation', [ '/*', [ 'value.priv', 'size.priv' ] ]);
1612
1613 Would have the result:
1614
1615 $Res = {
1616 '1123' => {
1617 'annotation' => {
1618 '/comment' => {
1619 'value.priv' => 'My comment',
1620 'size.priv => 10
1621 },
1622 '/altsubject' => {
1623 'value.priv' => '"Rhinoceroses',
1624 'size.priv => 13
1625 }
1626 }
1627 }
1628 }
1629
1631 _imap_cmd($Command, $IsUidCmd, $RespItems, @Args)
1632 Executes a standard IMAP command.
1633
1634 Method arguments
1635 $Command
1636 Text string of command to call IMAP server with (e.g. 'select',
1637 'search', etc).
1638
1639 $IsUidCmd
1640 1 if command involved message ids and can be prefixed with UID,
1641 0 otherwise.
1642
1643 $RespItems
1644 Responses to look for from command (eg 'list', 'fetch', etc).
1645 Commands which return results usually return them untagged. The
1646 following is an example of fetching flags from a number of
1647 messages.
1648
1649 C123 uid fetch 1:* (flags)
1650 * 1 FETCH (FLAGS (\Seen) UID 1)
1651 * 2 FETCH (FLAGS (\Seen) UID 2)
1652 C123 OK Completed
1653
1654 Between the sending of the command and the 'OK Completed'
1655 response, we have to pick up all the untagged 'FETCH' response
1656 items so we would pass 'fetch' (always use lower case) as the
1657 $RespItems to extract.
1658
1659 This can also be a hash ref of callback functions. See
1660 _parse_response for more examples
1661
1662 @Args
1663 Any extra arguments to pass to command.
1664
1665 _send_cmd($Self, $Cmd, @InArgs)
1666 Helper method used by the _imap_cmd method to actually build (and
1667 quote where necessary) the command arguments and then send the
1668 actual command.
1669
1670 _send_data($Self, $Opts, $Buffer, @Args)
1671 Helper method used by the _send_cmd method to actually build (and
1672 quote where necessary) the command arguments and then send the
1673 actual command.
1674
1675 _parse_response($Self, $RespItems, [ \%ParseMode ])
1676 Helper method called by _imap_cmd after sending the command. This
1677 methods retrieves data from the IMAP socket and parses it into Perl
1678 structures and returns the results.
1679
1680 $RespItems is either a string, which is the untagged response(s) to
1681 find and return, or for custom processing, it can be a hash ref.
1682
1683 If a hash ref, then each key will be an untagged response to look
1684 for, and each value a callback function to call for the
1685 corresponding untagged response.
1686
1687 Each callback will be called with 2 or 3 arguments; the untagged
1688 response string, the remainder of the line parsed into an array
1689 ref, and for fetch type responses, the id will be passed as the
1690 third argument.
1691
1692 One other piece of magic, if you pass a 'responseitem' key, then
1693 the value should be a string, and will be the untagged response
1694 returned from the function
1695
1696 _require_capability($Self, $Capability)
1697 Helper method which checks that the server has a certain
1698 capability. If not, it sets the internal last error, $@ and
1699 returns undef.
1700
1701 _trace($Self, $Line)
1702 Helper method which outputs any tracing data.
1703
1704 _is_current_folder($Self, $FolderName)
1705 Return true if a folder is currently selected and that folder is
1706 $FolderName
1707
1709 _next_atom($Self)
1710 Returns the next atom from the current line. Uses $Self->{ReadLine}
1711 for line data, or if undef, fills it with a new line of data from
1712 the IMAP connection socket and then begins processing.
1713
1714 If the next atom is:
1715
1716 · An unquoted string, simply returns the string.
1717
1718 · A quoted string, unquotes the string, changes any occurances of
1719 \" to " and returns the string.
1720
1721 · A literal (e.g. {NBytes}\r\n), reads the number of bytes of
1722 data in the literal into a scalar or file (depending on
1723 "literal_handle_control").
1724
1725 · A bracketed structure, reads all the sub-atoms within the
1726 structure and returns an array reference with all the sub-
1727 atoms.
1728
1729 In each case, after parsing the atom, it removes any trailing space
1730 separator, and then returns the remainder of the line to
1731 $Self->{ReadLine} ready for the next call to "_next_atom()".
1732
1733 _next_simple_atom($Self)
1734 Faster version of _next_atom() for known simple cases
1735
1736 _remaining_atoms($Self)
1737 Returns all the remaining atoms for the current line in the read
1738 line buffer as an array reference. Leaves $Self->{ReadLine} eq ''.
1739 See "_next_atom()"
1740
1741 _remaining_line($Self)
1742 Returns the remaining data in the read line buffer
1743 ($Self->{ReadLine}) as a scalar string/data value.
1744
1745 _fill_imap_read_buffer($Self)
1746 Wait until data is available on the IMAP connection socket (or a
1747 timeout occurs). Read the data into the internal buffer
1748 $Self->{ReadBuf}. You can then use "_imap_socket_read_line()",
1749 "_imap_socket_read_bytes()" or "_copy_imap_socket_to_handle()" to
1750 read data from the buffer in lines or bytes at a time.
1751
1752 _imap_socket_read_line($Self)
1753 Read a \r\n terminated list from the buffered IMAP connection
1754 socket.
1755
1756 _imap_socket_read_bytes($Self, $NBytes)
1757 Read a certain number of bytes from the buffered IMAP connection
1758 socket.
1759
1760 _imap_socket_out($Self, $Data)
1761 Write the data in $Data to the IMAP connection socket.
1762
1763 _copy_handle_to_imapsocket($Self, $InHandle)
1764 Copy a given number of bytes from a file handle to the IMAP
1765 connection
1766
1767 _copy_imap_socket_to_handle($Self, $OutHandle, $NBytes)
1768 Copies data from the IMAP socket to a file handle. This is
1769 different to _copy_handle_to_imap_socket() because we internally
1770 buffer the IMAP socket so we can't just use it to copy from the
1771 socket handle, we have to copy the contents of our buffer first.
1772
1773 The number of bytes specified must be available on the IMAP socket,
1774 if the function runs out of data it will 'die' with an error.
1775
1776 _quote($String)
1777 Returns an IMAP quoted version of a string. This place "..." around
1778 the string, and replaces any internal " with \".
1779
1781 _parse_list_to_hash($ListRef, $Recursive)
1782 Parses an array reference list of ($Key, $Value) pairs into a hash.
1783 Makes sure that all the keys are lower cased (lc) first.
1784
1785 _fix_folder_name($FolderName, %Opts)
1786 Changes a folder name based on the current root folder prefix as
1787 set with the "set_root_prefix()" call.
1788
1789 Wildcard => 1 = a folder name with % or * is left alone
1790 NoEncoding => 1 = don't do modified utf-7 encoding, leave as unicode
1791
1792 _fix_folder_encoding($FolderName)
1793 Encode folder name using IMAP-UTF-7
1794
1795 _unfix_folder_name($FolderName)
1796 Unchanges a folder name based on the current root folder prefix as
1797 set with the "set_root_prefix()" call.
1798
1799 _fix_message_ids($MessageIds)
1800 Used by IMAP commands to handle a number of different ways that
1801 message IDs can be specified.
1802
1803 Method arguments
1804 $MessageIds
1805 String or array ref which specified the message IDs or UIDs.
1806
1807 The $MessageIds parameter may take the following forms:
1808
1809 array ref
1810 Array is turned into a string of comma separated ID numbers.
1811
1812 1:* Normally a * would result in the message ID string being
1813 quoted. This ensure that such a range string is not quoted
1814 because some servers (e.g. cyrus) don't like.
1815
1816 _parse_email_address($EmailAddressList)
1817 Converts a list of IMAP email address structures as parsed and
1818 returned from an IMAP fetch (envelope) call into a single RFC 822
1819 email string (e.g. "Person 1 Name" <ename@ecorp.com>, "Person 2
1820 Name" <...>, etc) to finally return to the user.
1821
1822 This is used to parse an envelope structure returned from a fetch
1823 call.
1824
1825 See the documentation section 'FETCH RESULTS' for more information.
1826
1827 _parse_envelope($Envelope, $IncludeRaw, $DecodeUTF8)
1828 Converts an IMAP envelope structure as parsed and returned from an
1829 IMAP fetch (envelope) call into a convenient hash structure.
1830
1831 If $IncludeRaw is true, includes the XXX-Raw fields, otherwise
1832 these are left out.
1833
1834 If $DecodeUTF8 is true, then checks if the fields contain any
1835 quoted-printable chars, and decodes them to a Perl UTF8 string if
1836 they do.
1837
1838 See the documentation section 'FETCH RESULTS' from more
1839 information.
1840
1841 _parse_bodystructure($BodyStructure, $IncludeRaw, $DecodeUTF8,
1842 $PartNum)
1843 Parses a standard IMAP body structure and turns it into a Perl
1844 friendly nested hash structure. This routine is recursive and you
1845 should not pass a value for $PartNum when called for the top level
1846 bodystructure item. Note that this routine destroys the array
1847 reference structure passed in as $BodyStructure.
1848
1849 See the documentation section 'FETCH RESULTS' from more information
1850
1851 _parse_fetch_annotation($AnnotateItem)
1852 Takes the result from a single IMAP annotation item into a Perl
1853 friendly structure.
1854
1855 See the documentation section 'FETCH RESULTS' from more
1856 information.
1857
1858 _parse_fetch_result($FetchResult)
1859 Takes the result from a single IMAP fetch response line and parses
1860 it into a Perl friendly structure.
1861
1862 See the documentation section 'FETCH RESULTS' from more
1863 information.
1864
1865 _parse_header_result($HeaderResults, $Value, $FetchResult)
1866 Take a body[header.fields (xyz)] fetch response and parse out the
1867 header fields and values
1868
1869 _decode_utf8($Value)
1870 Decodes the passed quoted printable value to a Perl Unicode string.
1871
1872 _expand_sequence(@Sequences)
1873 Expand a list of IMAP id sequences into a full list of ids
1874
1876 DESTROY()
1877 Called by Perl when this object is destroyed. Logs out of the IMAP
1878 server if still connected.
1879
1881 Net::IMAP, Mail::IMAPClient, IMAP::Admin, RFC 3501
1882
1883 Latest news/details can also be found at:
1884
1885 http://cpan.robm.fastmail.fm/mailimaptalk/
1886
1887 Available on github at:
1888
1889 <https://github.com/robmueller/mail-imaptalk/>
1890
1892 Rob Mueller <cpan@robm.fastmail.fm>. Thanks to Jeremy Howard
1893 <j+daemonize@howard.fm> for socket code, support and documentation
1894 setup.
1895
1897 Copyright (C) 2003-2016 by FastMail Pty Ltd
1898
1899 This library is free software; you can redistribute it and/or modify it
1900 under the same terms as Perl itself.
1901
1902
1903
1904perl v5.28.0 2016-10-22 Mail::IMAPTalk(3)