1 ;;; imap.el --- imap library
2 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002
3 ;; Free Software Foundation, Inc.
5 ;; Author: Simon Josefsson <jas@pdc.kth.se>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
27 ;; imap.el is a elisp library providing an interface for talking to
30 ;; imap.el is roughly divided in two parts, one that parses IMAP
31 ;; responses from the server and storing data into buffer-local
32 ;; variables, and one for utility functions which send commands to
33 ;; server, waits for an answer, and return information. The latter
34 ;; part is layered on top of the previous.
36 ;; The imap.el API consist of the following functions, other functions
37 ;; in this file should not be called directly and the result of doing
38 ;; so are at best undefined.
42 ;; imap-open, imap-opened, imap-authenticate, imap-close,
43 ;; imap-capability, imap-namespace, imap-error-text
47 ;; imap-mailbox-get, imap-mailbox-map, imap-current-mailbox,
48 ;; imap-current-mailbox-p, imap-search, imap-mailbox-select,
49 ;; imap-mailbox-examine, imap-mailbox-unselect, imap-mailbox-expunge
50 ;; imap-mailbox-close, imap-mailbox-create, imap-mailbox-delete
51 ;; imap-mailbox-rename, imap-mailbox-lsub, imap-mailbox-list
52 ;; imap-mailbox-subscribe, imap-mailbox-unsubscribe, imap-mailbox-status
53 ;; imap-mailbox-acl-get, imap-mailbox-acl-set, imap-mailbox-acl-delete
57 ;; imap-fetch-asynch, imap-fetch,
58 ;; imap-current-message, imap-list-to-message-set,
59 ;; imap-message-get, imap-message-map
60 ;; imap-message-envelope-date, imap-message-envelope-subject,
61 ;; imap-message-envelope-from, imap-message-envelope-sender,
62 ;; imap-message-envelope-reply-to, imap-message-envelope-to,
63 ;; imap-message-envelope-cc, imap-message-envelope-bcc
64 ;; imap-message-envelope-in-reply-to, imap-message-envelope-message-id
65 ;; imap-message-body, imap-message-flag-permanent-p
66 ;; imap-message-flags-set, imap-message-flags-del
67 ;; imap-message-flags-add, imap-message-copyuid
68 ;; imap-message-copy, imap-message-appenduid
69 ;; imap-message-append, imap-envelope-from
72 ;; It is my hope that theese commands should be pretty self
73 ;; explanatory for someone that know IMAP. All functions have
74 ;; additional documentation on how to invoke them.
76 ;; imap.el support RFC1730/2060 (IMAP4/IMAP4rev1), implemented IMAP
77 ;; extensions are RFC2195 (CRAM-MD5), RFC2086 (ACL), RFC2342
78 ;; (NAMESPACE), RFC2359 (UIDPLUS), the IMAP-part of RFC2595 (STARTTLS,
79 ;; LOGINDISABLED) (with use of external library starttls.el and
80 ;; program starttls) and the GSSAPI / kerberos V4 sections of RFC1731
81 ;; (with use of external program `imtest'). It also take advantage
82 ;; the UNSELECT extension in Cyrus IMAPD.
84 ;; Without the work of John McClary Prevost and Jim Radford this library
85 ;; would not have seen the light of day. Many thanks.
87 ;; This is a transcript of short interactive session for demonstration
90 ;; (imap-open "my.mail.server")
91 ;; => " *imap* my.mail.server:0"
93 ;; The rest are invoked with current buffer as the buffer returned by
94 ;; `imap-open'. It is possible to do all without this, but it would
95 ;; look ugly here since `buffer' is always the last argument for all
96 ;; imap.el API functions.
98 ;; (imap-authenticate "myusername" "mypassword")
101 ;; (imap-mailbox-lsub "*")
102 ;; => ("INBOX.sentmail" "INBOX.private" "INBOX.draft" "INBOX.spam")
104 ;; (imap-mailbox-list "INBOX.n%")
105 ;; => ("INBOX.namedroppers" "INBOX.nnimap" "INBOX.ntbugtraq")
107 ;; (imap-mailbox-select "INBOX.nnimap")
110 ;; (imap-mailbox-get 'exists)
113 ;; (imap-mailbox-get 'uidvalidity)
116 ;; (imap-search "FLAGGED SINCE 18-DEC-98")
119 ;; (imap-fetch 235 "RFC822.PEEK" 'RFC822)
120 ;; => "X-Sieve: cmu-sieve 1.3^M\nX-Username: <jas@pdc.kth.se>^M\r...."
124 ;; o Parse UIDs as strings? We need to overcome the 28 bit limit somehow.
125 ;; o Don't use `read' at all (important places already fixed)
126 ;; o Accept list of articles instead of message set string in most
127 ;; imap-message-* functions.
131 ;; - 19991218 added starttls/digest-md5 patch,
132 ;; by Daiki Ueno <ueno@ueda.info.waseda.ac.jp>
133 ;; NB! you need SLIM for starttls.el and digest-md5.el
134 ;; - 19991023 commited to pgnus
139 (eval-when-compile (require 'cl))
140 (eval-when-compile (require 'static))
145 (autoload 'open-ssl-stream "ssl")
146 (autoload 'starttls-open-stream "starttls")
147 (autoload 'starttls-negotiate "starttls")
148 (autoload 'rfc2104-hash "rfc2104")
149 (autoload 'md5 "md5")
150 (autoload 'utf7-encode "utf7")
151 (autoload 'utf7-decode "utf7")
152 (autoload 'format-spec "format-spec")
153 (autoload 'format-spec-make "format-spec")
154 ;; Avoid use gnus-point-at-eol so we're independent of Gnus. These
155 ;; days we have point-at-eol anyhow.
156 (if (fboundp 'point-at-eol)
157 (defalias 'imap-point-at-eol 'point-at-eol)
158 (defun imap-point-at-eol ()
162 (autoload 'sasl-digest-md5-digest-response "sasl"))
167 "Low-level IMAP issues."
171 (defcustom imap-kerberos4-program '("imtest -m kerberos_v4 -u %l -p %p %s"
173 "List of strings containing commands for Kerberos 4 authentication.
174 %s is replaced with server hostname, %p with port to connect to, and
175 %l with the value of `imap-default-user'. The program should accept
176 IMAP commands on stdin and return responses to stdout. Each entry in
177 the list is tried until a successful connection is made."
179 :type '(repeat string))
181 (defcustom imap-gssapi-program '("imtest -m gssapi -u %l -p %p %s")
182 "List of strings containing commands for GSSAPI (krb5) authentication.
183 %s is replaced with server hostname, %p with port to connect to, and
184 %l with the value of `imap-default-user'. The program should accept
185 IMAP commands on stdin and return responses to stdout. Each entry in
186 the list is tried until a successful connection is made."
188 :type '(repeat string))
190 (defcustom imap-ssl-program '("openssl s_client -quiet -ssl3 -connect %s:%p"
191 "openssl s_client -quiet -ssl2 -connect %s:%p"
192 "s_client -quiet -ssl3 -connect %s:%p"
193 "s_client -quiet -ssl2 -connect %s:%p")
194 "A string, or list of strings, containing commands for SSL connections.
195 Within a string, %s is replaced with the server address and %p with
196 port number on server. The program should accept IMAP commands on
197 stdin and return responses to stdout. Each entry in the list is tried
198 until a successful connection is made."
200 :type '(choice string
203 (defcustom imap-shell-program '("ssh %s imapd"
205 "ssh %g ssh %s imapd"
206 "rsh %g rsh %s imapd")
207 "A list of strings, containing commands for IMAP connection.
208 Within a string, %s is replaced with the server address, %p with port
209 number on server, %g with `imap-shell-host', and %l with
210 `imap-default-user'. The program should read IMAP commands from stdin
211 and write IMAP response to stdout. Each entry in the list is tried
212 until a successful connection is made."
214 :type '(repeat string))
216 (defcustom imap-process-connection-type nil
217 "*Value for `process-connection-type' to use for Kerberos4 and GSSAPI."
221 (defcustom imap-use-utf7 t
222 "If non-nil, do utf7 encoding/decoding of mailbox names.
223 Since the UTF7 decoding currently only decodes into ISO-8859-1
224 characters, you may disable this decoding if you need to access UTF7
225 encoded mailboxes which doesn't translate into ISO-8859-1."
229 (defcustom imap-log nil
230 "If non-nil, a imap session trace is placed in *imap-log* buffer."
234 (defcustom imap-debug nil
235 "If non-nil, random debug spews are placed in *imap-debug* buffer."
239 (defcustom imap-shell-host "gateway"
240 "Hostname of rlogin proxy."
244 (defcustom imap-default-user (user-login-name)
245 "Default username to use."
249 ;; Various variables.
251 (defvar imap-fetch-data-hook nil
252 "Hooks called after receiving each FETCH response.")
254 (defvar imap-streams '(gssapi kerberos4 starttls ssl network shell)
255 "Priority of streams to consider when opening connection to server.")
257 (defvar imap-stream-alist
258 '((gssapi imap-gssapi-stream-p imap-gssapi-open)
259 (kerberos4 imap-kerberos4-stream-p imap-kerberos4-open)
260 (ssl imap-ssl-p imap-ssl-open)
261 (network imap-network-p imap-network-open)
262 (shell imap-shell-p imap-shell-open)
263 (starttls imap-starttls-p imap-starttls-open))
264 "Definition of network streams.
268 NAME names the stream, CHECK is a function returning non-nil if the
269 server support the stream and OPEN is a function for opening the
272 (defvar imap-authenticators '(gssapi
278 "Priority of authenticators to consider when authenticating to server.")
280 (defvar imap-authenticator-alist
281 '((gssapi imap-gssapi-auth-p imap-gssapi-auth)
282 (kerberos4 imap-kerberos4-auth-p imap-kerberos4-auth)
283 (cram-md5 imap-cram-md5-p imap-cram-md5-auth)
284 (login imap-login-p imap-login-auth)
285 (anonymous imap-anonymous-p imap-anonymous-auth)
286 (digest-md5 imap-digest-md5-p imap-digest-md5-auth))
287 "Definition of authenticators.
289 \(NAME CHECK AUTHENTICATE)
291 NAME names the authenticator. CHECK is a function returning non-nil if
292 the server support the authenticator and AUTHENTICATE is a function
293 for doing the actual authentication.")
295 (defvar imap-error nil
296 "Error codes from the last command.")
298 ;; Internal constants. Change theese and die.
300 (defconst imap-default-port 143)
301 (defconst imap-default-ssl-port 993)
302 (defconst imap-default-stream 'network)
303 (defconst imap-local-variables '(imap-server
312 imap-current-target-mailbox
321 imap-calculate-literal-size-first
323 (defconst imap-log-buffer "*imap-log*")
324 (defconst imap-debug-buffer "*imap-debug*")
326 ;; Internal variables.
328 (defvar imap-stream nil)
329 (defvar imap-auth nil)
330 (defvar imap-server nil)
331 (defvar imap-port nil)
332 (defvar imap-username nil)
333 (defvar imap-password nil)
334 (defvar imap-calculate-literal-size-first nil)
335 (defvar imap-state 'closed
337 Valid states are `closed', `initial', `nonauth', `auth', `selected'
340 (defvar imap-server-eol "\r\n"
341 "The EOL string sent from the server.")
343 (defvar imap-client-eol "\r\n"
344 "The EOL string we send to the server.")
346 (defvar imap-current-mailbox nil
347 "Current mailbox name.")
349 (defvar imap-current-target-mailbox nil
350 "Current target mailbox for COPY and APPEND commands.")
352 (defvar imap-mailbox-data nil
353 "Obarray with mailbox data.")
355 (defvar imap-mailbox-prime 997
356 "Length of imap-mailbox-data.")
358 (defvar imap-current-message nil
359 "Current message number.")
361 (defvar imap-message-data nil
362 "Obarray with message data.")
364 (defvar imap-message-prime 997
365 "Length of imap-message-data.")
367 (defvar imap-capability nil
368 "Capability for server.")
370 (defvar imap-namespace nil
371 "Namespace for current server.")
373 (defvar imap-reached-tag 0
374 "Lower limit on command tags that have been parsed.")
376 (defvar imap-failed-tags nil
377 "Alist of tags that failed.
378 Each element is a list with four elements; tag (a integer), response
379 state (a symbol, `OK', `NO' or `BAD'), response code (a string), and
380 human readable response text (a string).")
383 "Command tag number.")
385 (defvar imap-process nil
388 (defvar imap-continuation nil
389 "Non-nil indicates that the server emitted a continuation request.
390 The actually value is really the text on the continuation line.")
392 (defvar imap-callbacks nil
393 "List of response tags and callbacks, on the form `(number . function)'.
394 The function should take two arguments, the first the IMAP tag and the
395 second the status (OK, NO, BAD etc) of the command.")
398 ;; Utility functions:
400 (defun imap-remassoc (key alist)
401 "Delete by side effect any elements of LIST whose car is `equal' to KEY.
402 The modified LIST is returned. If the first member
403 of LIST has a car that is `equal' to KEY, there is no way to remove it
404 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
405 sure of changing the value of `foo'."
407 (if (equal key (caar alist))
409 (setcdr alist (imap-remassoc key (cdr alist)))
412 (defun imap-read-passwd (prompt &rest args)
413 "Read a password using PROMPT.
414 If ARGS, PROMPT is used as an argument to `format'."
415 (let ((prompt (if args
416 (apply 'format prompt args)
418 (funcall (if (or (fboundp 'read-passwd)
420 (fboundp 'read-passwd))
421 (and (load "passwd" t)
422 (fboundp 'read-passwd)))
424 (autoload 'ange-ftp-read-passwd "ange-ftp")
425 'ange-ftp-read-passwd)
428 (defsubst imap-utf7-encode (string)
432 (utf7-encode string t)
434 "imap: Could not UTF7 encode `%s', using it unencoded..."
439 (defsubst imap-utf7-decode (string)
443 (utf7-decode string t)
445 "imap: Could not UTF7 decode `%s', using it undecoded..."
450 (defsubst imap-ok-p (status)
453 (setq imap-error status)
456 (defun imap-error-text (&optional buffer)
457 (with-current-buffer (or buffer (current-buffer))
458 (nth 3 (car imap-failed-tags))))
461 ;; Server functions; stream stuff:
463 (defun imap-kerberos4-stream-p (buffer)
464 (imap-capability 'AUTH=KERBEROS_V4 buffer))
466 (defun imap-kerberos4-open (name buffer server port)
467 (let ((cmds imap-kerberos4-program)
469 (while (and (not done) (setq cmd (pop cmds)))
470 (message "Opening Kerberos 4 IMAP connection with `%s'..." cmd)
472 (let* ((port (or port imap-default-port))
473 (process-connection-type imap-process-connection-type)
474 (process (as-binary-process
476 name buffer shell-file-name shell-command-switch
481 ?p (number-to-string port)
482 ?l imap-default-user)))))
485 (with-current-buffer buffer
486 (setq imap-client-eol "\n"
487 imap-calculate-literal-size-first t)
488 (while (and (memq (process-status process) '(open run))
489 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
490 (goto-char (point-min))
491 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
492 (or (while (looking-at "^C:")
495 ;; cyrus 1.6 imtest print "S: " before server greeting
496 (or (not (looking-at "S: "))
499 (not (and (imap-parse-greeting)
500 ;; success in imtest < 1.6:
501 (or (re-search-forward
502 "^__\\(.*\\)__\n" nil t)
503 ;; success in imtest 1.6:
505 "^\\(Authenticat.*\\)" nil t))
506 (setq response (match-string 1)))))
507 (accept-process-output process 1)
510 (with-current-buffer (get-buffer-create imap-log-buffer)
511 (buffer-disable-undo)
512 (goto-char (point-max))
513 (insert-buffer-substring buffer)))
515 (message "Opening Kerberos 4 IMAP connection with `%s'...%s" cmd
516 (if response (concat "done, " response) "failed"))
517 (if (and response (let ((case-fold-search nil))
518 (not (string-match "failed" response))))
520 (if (memq (process-status process) '(open run))
521 (imap-send-command "LOGOUT"))
522 (delete-process process)
526 (defun imap-gssapi-stream-p (buffer)
527 (imap-capability 'AUTH=GSSAPI buffer))
529 (defun imap-gssapi-open (name buffer server port)
530 (let ((cmds imap-gssapi-program)
532 (while (and (not done) (setq cmd (pop cmds)))
533 (message "Opening GSSAPI IMAP connection with `%s'..." cmd)
534 (let* ((port (or port imap-default-port))
535 (process-connection-type imap-process-connection-type)
536 (process (as-binary-process
538 name buffer shell-file-name shell-command-switch
543 ?p (number-to-string port)
544 ?l imap-default-user)))))
547 (with-current-buffer buffer
548 (setq imap-client-eol "\n"
549 imap-calculate-literal-size-first t)
550 (while (and (memq (process-status process) '(open run))
551 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
552 (goto-char (point-min))
553 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
554 (or (while (looking-at "^C:")
557 ;; cyrus 1.6 imtest print "S: " before server greeting
558 (or (not (looking-at "S: "))
561 (not (and (imap-parse-greeting)
562 ;; success in imtest 1.6:
564 "^\\(Authenticat.*\\)" nil t)
565 (setq response (match-string 1)))))
566 (accept-process-output process 1)
569 (with-current-buffer (get-buffer-create imap-log-buffer)
570 (buffer-disable-undo)
571 (goto-char (point-max))
572 (insert-buffer-substring buffer)))
574 (message "GSSAPI IMAP connection: %s" (or response "failed"))
575 (if (and response (let ((case-fold-search nil))
576 (not (string-match "failed" response))))
578 (if (memq (process-status process) '(open run))
579 (imap-send-command "LOGOUT"))
580 (delete-process process)
584 (defun imap-ssl-p (buffer)
587 (defun imap-ssl-open (name buffer server port)
588 "Open a SSL connection to server."
589 (let ((cmds (if (listp imap-ssl-program) imap-ssl-program
590 (list imap-ssl-program)))
595 (while (and (not done) (setq cmd (pop cmds)))
596 (message "imap: Opening SSL connection with `%s'..." cmd)
597 (let* ((port (or port imap-default-ssl-port))
598 (ssl-program-name shell-file-name)
599 (ssl-program-arguments
600 (list shell-command-switch
601 (format-spec cmd (format-spec-make
603 ?p (number-to-string port)))))
607 (cond ((eq system-type 'windows-nt)
608 (let (selective-display
609 (coding-system-for-write 'binary)
610 (coding-system-for-read 'raw-text-dos))
611 (open-ssl-stream name buffer server port)))
614 (open-ssl-stream name buffer server port))))
616 (with-current-buffer buffer
617 (goto-char (point-min))
618 (while (and (memq (process-status process) '(open run))
619 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
620 (goto-char (point-max))
622 (not (imap-parse-greeting)))
623 (accept-process-output process 1)
626 (with-current-buffer (get-buffer-create imap-log-buffer)
627 (buffer-disable-undo)
628 (goto-char (point-max))
629 (insert-buffer-substring buffer)))
631 (when (memq (process-status process) '(open run))
632 (setq done process))))))
635 (message "imap: Opening SSL connection with `%s'...done" cmd)
637 (message "imap: Opening SSL connection with `%s'...failed" cmd)
640 (defun imap-network-p (buffer)
643 (defun imap-network-open (name buffer server port)
644 (let* ((port (or port imap-default-port))
645 (process (open-network-stream-as-binary name buffer server port)))
647 (while (and (memq (process-status process) '(open run))
648 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
649 (goto-char (point-min))
650 (not (imap-parse-greeting)))
651 (accept-process-output process 1)
654 (with-current-buffer (get-buffer-create imap-log-buffer)
655 (buffer-disable-undo)
656 (goto-char (point-max))
657 (insert-buffer-substring buffer)))
658 (when (memq (process-status process) '(open run))
661 (defun imap-shell-p (buffer)
664 (defun imap-shell-open (name buffer server port)
665 (let ((cmds imap-shell-program)
667 (while (and (not done) (setq cmd (pop cmds)))
668 (message "imap: Opening IMAP connection with `%s'..." cmd)
669 (setq imap-client-eol "\n")
670 (let* ((port (or port imap-default-port))
671 (process (as-binary-process
673 name buffer shell-file-name shell-command-switch
679 ?p (number-to-string port)
680 ?l imap-default-user))))))
682 (while (and (memq (process-status process) '(open run))
683 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
684 (goto-char (point-min))
685 (not (imap-parse-greeting)))
686 (accept-process-output process 1)
689 (with-current-buffer (get-buffer-create imap-log-buffer)
690 (buffer-disable-undo)
691 (goto-char (point-max))
692 (insert-buffer-substring buffer)))
694 (when (memq (process-status process) '(open run))
695 (setq done process)))))
698 (message "imap: Opening IMAP connection with `%s'...done" cmd)
700 (message "imap: Opening IMAP connection with `%s'...failed" cmd)
703 (defun imap-starttls-p (buffer)
704 (imap-capability 'STARTTLS buffer))
706 (defun imap-starttls-open (name buffer server port)
707 (let* ((port (or port imap-default-port))
708 (process (as-binary-process
709 (starttls-open-stream name buffer server port)))
711 (message "imap: Connecting with STARTTLS...")
713 (while (and (memq (process-status process) '(open run))
714 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
715 (goto-char (point-min))
716 (not (imap-parse-greeting)))
717 (accept-process-output process 1)
720 (with-current-buffer (get-buffer-create imap-log-buffer)
721 (buffer-disable-undo)
722 (goto-char (point-max))
723 (insert-buffer-substring buffer)))
724 (let ((imap-process process))
727 (set-process-filter imap-process 'imap-arrival-filter)
728 (when (and (eq imap-stream 'starttls)
729 (imap-ok-p (imap-send-command-wait "STARTTLS")))
730 (starttls-negotiate imap-process)))
731 (set-process-filter imap-process nil)))
732 (when (memq (process-status process) '(open run))
733 (setq done process)))
736 (message "imap: Connecting with STARTTLS...done")
738 (message "imap: Connecting with STARTTLS...failed")
741 ;; Server functions; authenticator stuff:
743 (defun imap-interactive-login (buffer loginfunc)
744 "Login to server in BUFFER.
745 LOGINFUNC is passed a username and a password, it should return t if
746 it where sucessful authenticating itself to the server, nil otherwise.
747 Returns t if login was successful, nil otherwise."
748 (with-current-buffer buffer
749 (make-local-variable 'imap-username)
750 (make-local-variable 'imap-password)
751 (let (user passwd ret)
752 ;; (condition-case ()
753 (while (or (not user) (not passwd))
754 (setq user (or imap-username
755 (read-from-minibuffer
756 (concat "IMAP username for " imap-server
757 " (using stream `" (symbol-name imap-stream)
759 (or user imap-default-user))))
760 (setq passwd (or imap-password
762 (concat "IMAP password for " user "@"
763 imap-server " (using authenticator `"
764 (symbol-name imap-auth) "'): "))))
765 (when (and user passwd)
766 (if (funcall loginfunc user passwd)
770 (if (and (not imap-password)
771 (y-or-n-p "Store password for this session? "))
772 (setq imap-password passwd)))
773 (message "Login failed...")
776 ;; (quit (with-current-buffer buffer
779 ;; (error (with-current-buffer buffer
784 (defun imap-gssapi-auth-p (buffer)
785 (and (imap-capability 'AUTH=GSSAPI buffer)
786 (eq imap-stream 'gssapi)))
788 (defun imap-gssapi-auth (buffer)
789 (message "imap: Authenticating using GSSAPI...%s"
790 (if (eq imap-stream 'gssapi) "done" "failed"))
791 (eq imap-stream 'gssapi))
793 (defun imap-kerberos4-auth-p (buffer)
794 (and (imap-capability 'AUTH=KERBEROS_V4 buffer)
795 (eq imap-stream 'kerberos4)))
797 (defun imap-kerberos4-auth (buffer)
798 (message "imap: Authenticating using Kerberos 4...%s"
799 (if (eq imap-stream 'kerberos4) "done" "failed"))
800 (eq imap-stream 'kerberos4))
802 (defun imap-cram-md5-p (buffer)
803 (imap-capability 'AUTH=CRAM-MD5 buffer))
805 (defun imap-cram-md5-auth (buffer)
806 "Login to server using the AUTH CRAM-MD5 method."
807 (message "imap: Authenticating using CRAM-MD5...")
808 (let ((done (imap-interactive-login
810 (lambda (user passwd)
812 (imap-send-command-wait
814 "AUTHENTICATE CRAM-MD5"
816 (let* ((decoded (base64-decode-string challenge))
818 (if (and (featurep 'xemacs)
819 (>= (function-max-args 'md5) 4))
820 (lambda (object &optional start end)
821 (md5 object start end 'binary))
823 (hash (rfc2104-hash hash-function 64 16
825 (response (concat user " " hash))
826 (encoded (base64-encode-string response)))
829 (message "imap: Authenticating using CRAM-MD5...done")
830 (message "imap: Authenticating using CRAM-MD5...failed"))))
832 (defun imap-login-p (buffer)
833 (and (not (imap-capability 'LOGINDISABLED buffer))
834 (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
836 (defun imap-login-auth (buffer)
837 "Login to server using the LOGIN command."
838 (message "imap: Plaintext authentication...")
839 (imap-interactive-login buffer
840 (lambda (user passwd)
841 (imap-ok-p (imap-send-command-wait
842 (concat "LOGIN \"" user "\" \""
845 (defun imap-anonymous-p (buffer)
848 (defun imap-anonymous-auth (buffer)
849 (message "imap: Logging in anonymously...")
850 (with-current-buffer buffer
851 (imap-ok-p (imap-send-command-wait
852 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
853 (system-name)) "\"")))))
855 (defun imap-digest-md5-p (buffer)
856 (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
858 (require 'digest-md5)
861 (defun imap-digest-md5-auth (buffer)
862 "Login to server using the AUTH DIGEST-MD5 method."
863 (message "imap: Authenticating using DIGEST-MD5...")
864 (imap-interactive-login
866 (lambda (user passwd)
870 "AUTHENTICATE DIGEST-MD5"
872 (base64-encode-string
873 (sasl-digest-md5-digest-response
874 (base64-decode-string challenge)
875 user passwd "imap" imap-server)
877 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
879 (setq imap-continuation nil)
880 (imap-send-command-1 "")
881 (imap-ok-p (imap-wait-for-tag tag)))))))
885 (defun imap-open-1 (buffer)
886 (with-current-buffer buffer
888 (setq imap-current-mailbox nil
889 imap-current-message nil
891 imap-process (condition-case ()
892 (funcall (nth 2 (assq imap-stream
894 "imap" buffer imap-server imap-port)
897 (set-process-filter imap-process 'imap-arrival-filter)
898 (set-process-sentinel imap-process 'imap-sentinel)
899 (while (and (eq imap-state 'initial)
900 (memq (process-status imap-process) '(open run)))
901 (message "Waiting for response from %s..." imap-server)
902 (accept-process-output imap-process 1))
903 (message "Waiting for response from %s...done" imap-server)
904 (and (memq (process-status imap-process) '(open run))
907 (defun imap-open (server &optional port stream auth buffer)
908 "Open a IMAP connection to host SERVER at PORT returning a buffer.
909 If PORT is unspecified, a default value is used (143 except
910 for SSL which use 993).
911 STREAM indicates the stream to use, see `imap-streams' for available
912 streams. If nil, it choices the best stream the server is capable of.
913 AUTH indicates authenticator to use, see `imap-authenticators' for
914 available authenticators. If nil, it choices the best stream the
915 server is capable of.
916 BUFFER can be a buffer or a name of a buffer, which is created if
917 necessery. If nil, the buffer name is generated."
918 (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
919 (with-current-buffer (get-buffer-create buffer)
920 (if (imap-opened buffer)
922 (mapcar 'make-local-variable imap-local-variables)
923 (set-buffer-multibyte nil)
924 (buffer-disable-undo)
925 (setq imap-server (or server imap-server))
926 (setq imap-port (or port imap-port))
927 (setq imap-auth (or auth imap-auth))
928 (setq imap-stream (or stream imap-stream))
929 (message "imap: Connecting to %s..." imap-server)
930 (if (null (let ((imap-stream (or imap-stream imap-default-stream)))
931 (imap-open-1 buffer)))
933 (message "imap: Connecting to %s...failed" imap-server)
935 (when (null imap-stream)
936 ;; Need to choose stream.
937 (let ((streams imap-streams))
938 (while (setq stream (pop streams))
939 ;; OK to use this stream?
940 (when (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
942 (if (not (eq imap-default-stream stream))
943 (with-current-buffer (get-buffer-create
944 (generate-new-buffer-name " *temp*"))
945 (mapcar 'make-local-variable imap-local-variables)
946 (set-buffer-multibyte nil)
947 (buffer-disable-undo)
948 (setq imap-server (or server imap-server))
949 (setq imap-port (or port imap-port))
950 (setq imap-auth (or auth imap-auth))
951 (message "imap: Reconnecting with stream `%s'..." stream)
952 (if (null (let ((imap-stream stream))
953 (imap-open-1 (current-buffer))))
955 (kill-buffer (current-buffer))
957 "imap: Reconnecting with stream `%s'...failed"
959 ;; We're done, kill the first connection
962 (rename-buffer buffer)
963 (message "imap: Reconnecting with stream `%s'...done"
965 (setq imap-stream stream)
966 (setq imap-capability nil)
969 (message "imap: Connecting to %s...done" imap-server)
970 (setq imap-stream stream)
971 (setq imap-capability nil)
972 (setq streams nil))))))
973 (when (imap-opened buffer)
974 (setq imap-mailbox-data (make-vector imap-mailbox-prime 0)))
978 (defun imap-opened (&optional buffer)
979 "Return non-nil if connection to imap server in BUFFER is open.
980 If BUFFER is nil then the current buffer is used."
981 (and (setq buffer (get-buffer (or buffer (current-buffer))))
982 (buffer-live-p buffer)
983 (with-current-buffer buffer
985 (memq (process-status imap-process) '(open run))))))
987 (defun imap-authenticate (&optional user passwd buffer)
988 "Authenticate to server in BUFFER, using current buffer if nil.
989 It uses the authenticator specified when opening the server. If the
990 authenticator requires username/passwords, they are queried from the
991 user and optionally stored in the buffer. If USER and/or PASSWD is
992 specified, the user will not be questioned and the username and/or
993 password is remembered in the buffer."
994 (with-current-buffer (or buffer (current-buffer))
995 (if (not (eq imap-state 'nonauth))
996 (or (eq imap-state 'auth)
997 (eq imap-state 'select)
998 (eq imap-state 'examine))
999 (make-local-variable 'imap-username)
1000 (make-local-variable 'imap-password)
1001 (if user (setq imap-username user))
1002 (if passwd (setq imap-password passwd))
1004 (and (funcall (nth 2 (assq imap-auth
1005 imap-authenticator-alist)) buffer)
1006 (setq imap-state 'auth))
1007 ;; Choose authenticator.
1008 (let ((auths imap-authenticators)
1010 (while (setq auth (pop auths))
1011 ;; OK to use authenticator?
1012 (when (funcall (nth 1 (assq auth imap-authenticator-alist)) buffer)
1013 (message "imap: Authenticating to `%s' using `%s'..."
1015 (setq imap-auth auth)
1016 (if (funcall (nth 2 (assq auth imap-authenticator-alist)) buffer)
1018 (message "imap: Authenticating to `%s' using `%s'...done"
1021 (message "imap: Authenticating to `%s' using `%s'...failed"
1022 imap-server auth)))))
1025 (defun imap-close (&optional buffer)
1026 "Close connection to server in BUFFER.
1027 If BUFFER is nil, the current buffer is used."
1028 (with-current-buffer (or buffer (current-buffer))
1031 (imap-send-command-wait "LOGOUT")
1033 (when (and imap-process
1034 (memq (process-status imap-process) '(open run)))
1035 (delete-process imap-process))
1036 (setq imap-current-mailbox nil
1037 imap-current-message nil
1042 (defun imap-capability (&optional identifier buffer)
1043 "Return a list of identifiers which server in BUFFER support.
1044 If IDENTIFIER, return non-nil if it's among the servers capabilities.
1045 If BUFFER is nil, the current buffer is assumed."
1046 (with-current-buffer (or buffer (current-buffer))
1047 (unless imap-capability
1048 (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
1049 (setq imap-capability '(IMAP2))))
1051 (memq (intern (upcase (symbol-name identifier))) imap-capability)
1054 (defun imap-namespace (&optional buffer)
1055 "Return a namespace hierarchy at server in BUFFER.
1056 If BUFFER is nil, the current buffer is assumed."
1057 (with-current-buffer (or buffer (current-buffer))
1058 (unless imap-namespace
1059 (when (imap-capability 'NAMESPACE)
1060 (imap-send-command-wait "NAMESPACE")))
1063 (defun imap-send-command-wait (command &optional buffer)
1064 (imap-wait-for-tag (imap-send-command command buffer) buffer))
1067 ;; Mailbox functions:
1069 (defun imap-mailbox-put (propname value &optional mailbox buffer)
1070 (with-current-buffer (or buffer (current-buffer))
1071 (if imap-mailbox-data
1072 (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
1074 (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
1075 propname value mailbox (current-buffer)))
1078 (defsubst imap-mailbox-get-1 (propname &optional mailbox)
1079 (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
1082 (defun imap-mailbox-get (propname &optional mailbox buffer)
1083 (let ((mailbox (imap-utf7-encode mailbox)))
1084 (with-current-buffer (or buffer (current-buffer))
1085 (imap-mailbox-get-1 propname (or mailbox imap-current-mailbox)))))
1087 (defun imap-mailbox-map-1 (func &optional mailbox-decoder buffer)
1088 (with-current-buffer (or buffer (current-buffer))
1092 (push (funcall func (if mailbox-decoder
1093 (funcall mailbox-decoder (symbol-name s))
1094 (symbol-name s))) result))
1098 (defun imap-mailbox-map (func &optional buffer)
1099 "Map a function across each mailbox in `imap-mailbox-data', returning a list.
1100 Function should take a mailbox name (a string) as
1102 (imap-mailbox-map-1 func 'imap-utf7-decode buffer))
1104 (defun imap-current-mailbox (&optional buffer)
1105 (with-current-buffer (or buffer (current-buffer))
1106 (imap-utf7-decode imap-current-mailbox)))
1108 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
1109 (and (string= mailbox imap-current-mailbox)
1111 (eq imap-state 'examine))
1113 (eq imap-state 'selected)))))
1115 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
1116 (with-current-buffer (or buffer (current-buffer))
1117 (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
1119 (defun imap-mailbox-select-1 (mailbox &optional examine)
1120 "Select MAILBOX on server in BUFFER.
1121 If EXAMINE is non-nil, do a read-only select."
1122 (if (imap-current-mailbox-p-1 mailbox examine)
1123 imap-current-mailbox
1124 (setq imap-current-mailbox mailbox)
1125 (if (imap-ok-p (imap-send-command-wait
1126 (concat (if examine "EXAMINE" "SELECT") " \""
1129 (setq imap-message-data (make-vector imap-message-prime 0)
1130 imap-state (if examine 'examine 'selected))
1131 imap-current-mailbox)
1132 ;; Failed SELECT/EXAMINE unselects current mailbox
1133 (setq imap-current-mailbox nil))))
1135 (defun imap-mailbox-select (mailbox &optional examine buffer)
1136 (with-current-buffer (or buffer (current-buffer))
1138 (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
1140 (defun imap-mailbox-examine-1 (mailbox &optional buffer)
1141 (with-current-buffer (or buffer (current-buffer))
1142 (imap-mailbox-select-1 mailbox 'examine)))
1144 (defun imap-mailbox-examine (mailbox &optional buffer)
1145 "Examine MAILBOX on server in BUFFER."
1146 (imap-mailbox-select mailbox 'examine buffer))
1148 (defun imap-mailbox-unselect (&optional buffer)
1149 "Close current folder in BUFFER, without expunging articles."
1150 (with-current-buffer (or buffer (current-buffer))
1151 (when (or (eq imap-state 'auth)
1152 (and (imap-capability 'UNSELECT)
1153 (imap-ok-p (imap-send-command-wait "UNSELECT")))
1155 (imap-send-command-wait (concat "EXAMINE \""
1156 imap-current-mailbox
1158 (imap-ok-p (imap-send-command-wait "CLOSE"))))
1159 (setq imap-current-mailbox nil
1160 imap-message-data nil
1164 (defun imap-mailbox-expunge (&optional asynch buffer)
1165 "Expunge articles in current folder in BUFFER.
1166 If ASYNCH, do not wait for succesful completion of the command.
1167 If BUFFER is nil the current buffer is assumed."
1168 (with-current-buffer (or buffer (current-buffer))
1169 (when (and imap-current-mailbox (not (eq imap-state 'examine)))
1171 (imap-send-command "EXPUNGE")
1172 (imap-ok-p (imap-send-command-wait "EXPUNGE"))))))
1174 (defun imap-mailbox-close (&optional asynch buffer)
1175 "Expunge articles and close current folder in BUFFER.
1176 If ASYNCH, do not wait for succesful completion of the command.
1177 If BUFFER is nil the current buffer is assumed."
1178 (with-current-buffer (or buffer (current-buffer))
1179 (when imap-current-mailbox
1181 (imap-add-callback (imap-send-command "CLOSE")
1182 `(lambda (tag status)
1183 (message "IMAP mailbox `%s' closed... %s"
1184 imap-current-mailbox status)
1185 (when (eq ,imap-current-mailbox
1186 imap-current-mailbox)
1187 ;; Don't wipe out data if another mailbox
1189 (setq imap-current-mailbox nil
1190 imap-message-data nil
1191 imap-state 'auth))))
1192 (when (imap-ok-p (imap-send-command-wait "CLOSE"))
1193 (setq imap-current-mailbox nil
1194 imap-message-data nil
1198 (defun imap-mailbox-create-1 (mailbox)
1199 (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
1201 (defun imap-mailbox-create (mailbox &optional buffer)
1202 "Create MAILBOX on server in BUFFER.
1203 If BUFFER is nil the current buffer is assumed."
1204 (with-current-buffer (or buffer (current-buffer))
1205 (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
1207 (defun imap-mailbox-delete (mailbox &optional buffer)
1208 "Delete MAILBOX on server in BUFFER.
1209 If BUFFER is nil the current buffer is assumed."
1210 (let ((mailbox (imap-utf7-encode mailbox)))
1211 (with-current-buffer (or buffer (current-buffer))
1213 (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1215 (defun imap-mailbox-rename (oldname newname &optional buffer)
1216 "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1217 If BUFFER is nil the current buffer is assumed."
1218 (let ((oldname (imap-utf7-encode oldname))
1219 (newname (imap-utf7-encode newname)))
1220 (with-current-buffer (or buffer (current-buffer))
1222 (imap-send-command-wait (list "RENAME \"" oldname "\" "
1223 "\"" newname "\""))))))
1225 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1226 "Return a list of subscribed mailboxes on server in BUFFER.
1227 If ROOT is non-nil, only list matching mailboxes. If ADD-DELIMITER is
1228 non-nil, a hierarchy delimiter is added to root. REFERENCE is a
1229 implementation-specific string that has to be passed to lsub command."
1230 (with-current-buffer (or buffer (current-buffer))
1231 ;; Make sure we know the hierarchy separator for root's hierarchy
1232 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1233 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1234 (imap-utf7-encode root) "\"")))
1235 ;; clear list data (NB not delimiter and other stuff)
1236 (imap-mailbox-map-1 (lambda (mailbox)
1237 (imap-mailbox-put 'lsub nil mailbox)))
1239 (imap-send-command-wait
1240 (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1241 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1244 (imap-mailbox-map-1 (lambda (mailbox)
1245 (when (imap-mailbox-get-1 'lsub mailbox)
1246 (push (imap-utf7-decode mailbox) out))))
1249 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1250 "Return a list of mailboxes matching ROOT on server in BUFFER.
1251 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1252 root. REFERENCE is a implementation-specific string that has to be
1253 passed to list command."
1254 (with-current-buffer (or buffer (current-buffer))
1255 ;; Make sure we know the hierarchy separator for root's hierarchy
1256 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1257 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1258 (imap-utf7-encode root) "\"")))
1259 ;; clear list data (NB not delimiter and other stuff)
1260 (imap-mailbox-map-1 (lambda (mailbox)
1261 (imap-mailbox-put 'list nil mailbox)))
1263 (imap-send-command-wait
1264 (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1265 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1268 (imap-mailbox-map-1 (lambda (mailbox)
1269 (when (imap-mailbox-get-1 'list mailbox)
1270 (push (imap-utf7-decode mailbox) out))))
1273 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1274 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1275 Returns non-nil if successful."
1276 (with-current-buffer (or buffer (current-buffer))
1277 (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1278 (imap-utf7-encode mailbox)
1281 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1282 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1283 Returns non-nil if successful."
1284 (with-current-buffer (or buffer (current-buffer))
1285 (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1286 (imap-utf7-encode mailbox)
1289 (defun imap-mailbox-status (mailbox items &optional buffer)
1290 "Get status items ITEM in MAILBOX from server in BUFFER.
1291 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1292 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1293 or 'unseen. If ITEMS is a list of symbols, a list of values is
1294 returned, if ITEMS is a symbol only it's value is returned."
1295 (with-current-buffer (or buffer (current-buffer))
1297 (imap-send-command-wait (list "STATUS \""
1298 (imap-utf7-encode mailbox)
1305 (mapcar (lambda (item)
1306 (imap-mailbox-get item mailbox))
1308 (imap-mailbox-get items mailbox)))))
1310 (defun imap-mailbox-status-asynch (mailbox items &optional buffer)
1311 "Send status item request ITEM on MAILBOX to server in BUFFER.
1312 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1313 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1314 or 'unseen. The IMAP command tag is returned."
1315 (with-current-buffer (or buffer (current-buffer))
1316 (imap-send-command (list "STATUS \""
1317 (imap-utf7-encode mailbox)
1324 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1325 "Get ACL on mailbox from server in BUFFER."
1326 (let ((mailbox (imap-utf7-encode mailbox)))
1327 (with-current-buffer (or buffer (current-buffer))
1329 (imap-send-command-wait (list "GETACL \""
1330 (or mailbox imap-current-mailbox)
1332 (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1334 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1335 "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
1336 (let ((mailbox (imap-utf7-encode mailbox)))
1337 (with-current-buffer (or buffer (current-buffer))
1339 (imap-send-command-wait (list "SETACL \""
1340 (or mailbox imap-current-mailbox)
1346 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1347 "Removes any <identifier,rights> pair for IDENTIFIER in MAILBOX from server in BUFFER."
1348 (let ((mailbox (imap-utf7-encode mailbox)))
1349 (with-current-buffer (or buffer (current-buffer))
1351 (imap-send-command-wait (list "DELETEACL \""
1352 (or mailbox imap-current-mailbox)
1357 ;; Message functions:
1359 (defun imap-current-message (&optional buffer)
1360 (with-current-buffer (or buffer (current-buffer))
1361 imap-current-message))
1363 (defun imap-list-to-message-set (list)
1364 (mapconcat (lambda (item)
1365 (number-to-string item))
1371 (defun imap-range-to-message-set (range)
1376 (car item) (cdr item))
1377 (format "%d" item)))
1378 (if (and (listp range) (not (listp (cdr range))))
1379 (list range) ;; make (1 . 2) into ((1 . 2))
1383 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1384 (with-current-buffer (or buffer (current-buffer))
1385 (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1387 (imap-list-to-message-set uids)
1391 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1392 "Fetch properties PROPS from message set UIDS from server in BUFFER.
1393 UIDS can be a string, number or a list of numbers. If RECEIVE
1394 is non-nil return theese properties."
1395 (with-current-buffer (or buffer (current-buffer))
1396 (when (imap-ok-p (imap-send-command-wait
1397 (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1399 (imap-list-to-message-set uids)
1402 (if (or (null receive) (stringp uids))
1405 (mapcar (lambda (uid)
1407 (mapcar (lambda (prop)
1408 (imap-message-get uid prop))
1410 (imap-message-get uid receive)))
1412 (imap-message-get uids receive))))))
1414 (defun imap-message-put (uid propname value &optional buffer)
1415 (with-current-buffer (or buffer (current-buffer))
1416 (if imap-message-data
1417 (put (intern (number-to-string uid) imap-message-data)
1419 (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1420 uid propname value (current-buffer)))
1423 (defun imap-message-get (uid propname &optional buffer)
1424 (with-current-buffer (or buffer (current-buffer))
1425 (get (intern-soft (number-to-string uid) imap-message-data)
1428 (defun imap-message-map (func propname &optional buffer)
1429 "Map a function across each mailbox in `imap-message-data', returning a list."
1430 (with-current-buffer (or buffer (current-buffer))
1434 (push (funcall func (get s 'UID) (get s propname)) result))
1438 (defmacro imap-message-envelope-date (uid &optional buffer)
1439 `(with-current-buffer (or ,buffer (current-buffer))
1440 (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1442 (defmacro imap-message-envelope-subject (uid &optional buffer)
1443 `(with-current-buffer (or ,buffer (current-buffer))
1444 (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1446 (defmacro imap-message-envelope-from (uid &optional buffer)
1447 `(with-current-buffer (or ,buffer (current-buffer))
1448 (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1450 (defmacro imap-message-envelope-sender (uid &optional buffer)
1451 `(with-current-buffer (or ,buffer (current-buffer))
1452 (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1454 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1455 `(with-current-buffer (or ,buffer (current-buffer))
1456 (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1458 (defmacro imap-message-envelope-to (uid &optional buffer)
1459 `(with-current-buffer (or ,buffer (current-buffer))
1460 (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1462 (defmacro imap-message-envelope-cc (uid &optional buffer)
1463 `(with-current-buffer (or ,buffer (current-buffer))
1464 (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1466 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1467 `(with-current-buffer (or ,buffer (current-buffer))
1468 (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1470 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1471 `(with-current-buffer (or ,buffer (current-buffer))
1472 (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1474 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1475 `(with-current-buffer (or ,buffer (current-buffer))
1476 (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1478 (defmacro imap-message-body (uid &optional buffer)
1479 `(with-current-buffer (or ,buffer (current-buffer))
1480 (imap-message-get ,uid 'BODY)))
1482 (defun imap-search (predicate &optional buffer)
1483 (with-current-buffer (or buffer (current-buffer))
1484 (imap-mailbox-put 'search 'dummy)
1485 (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1486 (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1488 (message "Missing SEARCH response to a SEARCH command (server not RFC compliant)...")
1490 (imap-mailbox-get-1 'search imap-current-mailbox)))))
1492 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1493 "Return t iff FLAG can be permanently (between IMAP sessions) saved on articles, in MAILBOX on server in BUFFER."
1494 (with-current-buffer (or buffer (current-buffer))
1495 (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1496 (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1498 (defun imap-message-flags-set (articles flags &optional silent buffer)
1499 (when (and articles flags)
1500 (with-current-buffer (or buffer (current-buffer))
1501 (imap-ok-p (imap-send-command-wait
1502 (concat "UID STORE " articles
1503 " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1505 (defun imap-message-flags-del (articles flags &optional silent buffer)
1506 (when (and articles flags)
1507 (with-current-buffer (or buffer (current-buffer))
1508 (imap-ok-p (imap-send-command-wait
1509 (concat "UID STORE " articles
1510 " -FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1512 (defun imap-message-flags-add (articles flags &optional silent buffer)
1513 (when (and articles flags)
1514 (with-current-buffer (or buffer (current-buffer))
1515 (imap-ok-p (imap-send-command-wait
1516 (concat "UID STORE " articles
1517 " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1519 (defun imap-message-copyuid-1 (mailbox)
1520 (if (imap-capability 'UIDPLUS)
1521 (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1522 (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1523 (let ((old-mailbox imap-current-mailbox)
1525 (imap-message-data (make-vector 2 0)))
1526 (when (imap-mailbox-examine-1 mailbox)
1528 (and (imap-fetch "*" "UID")
1529 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1530 (apply 'max (imap-message-map
1531 (lambda (uid prop) uid) 'UID))))
1533 (imap-mailbox-select old-mailbox (eq state 'examine))
1534 (imap-mailbox-unselect)))))))
1536 (defun imap-message-copyuid (mailbox &optional buffer)
1537 (with-current-buffer (or buffer (current-buffer))
1538 (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1540 (defun imap-message-copy (articles mailbox
1541 &optional dont-create no-copyuid buffer)
1542 "Copy ARTICLES (a string message set) to MAILBOX on server in
1543 BUFFER, creating mailbox if it doesn't exist. If dont-create is
1544 non-nil, it will not create a mailbox. On success, return a list with
1545 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1546 first element, rest of list contain the saved articles' UIDs."
1548 (with-current-buffer (or buffer (current-buffer))
1549 (let ((mailbox (imap-utf7-encode mailbox)))
1550 (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1551 (imap-current-target-mailbox mailbox))
1552 (if (imap-ok-p (imap-send-command-wait cmd))
1554 (when (and (not dont-create)
1555 ;; removed because of buggy Oracle server
1556 ;; that doesn't send TRYCREATE tags (which
1557 ;; is a MUST according to specifications):
1558 ;;(imap-mailbox-get-1 'trycreate mailbox)
1559 (imap-mailbox-create-1 mailbox))
1560 (imap-ok-p (imap-send-command-wait cmd)))))
1562 (imap-message-copyuid-1 mailbox)))))))
1564 (defun imap-message-appenduid-1 (mailbox)
1565 (if (imap-capability 'UIDPLUS)
1566 (imap-mailbox-get-1 'appenduid mailbox)
1567 (let ((old-mailbox imap-current-mailbox)
1569 (imap-message-data (make-vector 2 0)))
1570 (when (imap-mailbox-examine-1 mailbox)
1572 (and (imap-fetch "*" "UID")
1573 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1574 (apply 'max (imap-message-map
1575 (lambda (uid prop) uid) 'UID))))
1577 (imap-mailbox-select old-mailbox (eq state 'examine))
1578 (imap-mailbox-unselect)))))))
1580 (defun imap-message-appenduid (mailbox &optional buffer)
1581 (with-current-buffer (or buffer (current-buffer))
1582 (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1584 (defun imap-message-append (mailbox article &optional flags date-time buffer)
1585 "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1586 FLAGS and DATE-TIME is currently not used. Return a cons holding
1587 uidvalidity of MAILBOX and UID the newly created article got, or nil
1589 (let ((mailbox (imap-utf7-encode mailbox)))
1590 (with-current-buffer (or buffer (current-buffer))
1591 (and (let ((imap-current-target-mailbox mailbox))
1593 (imap-send-command-wait
1594 (list "APPEND \"" mailbox "\" " article))))
1595 (imap-message-appenduid-1 mailbox)))))
1597 (defun imap-body-lines (body)
1598 "Return number of lines in article by looking at the mime bodystructure BODY."
1600 (if (stringp (car body))
1601 (cond ((and (string= (upcase (car body)) "TEXT")
1602 (numberp (nth 7 body)))
1604 ((and (string= (upcase (car body)) "MESSAGE")
1605 (numberp (nth 9 body)))
1608 (apply '+ (mapcar 'imap-body-lines body)))
1611 (defun imap-envelope-from (from)
1612 "Return a from string line."
1614 (concat (aref from 0)
1615 (if (aref from 0) " <")
1619 (if (aref from 0) ">"))))
1622 ;; Internal functions.
1624 (defun imap-add-callback (tag func)
1625 (setq imap-callbacks (append (list (cons tag func)) imap-callbacks)))
1627 (defun imap-send-command-1 (cmdstr)
1628 (setq cmdstr (concat cmdstr imap-client-eol))
1630 (with-current-buffer (get-buffer-create imap-log-buffer)
1631 (buffer-disable-undo)
1632 (goto-char (point-max))
1634 (process-send-string imap-process cmdstr))
1636 (defun imap-send-command (command &optional buffer)
1637 (with-current-buffer (or buffer (current-buffer))
1638 (if (not (listp command)) (setq command (list command)))
1639 (let ((tag (setq imap-tag (1+ imap-tag)))
1641 (setq cmdstr (concat (number-to-string imap-tag) " "))
1642 (while (setq cmd (pop command))
1643 (cond ((stringp cmd)
1644 (setq cmdstr (concat cmdstr cmd)))
1646 (let ((eol imap-client-eol)
1647 (calcfirst imap-calculate-literal-size-first)
1649 (with-current-buffer cmd
1651 (setq size (buffer-size)))
1652 (when (not (equal eol "\r\n"))
1653 ;; XXX modifies buffer!
1654 (goto-char (point-min))
1655 (while (search-forward "\r\n" nil t)
1656 (replace-match eol)))
1658 (setq size (buffer-size))))
1660 (concat cmdstr (format "{%d}" size))))
1663 (imap-send-command-1 cmdstr)
1665 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1666 (setq command nil);; abort command if no cont-req
1667 (let ((process imap-process)
1668 (stream imap-stream)
1669 (eol imap-client-eol))
1670 (with-current-buffer cmd
1672 (with-current-buffer (get-buffer-create
1674 (buffer-disable-undo)
1675 (goto-char (point-max))
1676 (insert-buffer-substring cmd)))
1677 (process-send-region process (point-min)
1679 (process-send-string process imap-client-eol))))
1680 (setq imap-continuation nil)))
1682 (imap-send-command-1 cmdstr)
1685 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1686 (setq command nil);; abort command if no cont-req
1687 (setq command (cons (funcall cmd imap-continuation)
1689 (setq imap-continuation nil)))
1691 (error "Unknown command type"))))
1693 (imap-send-command-1 cmdstr))
1696 (defun imap-wait-for-tag (tag &optional buffer)
1697 (with-current-buffer (or buffer (current-buffer))
1698 (let (imap-have-messaged)
1699 (while (and (null imap-continuation)
1700 (memq (process-status imap-process) '(open run))
1701 (< imap-reached-tag tag))
1702 (let ((len (/ (point-max) 1024))
1705 (setq imap-have-messaged t)
1706 (message "imap read: %dk" len))
1707 (accept-process-output imap-process 1)))
1708 (when imap-have-messaged
1710 (and (memq (process-status imap-process) '(open run))
1711 (or (assq tag imap-failed-tags)
1712 (if imap-continuation
1716 (defun imap-sentinel (process string)
1717 (delete-process process))
1719 (defun imap-find-next-line ()
1720 "Return point at end of current line, taking into account literals.
1721 Return nil if no complete line has arrived."
1722 (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
1725 (if (match-string 1)
1726 (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1728 (goto-char (+ (point) (string-to-number (match-string 1))))
1729 (imap-find-next-line))
1732 (defun imap-arrival-filter (proc string)
1733 "IMAP process filter."
1734 (with-current-buffer (process-buffer proc)
1735 (goto-char (point-max))
1738 (with-current-buffer (get-buffer-create imap-log-buffer)
1739 (buffer-disable-undo)
1740 (goto-char (point-max))
1743 (goto-char (point-min))
1744 (while (setq end (imap-find-next-line))
1746 (narrow-to-region (point-min) end)
1747 (delete-backward-char (length imap-server-eol))
1748 (goto-char (point-min))
1750 (cond ((eq imap-state 'initial)
1751 (imap-parse-greeting))
1752 ((or (eq imap-state 'auth)
1753 (eq imap-state 'nonauth)
1754 (eq imap-state 'selected)
1755 (eq imap-state 'examine))
1756 (imap-parse-response))
1758 (message "Unknown state %s in arrival filter"
1760 (delete-region (point-min) (point-max))))))))
1765 (defsubst imap-forward ()
1766 (or (eobp) (forward-char)))
1769 ;; ; Unsigned 32-bit integer
1770 ;; ; (0 <= n < 4,294,967,296)
1772 (defsubst imap-parse-number ()
1773 (when (looking-at "[0-9]+")
1775 (string-to-number (match-string 0))
1776 (goto-char (match-end 0)))))
1778 ;; literal = "{" number "}" CRLF *CHAR8
1779 ;; ; Number represents the number of CHAR8s
1781 (defsubst imap-parse-literal ()
1782 (when (looking-at "{\\([0-9]+\\)}\r\n")
1783 (let ((pos (match-end 0))
1784 (len (string-to-number (match-string 1))))
1785 (if (< (point-max) (+ pos len))
1787 (goto-char (+ pos len))
1788 (buffer-substring pos (+ pos len))))))
1790 ;; string = quoted / literal
1792 ;; quoted = DQUOTE *QUOTED-CHAR DQUOTE
1794 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
1795 ;; "\" quoted-specials
1797 ;; quoted-specials = DQUOTE / "\"
1799 ;; TEXT-CHAR = <any CHAR except CR and LF>
1801 (defsubst imap-parse-string ()
1802 (cond ((eq (char-after) ?\")
1804 (let ((p (point)) (name ""))
1805 (skip-chars-forward "^\"\\\\")
1806 (setq name (buffer-substring p (point)))
1807 (while (eq (char-after) ?\\)
1808 (setq p (1+ (point)))
1810 (skip-chars-forward "^\"\\\\")
1811 (setq name (concat name (buffer-substring p (point)))))
1814 ((eq (char-after) ?{)
1815 (imap-parse-literal))))
1819 (defsubst imap-parse-nil ()
1820 (if (looking-at "NIL")
1821 (goto-char (match-end 0))))
1823 ;; nstring = string / nil
1825 (defsubst imap-parse-nstring ()
1826 (or (imap-parse-string)
1827 (and (imap-parse-nil)
1830 ;; astring = atom / string
1832 ;; atom = 1*ATOM-CHAR
1834 ;; ATOM-CHAR = <any CHAR except atom-specials>
1836 ;; atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards /
1839 ;; list-wildcards = "%" / "*"
1841 ;; quoted-specials = DQUOTE / "\"
1843 (defsubst imap-parse-astring ()
1844 (or (imap-parse-string)
1845 (buffer-substring (point)
1846 (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
1847 (goto-char (1- (match-end 0)))
1851 ;; address = "(" addr-name SP addr-adl SP addr-mailbox SP
1854 ;; addr-adl = nstring
1855 ;; ; Holds route from [RFC-822] route-addr if
1858 ;; addr-host = nstring
1859 ;; ; nil indicates [RFC-822] group syntax.
1860 ;; ; Otherwise, holds [RFC-822] domain name
1862 ;; addr-mailbox = nstring
1863 ;; ; nil indicates end of [RFC-822] group; if
1864 ;; ; non-nil and addr-host is nil, holds
1865 ;; ; [RFC-822] group name.
1866 ;; ; Otherwise, holds [RFC-822] local-part
1867 ;; ; after removing [RFC-822] quoting
1869 ;; addr-name = nstring
1870 ;; ; If non-nil, holds phrase from [RFC-822]
1871 ;; ; mailbox after removing [RFC-822] quoting
1874 (defsubst imap-parse-address ()
1876 (when (eq (char-after) ?\()
1878 (setq address (vector (prog1 (imap-parse-nstring)
1880 (prog1 (imap-parse-nstring)
1882 (prog1 (imap-parse-nstring)
1884 (imap-parse-nstring)))
1885 (when (eq (char-after) ?\))
1889 ;; address-list = "(" 1*address ")" / nil
1893 (defsubst imap-parse-address-list ()
1894 (if (eq (char-after) ?\()
1895 (let (address addresses)
1897 (while (and (not (eq (char-after) ?\)))
1898 ;; next line for MS Exchange bug
1899 (progn (and (eq (char-after) ? ) (imap-forward)) t)
1900 (setq address (imap-parse-address)))
1901 (setq addresses (cons address addresses)))
1902 (when (eq (char-after) ?\))
1904 (nreverse addresses)))
1905 (assert (imap-parse-nil) t "In imap-parse-address-list")))
1907 ;; mailbox = "INBOX" / astring
1908 ;; ; INBOX is case-insensitive. All case variants of
1909 ;; ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
1910 ;; ; not as an astring. An astring which consists of
1911 ;; ; the case-insensitive sequence "I" "N" "B" "O" "X"
1912 ;; ; is considered to be INBOX and not an astring.
1913 ;; ; Refer to section 5.1 for further
1914 ;; ; semantic details of mailbox names.
1916 (defsubst imap-parse-mailbox ()
1917 (let ((mailbox (imap-parse-astring)))
1918 (if (string-equal "INBOX" (upcase mailbox))
1922 ;; greeting = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
1924 ;; resp-cond-auth = ("OK" / "PREAUTH") SP resp-text
1925 ;; ; Authentication condition
1927 ;; resp-cond-bye = "BYE" SP resp-text
1929 (defun imap-parse-greeting ()
1930 "Parse a IMAP greeting."
1931 (cond ((looking-at "\\* OK ")
1932 (setq imap-state 'nonauth))
1933 ((looking-at "\\* PREAUTH ")
1934 (setq imap-state 'auth))
1935 ((looking-at "\\* BYE ")
1936 (setq imap-state 'closed))))
1938 ;; response = *(continue-req / response-data) response-done
1940 ;; continue-req = "+" SP (resp-text / base64) CRLF
1942 ;; response-data = "*" SP (resp-cond-state / resp-cond-bye /
1943 ;; mailbox-data / message-data / capability-data) CRLF
1945 ;; response-done = response-tagged / response-fatal
1947 ;; response-fatal = "*" SP resp-cond-bye CRLF
1948 ;; ; Server closes connection immediately
1950 ;; response-tagged = tag SP resp-cond-state CRLF
1952 ;; resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
1953 ;; ; Status condition
1955 ;; resp-cond-bye = "BYE" SP resp-text
1957 ;; mailbox-data = "FLAGS" SP flag-list /
1958 ;; "LIST" SP mailbox-list /
1959 ;; "LSUB" SP mailbox-list /
1960 ;; "SEARCH" *(SP nz-number) /
1961 ;; "STATUS" SP mailbox SP "("
1962 ;; [status-att SP number *(SP status-att SP number)] ")" /
1963 ;; number SP "EXISTS" /
1964 ;; number SP "RECENT"
1966 ;; message-data = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
1968 ;; capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
1970 ;; ; IMAP4rev1 servers which offer RFC 1730
1971 ;; ; compatibility MUST list "IMAP4" as the first
1974 (defun imap-parse-response ()
1975 "Parse a IMAP command response."
1977 (case (setq token (read (current-buffer)))
1978 (+ (setq imap-continuation
1979 (or (buffer-substring (min (point-max) (1+ (point)))
1982 (* (case (prog1 (setq token (read (current-buffer)))
1984 (OK (imap-parse-resp-text))
1985 (NO (imap-parse-resp-text))
1986 (BAD (imap-parse-resp-text))
1987 (BYE (imap-parse-resp-text))
1988 (FLAGS (imap-mailbox-put 'flags (imap-parse-flag-list)))
1989 (LIST (imap-parse-data-list 'list))
1990 (LSUB (imap-parse-data-list 'lsub))
1991 (SEARCH (imap-mailbox-put
1993 (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
1994 (STATUS (imap-parse-status))
1995 (CAPABILITY (setq imap-capability
1996 (read (concat "(" (upcase (buffer-substring
1997 (point) (point-max)))
1999 (ACL (imap-parse-acl))
2000 (t (case (prog1 (read (current-buffer))
2002 (EXISTS (imap-mailbox-put 'exists token))
2003 (RECENT (imap-mailbox-put 'recent token))
2005 (FETCH (imap-parse-fetch token))
2006 (t (message "Garbage: %s" (buffer-string)))))))
2008 (if (not (integerp token))
2009 (message "Garbage: %s" (buffer-string))
2010 (case (prog1 (setq status (read (current-buffer)))
2013 (setq imap-reached-tag (max imap-reached-tag token))
2014 (imap-parse-resp-text)))
2016 (setq imap-reached-tag (max imap-reached-tag token))
2018 (imap-parse-resp-text))
2020 (when (eq (char-after) ?\[)
2021 (setq code (buffer-substring (point)
2022 (search-forward "]")))
2024 (setq text (buffer-substring (point) (point-max)))
2025 (push (list token status code text)
2026 imap-failed-tags))))
2028 (setq imap-reached-tag (max imap-reached-tag token))
2030 (imap-parse-resp-text))
2032 (when (eq (char-after) ?\[)
2033 (setq code (buffer-substring (point)
2034 (search-forward "]")))
2036 (setq text (buffer-substring (point) (point-max)))
2037 (push (list token status code text) imap-failed-tags)
2038 (error "Internal error, tag %s status %s code %s text %s"
2039 token status code text))))
2040 (t (message "Garbage: %s" (buffer-string))))
2041 (when (assq token imap-callbacks)
2042 (funcall (cdr (assq token imap-callbacks)) token status)
2043 (setq imap-callbacks
2044 (imap-remassoc token imap-callbacks)))))))))
2046 ;; resp-text = ["[" resp-text-code "]" SP] text
2048 ;; text = 1*TEXT-CHAR
2050 ;; TEXT-CHAR = <any CHAR except CR and LF>
2052 (defun imap-parse-resp-text ()
2053 (imap-parse-resp-text-code))
2055 ;; resp-text-code = "ALERT" /
2056 ;; "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
2057 ;; "NEWNAME" SP string SP string /
2059 ;; "PERMANENTFLAGS" SP "("
2060 ;; [flag-perm *(SP flag-perm)] ")" /
2064 ;; "UIDNEXT" SP nz-number /
2065 ;; "UIDVALIDITY" SP nz-number /
2066 ;; "UNSEEN" SP nz-number /
2067 ;; resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
2069 ;; resp_code_apnd = "APPENDUID" SPACE nz_number SPACE uniqueid
2071 ;; resp_code_copy = "COPYUID" SPACE nz_number SPACE set SPACE set
2073 ;; set = sequence-num / (sequence-num ":" sequence-num) /
2075 ;; ; Identifies a set of messages. For message
2076 ;; ; sequence numbers, these are consecutive
2077 ;; ; numbers from 1 to the number of messages in
2079 ;; ; Comma delimits individual numbers, colon
2080 ;; ; delimits between two numbers inclusive.
2081 ;; ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
2082 ;; ; 14,15 for a mailbox with 15 messages.
2084 ;; sequence-num = nz-number / "*"
2085 ;; ; * is the largest number in use. For message
2086 ;; ; sequence numbers, it is the number of messages
2087 ;; ; in the mailbox. For unique identifiers, it is
2088 ;; ; the unique identifier of the last message in
2091 ;; flag-perm = flag / "\*"
2093 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2094 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2095 ;; ; Does not include "\Recent"
2097 ;; flag-extension = "\" atom
2098 ;; ; Future expansion. Client implementations
2099 ;; ; MUST accept flag-extension flags. Server
2100 ;; ; implementations MUST NOT generate
2101 ;; ; flag-extension flags except as defined by
2102 ;; ; future standard or standards-track
2103 ;; ; revisions of this specification.
2105 ;; flag-keyword = atom
2107 ;; resp-text-atom = 1*<any ATOM-CHAR except "]">
2109 (defun imap-parse-resp-text-code ()
2110 ;; xxx next line for stalker communigate pro 3.3.1 bug
2111 (when (looking-at " \\[")
2113 (when (eq (char-after) ?\[)
2115 (cond ((search-forward "PERMANENTFLAGS " nil t)
2116 (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2117 ((search-forward "UIDNEXT \\([0-9]+\\)" nil t)
2118 (imap-mailbox-put 'uidnext (match-string 1)))
2119 ((search-forward "UNSEEN " nil t)
2120 (imap-mailbox-put 'unseen (read (current-buffer))))
2121 ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2122 (imap-mailbox-put 'uidvalidity (match-string 1)))
2123 ((search-forward "READ-ONLY" nil t)
2124 (imap-mailbox-put 'read-only t))
2125 ((search-forward "NEWNAME " nil t)
2126 (let (oldname newname)
2127 (setq oldname (imap-parse-string))
2129 (setq newname (imap-parse-string))
2130 (imap-mailbox-put 'newname newname oldname)))
2131 ((search-forward "TRYCREATE" nil t)
2132 (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2133 ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2134 (imap-mailbox-put 'appenduid
2135 (list (match-string 1)
2136 (string-to-number (match-string 2)))
2137 imap-current-target-mailbox))
2138 ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2139 (imap-mailbox-put 'copyuid (list (match-string 1)
2142 imap-current-target-mailbox))
2143 ((search-forward "ALERT] " nil t)
2144 (message "Imap server %s information: %s" imap-server
2145 (buffer-substring (point) (point-max)))))))
2147 ;; mailbox-list = "(" [mbx-list-flags] ")" SP
2148 ;; (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2150 ;; mbx-list-flags = *(mbx-list-oflag SP) mbx-list-sflag
2151 ;; *(SP mbx-list-oflag) /
2152 ;; mbx-list-oflag *(SP mbx-list-oflag)
2154 ;; mbx-list-oflag = "\Noinferiors" / flag-extension
2155 ;; ; Other flags; multiple possible per LIST response
2157 ;; mbx-list-sflag = "\Noselect" / "\Marked" / "\Unmarked"
2158 ;; ; Selectability flags; only one per LIST response
2160 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2161 ;; "\" quoted-specials
2163 ;; quoted-specials = DQUOTE / "\"
2165 (defun imap-parse-data-list (type)
2166 (let (flags delimiter mailbox)
2167 (setq flags (imap-parse-flag-list))
2168 (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2169 (setq delimiter (match-string 1))
2170 (goto-char (1+ (match-end 0)))
2171 (when (setq mailbox (imap-parse-mailbox))
2172 (imap-mailbox-put type t mailbox)
2173 (imap-mailbox-put 'list-flags flags mailbox)
2174 (imap-mailbox-put 'delimiter delimiter mailbox)))))
2176 ;; msg_att ::= "(" 1#("ENVELOPE" SPACE envelope /
2177 ;; "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2178 ;; "INTERNALDATE" SPACE date_time /
2179 ;; "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2180 ;; "RFC822.SIZE" SPACE number /
2181 ;; "BODY" ["STRUCTURE"] SPACE body /
2182 ;; "BODY" section ["<" number ">"] SPACE nstring /
2183 ;; "UID" SPACE uniqueid) ")"
2185 ;; date_time ::= <"> date_day_fixed "-" date_month "-" date_year
2186 ;; SPACE time SPACE zone <">
2188 ;; section ::= "[" [section_text / (nz_number *["." nz_number]
2189 ;; ["." (section_text / "MIME")])] "]"
2191 ;; section_text ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2192 ;; SPACE header_list / "TEXT"
2194 ;; header_fld_name ::= astring
2196 ;; header_list ::= "(" 1#header_fld_name ")"
2198 (defsubst imap-parse-header-list ()
2199 (when (eq (char-after) ?\()
2201 (while (not (eq (char-after) ?\)))
2203 (push (imap-parse-astring) strlist))
2205 (nreverse strlist))))
2207 (defsubst imap-parse-fetch-body-section ()
2209 (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2210 (if (eq (char-before) ? )
2212 (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2213 (search-forward "]" nil t))
2216 (defun imap-parse-fetch (response)
2217 (when (eq (char-after) ?\()
2218 (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2219 rfc822size body bodydetail bodystructure flags-empty)
2220 (while (not (eq (char-after) ?\)))
2222 (let ((token (read (current-buffer))))
2224 (cond ((eq token 'UID)
2225 (setq uid (condition-case ()
2226 (read (current-buffer))
2229 (setq flags (imap-parse-flag-list))
2231 (setq flags-empty 't)))
2232 ((eq token 'ENVELOPE)
2233 (setq envelope (imap-parse-envelope)))
2234 ((eq token 'INTERNALDATE)
2235 (setq internaldate (imap-parse-string)))
2237 (setq rfc822 (imap-parse-nstring)))
2238 ((eq token 'RFC822.HEADER)
2239 (setq rfc822header (imap-parse-nstring)))
2240 ((eq token 'RFC822.TEXT)
2241 (setq rfc822text (imap-parse-nstring)))
2242 ((eq token 'RFC822.SIZE)
2243 (setq rfc822size (read (current-buffer))))
2245 (if (eq (char-before) ?\[)
2247 (upcase (imap-parse-fetch-body-section))
2248 (and (eq (char-after) ?<)
2249 (buffer-substring (1+ (point))
2250 (search-forward ">" nil t)))
2251 (progn (imap-forward)
2252 (imap-parse-nstring)))
2254 (setq body (imap-parse-body))))
2255 ((eq token 'BODYSTRUCTURE)
2256 (setq bodystructure (imap-parse-body))))))
2258 (setq imap-current-message uid)
2259 (imap-message-put uid 'UID uid)
2260 (and (or flags flags-empty) (imap-message-put uid 'FLAGS flags))
2261 (and envelope (imap-message-put uid 'ENVELOPE envelope))
2262 (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2263 (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2264 (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2265 (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2266 (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2267 (and body (imap-message-put uid 'BODY body))
2268 (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2269 (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2270 (run-hooks 'imap-fetch-data-hook)))))
2272 ;; mailbox-data = ...
2273 ;; "STATUS" SP mailbox SP "("
2274 ;; [status-att SP number
2275 ;; *(SP status-att SP number)] ")"
2278 ;; status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2281 (defun imap-parse-status ()
2282 (let ((mailbox (imap-parse-mailbox)))
2283 (when (and mailbox (search-forward "(" nil t))
2284 (while (not (eq (char-after) ?\)))
2285 (let ((token (read (current-buffer))))
2286 (cond ((eq token 'MESSAGES)
2287 (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2289 (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2290 ((eq token 'UIDNEXT)
2291 (and (looking-at " \\([0-9]+\\)")
2292 (imap-mailbox-put 'uidnext (match-string 1) mailbox)
2293 (goto-char (match-end 1))))
2294 ((eq token 'UIDVALIDITY)
2295 (and (looking-at " \\([0-9]+\\)")
2296 (imap-mailbox-put 'uidvalidity (match-string 1) mailbox)
2297 (goto-char (match-end 1))))
2299 (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2301 (message "Unknown status data %s in mailbox %s ignored"
2302 token mailbox))))))))
2304 ;; acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2307 ;; identifier ::= astring
2309 ;; rights ::= astring
2311 (defun imap-parse-acl ()
2312 (let ((mailbox (imap-parse-mailbox))
2313 identifier rights acl)
2314 (while (eq (char-after) ?\ )
2316 (setq identifier (imap-parse-astring))
2318 (setq rights (imap-parse-astring))
2319 (setq acl (append acl (list (cons identifier rights)))))
2320 (imap-mailbox-put 'acl acl mailbox)))
2322 ;; flag-list = "(" [flag *(SP flag)] ")"
2324 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2325 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2326 ;; ; Does not include "\Recent"
2328 ;; flag-keyword = atom
2330 ;; flag-extension = "\" atom
2331 ;; ; Future expansion. Client implementations
2332 ;; ; MUST accept flag-extension flags. Server
2333 ;; ; implementations MUST NOT generate
2334 ;; ; flag-extension flags except as defined by
2335 ;; ; future standard or standards-track
2336 ;; ; revisions of this specification.
2338 (defun imap-parse-flag-list ()
2339 (let (flag-list start)
2340 (assert (eq (char-after) ?\() t "In imap-parse-flag-list")
2341 (while (and (not (eq (char-after) ?\)))
2344 ;; next line for Courier IMAP bug.
2345 (skip-chars-forward " ")
2347 (> (skip-chars-forward "^ )" (imap-point-at-eol)) 0))
2348 (push (buffer-substring start (point)) flag-list))
2349 (assert (eq (char-after) ?\)) t "In imap-parse-flag-list")
2351 (nreverse flag-list)))
2353 ;; envelope = "(" env-date SP env-subject SP env-from SP env-sender SP
2354 ;; env-reply-to SP env-to SP env-cc SP env-bcc SP
2355 ;; env-in-reply-to SP env-message-id ")"
2357 ;; env-bcc = "(" 1*address ")" / nil
2359 ;; env-cc = "(" 1*address ")" / nil
2361 ;; env-date = nstring
2363 ;; env-from = "(" 1*address ")" / nil
2365 ;; env-in-reply-to = nstring
2367 ;; env-message-id = nstring
2369 ;; env-reply-to = "(" 1*address ")" / nil
2371 ;; env-sender = "(" 1*address ")" / nil
2373 ;; env-subject = nstring
2375 ;; env-to = "(" 1*address ")" / nil
2377 (defun imap-parse-envelope ()
2378 (when (eq (char-after) ?\()
2380 (vector (prog1 (imap-parse-nstring);; date
2382 (prog1 (imap-parse-nstring);; subject
2384 (prog1 (imap-parse-address-list);; from
2386 (prog1 (imap-parse-address-list);; sender
2388 (prog1 (imap-parse-address-list);; reply-to
2390 (prog1 (imap-parse-address-list);; to
2392 (prog1 (imap-parse-address-list);; cc
2394 (prog1 (imap-parse-address-list);; bcc
2396 (prog1 (imap-parse-nstring);; in-reply-to
2398 (prog1 (imap-parse-nstring);; message-id
2401 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2403 (defsubst imap-parse-string-list ()
2404 (cond ((eq (char-after) ?\();; body-fld-param
2407 (while (setq str (imap-parse-string))
2409 ;; buggy stalker communigate pro 3.0 doesn't print SPC
2410 ;; between body-fld-param's sometimes
2411 (or (eq (char-after) ?\")
2413 (nreverse strlist)))
2417 ;; body-extension = nstring / number /
2418 ;; "(" body-extension *(SP body-extension) ")"
2419 ;; ; Future expansion. Client implementations
2420 ;; ; MUST accept body-extension fields. Server
2421 ;; ; implementations MUST NOT generate
2422 ;; ; body-extension fields except as defined by
2423 ;; ; future standard or standards-track
2424 ;; ; revisions of this specification.
2426 (defun imap-parse-body-extension ()
2427 (if (eq (char-after) ?\()
2430 (push (imap-parse-body-extension) b-e)
2431 (while (eq (char-after) ?\ )
2433 (push (imap-parse-body-extension) b-e))
2434 (assert (eq (char-after) ?\)) t "In imap-parse-body-extension")
2437 (or (imap-parse-number)
2438 (imap-parse-nstring))))
2440 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2441 ;; *(SP body-extension)]]
2442 ;; ; MUST NOT be returned on non-extensible
2445 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2446 ;; *(SP body-extension)]]
2447 ;; ; MUST NOT be returned on non-extensible
2450 (defsubst imap-parse-body-ext ()
2452 (when (eq (char-after) ?\ );; body-fld-dsp
2455 (if (eq (char-after) ?\()
2458 (push (imap-parse-string) dsp)
2460 (push (imap-parse-string-list) dsp)
2462 (assert (imap-parse-nil) t "In imap-parse-body-ext"))
2463 (push (nreverse dsp) ext))
2464 (when (eq (char-after) ?\ );; body-fld-lang
2466 (if (eq (char-after) ?\()
2467 (push (imap-parse-string-list) ext)
2468 (push (imap-parse-nstring) ext))
2469 (while (eq (char-after) ?\ );; body-extension
2471 (setq ext (append (imap-parse-body-extension) ext)))))
2474 ;; body = "(" body-type-1part / body-type-mpart ")"
2476 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2477 ;; *(SP body-extension)]]
2478 ;; ; MUST NOT be returned on non-extensible
2481 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2482 ;; *(SP body-extension)]]
2483 ;; ; MUST NOT be returned on non-extensible
2486 ;; body-fields = body-fld-param SP body-fld-id SP body-fld-desc SP
2487 ;; body-fld-enc SP body-fld-octets
2489 ;; body-fld-desc = nstring
2491 ;; body-fld-dsp = "(" string SP body-fld-param ")" / nil
2493 ;; body-fld-enc = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2494 ;; "QUOTED-PRINTABLE") DQUOTE) / string
2496 ;; body-fld-id = nstring
2498 ;; body-fld-lang = nstring / "(" string *(SP string) ")"
2500 ;; body-fld-lines = number
2502 ;; body-fld-md5 = nstring
2504 ;; body-fld-octets = number
2506 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2508 ;; body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2509 ;; [SP body-ext-1part]
2511 ;; body-type-basic = media-basic SP body-fields
2512 ;; ; MESSAGE subtype MUST NOT be "RFC822"
2514 ;; body-type-msg = media-message SP body-fields SP envelope
2515 ;; SP body SP body-fld-lines
2517 ;; body-type-text = media-text SP body-fields SP body-fld-lines
2519 ;; body-type-mpart = 1*body SP media-subtype
2520 ;; [SP body-ext-mpart]
2522 ;; media-basic = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2523 ;; "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2524 ;; ; Defined in [MIME-IMT]
2526 ;; media-message = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2527 ;; ; Defined in [MIME-IMT]
2529 ;; media-subtype = string
2530 ;; ; Defined in [MIME-IMT]
2532 ;; media-text = DQUOTE "TEXT" DQUOTE SP media-subtype
2533 ;; ; Defined in [MIME-IMT]
2535 (defun imap-parse-body ()
2537 (when (eq (char-after) ?\()
2539 (if (eq (char-after) ?\()
2541 (while (and (eq (char-after) ?\()
2542 (setq subbody (imap-parse-body)))
2543 ;; buggy stalker communigate pro 3.0 insert a SPC between
2544 ;; parts in multiparts
2545 (when (and (eq (char-after) ?\ )
2546 (eq (char-after (1+ (point))) ?\())
2548 (push subbody body))
2550 (push (imap-parse-string) body);; media-subtype
2551 (when (eq (char-after) ?\ );; body-ext-mpart:
2553 (if (eq (char-after) ?\();; body-fld-param
2554 (push (imap-parse-string-list) body)
2555 (push (and (imap-parse-nil) nil) body))
2557 (append (imap-parse-body-ext) body)));; body-ext-...
2558 (assert (eq (char-after) ?\)) t "In imap-parse-body")
2562 (push (imap-parse-string) body);; media-type
2564 (push (imap-parse-string) body);; media-subtype
2566 ;; next line for Sun SIMS bug
2567 (and (eq (char-after) ? ) (imap-forward))
2568 (if (eq (char-after) ?\();; body-fld-param
2569 (push (imap-parse-string-list) body)
2570 (push (and (imap-parse-nil) nil) body))
2572 (push (imap-parse-nstring) body);; body-fld-id
2574 (push (imap-parse-nstring) body);; body-fld-desc
2576 ;; next `or' for Sun SIMS bug, it regard body-fld-enc as a
2577 ;; nstring and return nil instead of defaulting back to 7BIT
2578 ;; as the standard says.
2579 (push (or (imap-parse-nstring) "7BIT") body);; body-fld-enc
2581 (push (imap-parse-number) body);; body-fld-octets
2583 ;; ok, we're done parsing the required parts, what comes now is one
2586 ;; envelope (then we're parsing body-type-msg)
2587 ;; body-fld-lines (then we're parsing body-type-text)
2588 ;; body-ext-1part (then we're parsing body-type-basic)
2590 ;; the problem is that the two first are in turn optionally followed
2591 ;; by the third. So we parse the first two here (if there are any)...
2593 (when (eq (char-after) ?\ )
2596 (cond ((eq (char-after) ?\();; body-type-msg:
2597 (push (imap-parse-envelope) body);; envelope
2599 (push (imap-parse-body) body);; body
2600 ;; buggy stalker communigate pro 3.0 doesn't print
2601 ;; number of lines in message/rfc822 attachment
2602 (if (eq (char-after) ?\))
2605 (push (imap-parse-number) body))) ;; body-fld-lines
2606 ((setq lines (imap-parse-number)) ;; body-type-text:
2607 (push lines body)) ;; body-fld-lines
2609 (backward-char))))) ;; no match...
2611 ;; ...and then parse the third one here...
2613 (when (eq (char-after) ?\ );; body-ext-1part:
2615 (push (imap-parse-nstring) body);; body-fld-md5
2616 (setq body (append (imap-parse-body-ext) body)));; body-ext-1part..
2618 (assert (eq (char-after) ?\)) t "In imap-parse-body 2")
2622 (when imap-debug ; (untrace-all)
2624 (buffer-disable-undo (get-buffer-create imap-debug-buffer))
2625 (mapcar (lambda (f) (trace-function-background f imap-debug-buffer))
2637 imap-interactive-login
2653 imap-send-command-wait
2658 imap-current-mailbox
2659 imap-current-mailbox-p-1
2660 imap-current-mailbox-p
2661 imap-mailbox-select-1
2663 imap-mailbox-examine-1
2664 imap-mailbox-examine
2665 imap-mailbox-unselect
2666 imap-mailbox-expunge
2668 imap-mailbox-create-1
2674 imap-mailbox-subscribe
2675 imap-mailbox-unsubscribe
2677 imap-mailbox-acl-get
2678 imap-mailbox-acl-set
2679 imap-mailbox-acl-delete
2680 imap-current-message
2681 imap-list-to-message-set
2688 imap-message-flag-permanent-p
2689 imap-message-flags-set
2690 imap-message-flags-del
2691 imap-message-flags-add
2692 imap-message-copyuid-1
2693 imap-message-copyuid
2695 imap-message-appenduid-1
2696 imap-message-appenduid
2708 imap-parse-resp-text
2709 imap-parse-resp-text-code
2710 imap-parse-data-list
2714 imap-parse-flag-list
2716 imap-parse-body-extension
2722 ;;; imap.el ends here