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))
141 (autoload 'open-ssl-stream "ssl")
142 (autoload 'base64-decode-string "base64")
143 (autoload 'base64-encode-string "base64")
144 (autoload 'starttls-open-stream "starttls")
145 (autoload 'starttls-negotiate "starttls")
146 (autoload 'digest-md5-parse-digest-challenge "digest-md5")
147 (autoload 'digest-md5-digest-response "digest-md5")
148 (autoload 'digest-md5-digest-uri "digest-md5")
149 (autoload 'digest-md5-challenge "digest-md5")
150 (autoload 'rfc2104-hash "rfc2104")
151 (autoload 'md5 "md5")
152 (autoload 'utf7-encode "utf7")
153 (autoload 'utf7-decode "utf7")
154 (autoload 'format-spec "format-spec")
155 (autoload 'format-spec-make "format-spec")
156 ;; Avoid use gnus-point-at-eol so we're independent of Gnus. These
157 ;; days we have point-at-eol anyhow.
158 (if (fboundp 'point-at-eol)
159 (defalias 'imap-point-at-eol 'point-at-eol)
160 (defun imap-point-at-eol ()
168 "Low-level IMAP issues."
172 (defcustom imap-kerberos4-program '("imtest -m kerberos_v4 -u %l -p %p %s"
174 "List of strings containing commands for Kerberos 4 authentication.
175 %s is replaced with server hostname, %p with port to connect to, and
176 %l with the value of `imap-default-user'. The program should accept
177 IMAP commands on stdin and return responses to stdout. Each entry in
178 the list is tried until a successful connection is made."
180 :type '(repeat string))
182 (defcustom imap-gssapi-program '("imtest -m gssapi -u %l -p %p %s")
183 "List of strings containing commands for GSSAPI (krb5) authentication.
184 %s is replaced with server hostname, %p with port to connect to, and
185 %l with the value of `imap-default-user'. The program should accept
186 IMAP commands on stdin and return responses to stdout. Each entry in
187 the list is tried until a successful connection is made."
189 :type '(repeat string))
191 (defcustom imap-ssl-program '("openssl s_client -quiet -ssl3 -connect %s:%p"
192 "openssl s_client -quiet -ssl2 -connect %s:%p"
193 "s_client -quiet -ssl3 -connect %s:%p"
194 "s_client -quiet -ssl2 -connect %s:%p")
195 "A string, or list of strings, containing commands for SSL connections.
196 Within a string, %s is replaced with the server address and %p with
197 port number on server. The program should accept IMAP commands on
198 stdin and return responses to stdout. Each entry in the list is tried
199 until a successful connection is made."
201 :type '(choice string
204 (defcustom imap-shell-program '("ssh %s imapd"
206 "ssh %g ssh %s imapd"
207 "rsh %g rsh %s imapd")
208 "A list of strings, containing commands for IMAP connection.
209 Within a string, %s is replaced with the server address, %p with port
210 number on server, %g with `imap-shell-host', and %l with
211 `imap-default-user'. The program should read IMAP commands from stdin
212 and write IMAP response to stdout. Each entry in the list is tried
213 until a successful connection is made."
215 :type '(repeat string))
217 (defcustom imap-process-connection-type nil
218 "*Value for `process-connection-type' to use for Kerberos4 and GSSAPI."
222 (defcustom imap-use-utf7 t
223 "If non-nil, do utf7 encoding/decoding of mailbox names.
224 Since the UTF7 decoding currently only decodes into ISO-8859-1
225 characters, you may disable this decoding if you need to access UTF7
226 encoded mailboxes which doesn't translate into ISO-8859-1."
230 (defcustom imap-log nil
231 "If non-nil, a imap session trace is placed in *imap-log* buffer."
235 (defcustom imap-debug nil
236 "If non-nil, random debug spews are placed in *imap-debug* buffer."
240 (defcustom imap-shell-host "gateway"
241 "Hostname of rlogin proxy."
245 (defcustom imap-default-user (user-login-name)
246 "Default username to use."
250 ;; Various variables.
252 (defvar imap-fetch-data-hook nil
253 "Hooks called after receiving each FETCH response.")
255 (defvar imap-streams '(gssapi kerberos4 starttls ssl network shell)
256 "Priority of streams to consider when opening connection to server.")
258 (defvar imap-stream-alist
259 '((gssapi imap-gssapi-stream-p imap-gssapi-open)
260 (kerberos4 imap-kerberos4-stream-p imap-kerberos4-open)
261 (ssl imap-ssl-p imap-ssl-open)
262 (network imap-network-p imap-network-open)
263 (shell imap-shell-p imap-shell-open)
264 (starttls imap-starttls-p imap-starttls-open))
265 "Definition of network streams.
269 NAME names the stream, CHECK is a function returning non-nil if the
270 server support the stream and OPEN is a function for opening the
273 (defvar imap-authenticators '(gssapi
279 "Priority of authenticators to consider when authenticating to server.")
281 (defvar imap-authenticator-alist
282 '((gssapi imap-gssapi-auth-p imap-gssapi-auth)
283 (kerberos4 imap-kerberos4-auth-p imap-kerberos4-auth)
284 (cram-md5 imap-cram-md5-p imap-cram-md5-auth)
285 (login imap-login-p imap-login-auth)
286 (anonymous imap-anonymous-p imap-anonymous-auth)
287 (digest-md5 imap-digest-md5-p imap-digest-md5-auth))
288 "Definition of authenticators.
290 \(NAME CHECK AUTHENTICATE)
292 NAME names the authenticator. CHECK is a function returning non-nil if
293 the server support the authenticator and AUTHENTICATE is a function
294 for doing the actual authentication.")
296 (defvar imap-error nil
297 "Error codes from the last command.")
299 ;; Internal constants. Change theese and die.
301 (defconst imap-default-port 143)
302 (defconst imap-default-ssl-port 993)
303 (defconst imap-default-stream 'network)
304 (defconst imap-coding-system-for-read 'binary)
305 (defconst imap-coding-system-for-write 'binary)
306 (defconst imap-local-variables '(imap-server
315 imap-current-target-mailbox
324 imap-calculate-literal-size-first
326 (defconst imap-log-buffer "*imap-log*")
327 (defconst imap-debug-buffer "*imap-debug*")
329 ;; Internal variables.
331 (defvar imap-stream nil)
332 (defvar imap-auth nil)
333 (defvar imap-server nil)
334 (defvar imap-port nil)
335 (defvar imap-username nil)
336 (defvar imap-password nil)
337 (defvar imap-calculate-literal-size-first nil)
338 (defvar imap-state 'closed
340 Valid states are `closed', `initial', `nonauth', `auth', `selected'
343 (defvar imap-server-eol "\r\n"
344 "The EOL string sent from the server.")
346 (defvar imap-client-eol "\r\n"
347 "The EOL string we send to the server.")
349 (defvar imap-current-mailbox nil
350 "Current mailbox name.")
352 (defvar imap-current-target-mailbox nil
353 "Current target mailbox for COPY and APPEND commands.")
355 (defvar imap-mailbox-data nil
356 "Obarray with mailbox data.")
358 (defvar imap-mailbox-prime 997
359 "Length of imap-mailbox-data.")
361 (defvar imap-current-message nil
362 "Current message number.")
364 (defvar imap-message-data nil
365 "Obarray with message data.")
367 (defvar imap-message-prime 997
368 "Length of imap-message-data.")
370 (defvar imap-capability nil
371 "Capability for server.")
373 (defvar imap-namespace nil
374 "Namespace for current server.")
376 (defvar imap-reached-tag 0
377 "Lower limit on command tags that have been parsed.")
379 (defvar imap-failed-tags nil
380 "Alist of tags that failed.
381 Each element is a list with four elements; tag (a integer), response
382 state (a symbol, `OK', `NO' or `BAD'), response code (a string), and
383 human readable response text (a string).")
386 "Command tag number.")
388 (defvar imap-process nil
391 (defvar imap-continuation nil
392 "Non-nil indicates that the server emitted a continuation request.
393 The actually value is really the text on the continuation line.")
395 (defvar imap-callbacks nil
396 "List of response tags and callbacks, on the form `(number . function)'.
397 The function should take two arguments, the first the IMAP tag and the
398 second the status (OK, NO, BAD etc) of the command.")
401 ;; Utility functions:
403 (defun imap-remassoc (key alist)
404 "Delete by side effect any elements of LIST whose car is `equal' to KEY.
405 The modified LIST is returned. If the first member
406 of LIST has a car that is `equal' to KEY, there is no way to remove it
407 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
408 sure of changing the value of `foo'."
410 (if (equal key (caar alist))
412 (setcdr alist (imap-remassoc key (cdr alist)))
415 (defsubst imap-disable-multibyte ()
416 "Enable multibyte in the current buffer."
417 (when (fboundp 'set-buffer-multibyte)
418 (set-buffer-multibyte nil)))
420 (defun imap-read-passwd (prompt &rest args)
421 "Read a password using PROMPT.
422 If ARGS, PROMPT is used as an argument to `format'."
423 (let ((prompt (if args
424 (apply 'format prompt args)
426 (funcall (if (or (fboundp 'read-passwd)
428 (fboundp 'read-passwd))
429 (and (load "passwd" t)
430 (fboundp 'read-passwd)))
432 (autoload 'ange-ftp-read-passwd "ange-ftp")
433 'ange-ftp-read-passwd)
436 (defsubst imap-utf7-encode (string)
440 (utf7-encode string t)
442 "imap: Could not UTF7 encode `%s', using it unencoded..."
447 (defsubst imap-utf7-decode (string)
451 (utf7-decode string t)
453 "imap: Could not UTF7 decode `%s', using it undecoded..."
458 (defsubst imap-ok-p (status)
461 (setq imap-error status)
464 (defun imap-error-text (&optional buffer)
465 (with-current-buffer (or buffer (current-buffer))
466 (nth 3 (car imap-failed-tags))))
469 ;; Server functions; stream stuff:
471 (defun imap-kerberos4-stream-p (buffer)
472 (imap-capability 'AUTH=KERBEROS_V4 buffer))
474 (defun imap-kerberos4-open (name buffer server port)
475 (let ((cmds imap-kerberos4-program)
477 (while (and (not done) (setq cmd (pop cmds)))
478 (message "Opening Kerberos 4 IMAP connection with `%s'..." cmd)
480 (let* ((port (or port imap-default-port))
481 (coding-system-for-read imap-coding-system-for-read)
482 (coding-system-for-write imap-coding-system-for-write)
483 (process-connection-type imap-process-connection-type)
484 (process (start-process
485 name buffer shell-file-name shell-command-switch
490 ?p (number-to-string port)
491 ?l imap-default-user))))
494 (with-current-buffer buffer
495 (setq imap-client-eol "\n"
496 imap-calculate-literal-size-first t)
497 (while (and (memq (process-status process) '(open run))
498 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
499 (goto-char (point-min))
500 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
501 (or (while (looking-at "^C:")
504 ;; cyrus 1.6 imtest print "S: " before server greeting
505 (or (not (looking-at "S: "))
508 (not (and (imap-parse-greeting)
509 ;; success in imtest < 1.6:
510 (or (re-search-forward
511 "^__\\(.*\\)__\n" nil t)
512 ;; success in imtest 1.6:
514 "^\\(Authenticat.*\\)" nil t))
515 (setq response (match-string 1)))))
516 (accept-process-output process 1)
519 (with-current-buffer (get-buffer-create imap-log-buffer)
520 (imap-disable-multibyte)
521 (buffer-disable-undo)
522 (goto-char (point-max))
523 (insert-buffer-substring buffer)))
525 (message "Opening Kerberos 4 IMAP connection with `%s'...%s" cmd
526 (if response (concat "done, " response) "failed"))
527 (if (and response (let ((case-fold-search nil))
528 (not (string-match "failed" response))))
530 (if (memq (process-status process) '(open run))
531 (imap-send-command-wait "LOGOUT"))
532 (delete-process process)
536 (defun imap-gssapi-stream-p (buffer)
537 (imap-capability 'AUTH=GSSAPI buffer))
539 (defun imap-gssapi-open (name buffer server port)
540 (let ((cmds imap-gssapi-program)
542 (while (and (not done) (setq cmd (pop cmds)))
543 (message "Opening GSSAPI IMAP connection with `%s'..." cmd)
544 (let* ((port (or port imap-default-port))
545 (coding-system-for-read imap-coding-system-for-read)
546 (coding-system-for-write imap-coding-system-for-write)
547 (process-connection-type imap-process-connection-type)
548 (process (start-process
549 name buffer shell-file-name shell-command-switch
554 ?p (number-to-string port)
555 ?l imap-default-user))))
558 (with-current-buffer buffer
559 (setq imap-client-eol "\n"
560 imap-calculate-literal-size-first t)
561 (while (and (memq (process-status process) '(open run))
562 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
563 (goto-char (point-min))
564 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
565 (or (while (looking-at "^C:")
568 ;; cyrus 1.6 imtest print "S: " before server greeting
569 (or (not (looking-at "S: "))
572 (not (and (imap-parse-greeting)
573 ;; success in imtest 1.6:
575 "^\\(Authenticat.*\\)" nil t)
576 (setq response (match-string 1)))))
577 (accept-process-output process 1)
580 (with-current-buffer (get-buffer-create imap-log-buffer)
581 (imap-disable-multibyte)
582 (buffer-disable-undo)
583 (goto-char (point-max))
584 (insert-buffer-substring buffer)))
586 (message "GSSAPI IMAP connection: %s" (or response "failed"))
587 (if (and response (let ((case-fold-search nil))
588 (not (string-match "failed" response))))
590 (if (memq (process-status process) '(open run))
591 (imap-send-command-wait "LOGOUT"))
592 (delete-process process)
596 (defun imap-ssl-p (buffer)
599 (defun imap-ssl-open (name buffer server port)
600 "Open a SSL connection to server."
601 (let ((cmds (if (listp imap-ssl-program) imap-ssl-program
602 (list imap-ssl-program)))
607 (while (and (not done) (setq cmd (pop cmds)))
608 (message "imap: Opening SSL connection with `%s'..." cmd)
609 (let* ((port (or port imap-default-ssl-port))
610 (coding-system-for-read imap-coding-system-for-read)
611 (coding-system-for-write imap-coding-system-for-write)
612 (ssl-program-name shell-file-name)
613 (ssl-program-arguments
614 (list shell-command-switch
615 (format-spec cmd (format-spec-make
617 ?p (number-to-string port)))))
619 (when (setq process (condition-case ()
620 (open-ssl-stream name buffer server port)
622 (with-current-buffer buffer
623 (goto-char (point-min))
624 (while (and (memq (process-status process) '(open run))
625 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
626 (goto-char (point-max))
628 (not (imap-parse-greeting)))
629 (accept-process-output process 1)
632 (with-current-buffer (get-buffer-create imap-log-buffer)
633 (imap-disable-multibyte)
634 (buffer-disable-undo)
635 (goto-char (point-max))
636 (insert-buffer-substring buffer)))
638 (when (memq (process-status process) '(open run))
639 (setq done process))))))
642 (message "imap: Opening SSL connection with `%s'...done" cmd)
644 (message "imap: Opening SSL connection with `%s'...failed" cmd)
647 (defun imap-network-p (buffer)
650 (defun imap-network-open (name buffer server port)
651 (let* ((port (or port imap-default-port))
652 (coding-system-for-read imap-coding-system-for-read)
653 (coding-system-for-write imap-coding-system-for-write)
654 (process (open-network-stream name buffer server port)))
656 (while (and (memq (process-status process) '(open run))
657 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
658 (goto-char (point-min))
659 (not (imap-parse-greeting)))
660 (accept-process-output process 1)
663 (with-current-buffer (get-buffer-create imap-log-buffer)
664 (imap-disable-multibyte)
665 (buffer-disable-undo)
666 (goto-char (point-max))
667 (insert-buffer-substring buffer)))
668 (when (memq (process-status process) '(open run))
671 (defun imap-shell-p (buffer)
674 (defun imap-shell-open (name buffer server port)
675 (let ((cmds imap-shell-program)
677 (while (and (not done) (setq cmd (pop cmds)))
678 (message "imap: Opening IMAP connection with `%s'..." cmd)
679 (setq imap-client-eol "\n")
680 (let* ((port (or port imap-default-port))
681 (coding-system-for-read imap-coding-system-for-read)
682 (coding-system-for-write imap-coding-system-for-write)
683 (process (start-process
684 name buffer shell-file-name shell-command-switch
690 ?p (number-to-string port)
691 ?l imap-default-user)))))
693 (while (and (memq (process-status process) '(open run))
694 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
695 (goto-char (point-min))
696 (not (imap-parse-greeting)))
697 (accept-process-output process 1)
700 (with-current-buffer (get-buffer-create imap-log-buffer)
701 (imap-disable-multibyte)
702 (buffer-disable-undo)
703 (goto-char (point-max))
704 (insert-buffer-substring buffer)))
706 (when (memq (process-status process) '(open run))
707 (setq done process)))))
710 (message "imap: Opening IMAP connection with `%s'...done" cmd)
712 (message "imap: Opening IMAP connection with `%s'...failed" cmd)
715 (defun imap-starttls-p (buffer)
716 (imap-capability 'STARTTLS buffer))
718 (defun imap-starttls-open (name buffer server port)
719 (let* ((port (or port imap-default-port))
720 (coding-system-for-read imap-coding-system-for-read)
721 (coding-system-for-write imap-coding-system-for-write)
722 (process (starttls-open-stream name buffer server port))
724 (message "imap: Connecting with STARTTLS...")
726 (while (and (memq (process-status process) '(open run))
727 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
728 (goto-char (point-min))
729 (not (imap-parse-greeting)))
730 (accept-process-output process 1)
733 (with-current-buffer (get-buffer-create imap-log-buffer)
734 (buffer-disable-undo)
735 (goto-char (point-max))
736 (insert-buffer-substring buffer)))
737 (let ((imap-process process))
740 (set-process-filter imap-process 'imap-arrival-filter)
741 (when (and (eq imap-stream 'starttls)
742 (imap-ok-p (imap-send-command-wait "STARTTLS")))
743 (starttls-negotiate imap-process)))
744 (set-process-filter imap-process nil)))
745 (when (memq (process-status process) '(open run))
746 (setq done process)))
749 (message "imap: Connecting with STARTTLS...done")
751 (message "imap: Connecting with STARTTLS...failed")
754 ;; Server functions; authenticator stuff:
756 (defun imap-interactive-login (buffer loginfunc)
757 "Login to server in BUFFER.
758 LOGINFUNC is passed a username and a password, it should return t if
759 it where sucessful authenticating itself to the server, nil otherwise.
760 Returns t if login was successful, nil otherwise."
761 (with-current-buffer buffer
762 (make-local-variable 'imap-username)
763 (make-local-variable 'imap-password)
764 (let (user passwd ret)
765 ;; (condition-case ()
766 (while (or (not user) (not passwd))
767 (setq user (or imap-username
768 (read-from-minibuffer
769 (concat "IMAP username for " imap-server ": ")
770 (or user imap-default-user))))
771 (setq passwd (or imap-password
773 (concat "IMAP password for " user "@"
775 (when (and user passwd)
776 (if (funcall loginfunc user passwd)
780 (if (and (not imap-password)
781 (y-or-n-p "Store password for this session? "))
782 (setq imap-password passwd)))
783 (message "Login failed...")
786 ;; (quit (with-current-buffer buffer
789 ;; (error (with-current-buffer buffer
794 (defun imap-gssapi-auth-p (buffer)
795 (and (imap-capability 'AUTH=GSSAPI buffer)
796 (eq imap-state 'gssapi)))
798 (defun imap-gssapi-auth (buffer)
799 (message "imap: Authenticating using GSSAPI...%s"
800 (if (eq imap-stream 'gssapi) "done" "failed"))
801 (eq imap-stream 'gssapi))
803 (defun imap-kerberos4-auth-p (buffer)
804 (and (imap-capability 'AUTH=KERBEROS_V4 buffer)
805 (eq imap-state 'kerberos4)))
807 (defun imap-kerberos4-auth (buffer)
808 (message "imap: Authenticating using Kerberos 4...%s"
809 (if (eq imap-stream 'kerberos4) "done" "failed"))
810 (eq imap-stream 'kerberos4))
812 (defun imap-cram-md5-p (buffer)
813 (imap-capability 'AUTH=CRAM-MD5 buffer))
815 (defun imap-cram-md5-auth (buffer)
816 "Login to server using the AUTH CRAM-MD5 method."
817 (message "imap: Authenticating using CRAM-MD5...")
818 (let ((done (imap-interactive-login
820 (lambda (user passwd)
822 (imap-send-command-wait
824 "AUTHENTICATE CRAM-MD5"
826 (let* ((decoded (base64-decode-string challenge))
827 (hash (rfc2104-hash 'md5 64 16 passwd decoded))
828 (response (concat user " " hash))
829 (encoded (base64-encode-string response)))
832 (message "imap: Authenticating using CRAM-MD5...done")
833 (message "imap: Authenticating using CRAM-MD5...failed"))))
835 (defun imap-login-p (buffer)
836 (and (not (imap-capability 'LOGINDISABLED buffer))
837 (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
839 (defun imap-login-auth (buffer)
840 "Login to server using the LOGIN command."
841 (message "imap: Plaintext authentication...")
842 (imap-interactive-login buffer
843 (lambda (user passwd)
844 (imap-ok-p (imap-send-command-wait
845 (concat "LOGIN \"" user "\" \""
848 (defun imap-anonymous-p (buffer)
851 (defun imap-anonymous-auth (buffer)
852 (message "imap: Loging in anonymously...")
853 (with-current-buffer buffer
854 (imap-ok-p (imap-send-command-wait
855 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
856 (system-name)) "\"")))))
858 (defun imap-digest-md5-p (buffer)
859 (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
861 (require 'digest-md5)
864 (defun imap-digest-md5-auth (buffer)
865 "Login to server using the AUTH DIGEST-MD5 method."
866 (message "imap: Authenticating using DIGEST-MD5...")
867 (imap-interactive-login
869 (lambda (user passwd)
873 "AUTHENTICATE DIGEST-MD5"
875 (digest-md5-parse-digest-challenge
876 (base64-decode-string challenge))
878 (digest-md5-digest-uri
879 "imap" (digest-md5-challenge 'realm)))
881 (digest-md5-digest-response
882 user passwd digest-uri)))
883 (base64-encode-string response 'no-line-break))))
885 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
887 (setq imap-continuation nil)
888 (imap-send-command-1 "")
889 (imap-ok-p (imap-wait-for-tag tag)))))))
893 (defun imap-open-1 (buffer)
894 (with-current-buffer buffer
896 (setq imap-current-mailbox nil
897 imap-current-message nil
899 imap-process (condition-case ()
900 (funcall (nth 2 (assq imap-stream
902 "imap" buffer imap-server imap-port)
905 (set-process-filter imap-process 'imap-arrival-filter)
906 (set-process-sentinel imap-process 'imap-sentinel)
907 (while (and (eq imap-state 'initial)
908 (memq (process-status imap-process) '(open run)))
909 (message "Waiting for response from %s..." imap-server)
910 (accept-process-output imap-process 1))
911 (message "Waiting for response from %s...done" imap-server)
912 (and (memq (process-status imap-process) '(open run))
915 (defun imap-open (server &optional port stream auth buffer)
916 "Open a IMAP connection to host SERVER at PORT returning a buffer.
917 If PORT is unspecified, a default value is used (143 except
918 for SSL which use 993).
919 STREAM indicates the stream to use, see `imap-streams' for available
920 streams. If nil, it choices the best stream the server is capable of.
921 AUTH indicates authenticator to use, see `imap-authenticators' for
922 available authenticators. If nil, it choices the best stream the
923 server is capable of.
924 BUFFER can be a buffer or a name of a buffer, which is created if
925 necessery. If nil, the buffer name is generated."
926 (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
927 (with-current-buffer (get-buffer-create buffer)
928 (if (imap-opened buffer)
930 (mapcar 'make-local-variable imap-local-variables)
931 (imap-disable-multibyte)
932 (buffer-disable-undo)
933 (setq imap-server (or server imap-server))
934 (setq imap-port (or port imap-port))
935 (setq imap-auth (or auth imap-auth))
936 (setq imap-stream (or stream imap-stream))
937 (message "imap: Connecting to %s..." imap-server)
938 (if (null (let ((imap-stream (or imap-stream imap-default-stream)))
939 (imap-open-1 buffer)))
940 (message "imap: Connecting to %s...failed" imap-server)
941 (when (null imap-stream)
942 ;; Need to choose stream.
943 (let ((streams imap-streams))
944 (while (setq stream (pop streams))
945 ;; OK to use this stream?
946 (when (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
948 (if (not (eq imap-default-stream stream))
950 (message "imap: Reconnecting with stream `%s'..." stream)
951 (if (null (let ((imap-stream stream))
952 (imap-open-1 (current-buffer))))
953 (message "imap: Reconnecting with stream `%s'...failed"
955 ;; We're done, kill the first connection
958 (rename-buffer buffer)
959 (message "imap: Reconnecting with stream `%s'...done"
961 (setq imap-stream stream)
962 (setq imap-capability nil)
965 (message "imap: Connecting to %s...done" imap-server)
966 (setq imap-stream stream)
967 (setq imap-capability nil)
968 (setq streams nil))))))
969 (when (imap-opened buffer)
970 (setq imap-mailbox-data (make-vector imap-mailbox-prime 0)))
973 (defun imap-opened (&optional buffer)
974 "Return non-nil if connection to imap server in BUFFER is open.
975 If BUFFER is nil then the current buffer is used."
976 (and (setq buffer (get-buffer (or buffer (current-buffer))))
977 (buffer-live-p buffer)
978 (with-current-buffer buffer
980 (memq (process-status imap-process) '(open run))))))
982 (defun imap-authenticate (&optional user passwd buffer)
983 "Authenticate to server in BUFFER, using current buffer if nil.
984 It uses the authenticator specified when opening the server. If the
985 authenticator requires username/passwords, they are queried from the
986 user and optionally stored in the buffer. If USER and/or PASSWD is
987 specified, the user will not be questioned and the username and/or
988 password is remembered in the buffer."
989 (with-current-buffer (or buffer (current-buffer))
990 (if (not (eq imap-state 'nonauth))
991 (or (eq imap-state 'auth)
992 (eq imap-state 'select)
993 (eq imap-state 'examine))
994 (make-local-variable 'imap-username)
995 (make-local-variable 'imap-password)
996 (if user (setq imap-username user))
997 (if passwd (setq imap-password passwd))
999 (and (funcall (nth 2 (assq imap-auth
1000 imap-authenticator-alist)) buffer)
1001 (setq imap-state 'auth))
1002 ;; Choose authenticator.
1004 (auths imap-authenticators))
1005 (while (setq auth (pop auths))
1006 ;; OK to use authenticator?
1007 (when (funcall (nth 1 (assq auth imap-authenticator-alist)) buffer)
1008 (message "imap: Authenticating to `%s' using `%s'..."
1010 (if (funcall (nth 2 (assq auth imap-authenticator-alist)) buffer)
1012 (message "imap: Authenticating to `%s' using `%s'...done"
1014 (setq imap-auth auth
1016 (message "imap: Authenticating to `%s' using `%s'...failed"
1017 imap-server auth)))))
1020 (defun imap-close (&optional buffer)
1021 "Close connection to server in BUFFER.
1022 If BUFFER is nil, the current buffer is used."
1023 (with-current-buffer (or buffer (current-buffer))
1026 (imap-send-command-wait "LOGOUT")
1028 (when (and imap-process
1029 (memq (process-status imap-process) '(open run)))
1030 (delete-process imap-process))
1031 (setq imap-current-mailbox nil
1032 imap-current-message nil
1037 (defun imap-capability (&optional identifier buffer)
1038 "Return a list of identifiers which server in BUFFER support.
1039 If IDENTIFIER, return non-nil if it's among the servers capabilities.
1040 If BUFFER is nil, the current buffer is assumed."
1041 (with-current-buffer (or buffer (current-buffer))
1042 (unless imap-capability
1043 (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
1044 (setq imap-capability '(IMAP2))))
1046 (memq (intern (upcase (symbol-name identifier))) imap-capability)
1049 (defun imap-namespace (&optional buffer)
1050 "Return a namespace hierarchy at server in BUFFER.
1051 If BUFFER is nil, the current buffer is assumed."
1052 (with-current-buffer (or buffer (current-buffer))
1053 (unless imap-namespace
1054 (when (imap-capability 'NAMESPACE)
1055 (imap-send-command-wait "NAMESPACE")))
1058 (defun imap-send-command-wait (command &optional buffer)
1059 (imap-wait-for-tag (imap-send-command command buffer) buffer))
1062 ;; Mailbox functions:
1064 (defun imap-mailbox-put (propname value &optional mailbox buffer)
1065 (with-current-buffer (or buffer (current-buffer))
1066 (if imap-mailbox-data
1067 (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
1069 (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
1070 propname value mailbox (current-buffer)))
1073 (defsubst imap-mailbox-get-1 (propname &optional mailbox)
1074 (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
1077 (defun imap-mailbox-get (propname &optional mailbox buffer)
1078 (let ((mailbox (imap-utf7-encode mailbox)))
1079 (with-current-buffer (or buffer (current-buffer))
1080 (imap-mailbox-get-1 propname (or mailbox imap-current-mailbox)))))
1082 (defun imap-mailbox-map-1 (func &optional mailbox-decoder buffer)
1083 (with-current-buffer (or buffer (current-buffer))
1087 (push (funcall func (if mailbox-decoder
1088 (funcall mailbox-decoder (symbol-name s))
1089 (symbol-name s))) result))
1093 (defun imap-mailbox-map (func &optional buffer)
1094 "Map a function across each mailbox in `imap-mailbox-data', returning a list.
1095 Function should take a mailbox name (a string) as
1097 (imap-mailbox-map-1 func 'imap-utf7-decode buffer))
1099 (defun imap-current-mailbox (&optional buffer)
1100 (with-current-buffer (or buffer (current-buffer))
1101 (imap-utf7-decode imap-current-mailbox)))
1103 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
1104 (and (string= mailbox imap-current-mailbox)
1106 (eq imap-state 'examine))
1108 (eq imap-state 'selected)))))
1110 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
1111 (with-current-buffer (or buffer (current-buffer))
1112 (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
1114 (defun imap-mailbox-select-1 (mailbox &optional examine)
1115 "Select MAILBOX on server in BUFFER.
1116 If EXAMINE is non-nil, do a read-only select."
1117 (if (imap-current-mailbox-p-1 mailbox examine)
1118 imap-current-mailbox
1119 (setq imap-current-mailbox mailbox)
1120 (if (imap-ok-p (imap-send-command-wait
1121 (concat (if examine "EXAMINE" "SELECT") " \""
1124 (setq imap-message-data (make-vector imap-message-prime 0)
1125 imap-state (if examine 'examine 'selected))
1126 imap-current-mailbox)
1127 ;; Failed SELECT/EXAMINE unselects current mailbox
1128 (setq imap-current-mailbox nil))))
1130 (defun imap-mailbox-select (mailbox &optional examine buffer)
1131 (with-current-buffer (or buffer (current-buffer))
1133 (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
1135 (defun imap-mailbox-examine-1 (mailbox &optional buffer)
1136 (with-current-buffer (or buffer (current-buffer))
1137 (imap-mailbox-select-1 mailbox 'examine)))
1139 (defun imap-mailbox-examine (mailbox &optional buffer)
1140 "Examine MAILBOX on server in BUFFER."
1141 (imap-mailbox-select mailbox 'examine buffer))
1143 (defun imap-mailbox-unselect (&optional buffer)
1144 "Close current folder in BUFFER, without expunging articles."
1145 (with-current-buffer (or buffer (current-buffer))
1146 (when (or (eq imap-state 'auth)
1147 (and (imap-capability 'UNSELECT)
1148 (imap-ok-p (imap-send-command-wait "UNSELECT")))
1150 (imap-send-command-wait (concat "EXAMINE \""
1151 imap-current-mailbox
1153 (imap-ok-p (imap-send-command-wait "CLOSE"))))
1154 (setq imap-current-mailbox nil
1155 imap-message-data nil
1159 (defun imap-mailbox-expunge (&optional asynch buffer)
1160 "Expunge articles in current folder in BUFFER.
1161 If ASYNCH, do not wait for succesful completion of the command.
1162 If BUFFER is nil the current buffer is assumed."
1163 (with-current-buffer (or buffer (current-buffer))
1164 (when (and imap-current-mailbox (not (eq imap-state 'examine)))
1166 (imap-send-command "EXPUNGE")
1167 (imap-ok-p (imap-send-command-wait "EXPUNGE"))))))
1169 (defun imap-mailbox-close (&optional asynch buffer)
1170 "Expunge articles and close current folder in BUFFER.
1171 If ASYNCH, do not wait for succesful completion of the command.
1172 If BUFFER is nil the current buffer is assumed."
1173 (with-current-buffer (or buffer (current-buffer))
1174 (when imap-current-mailbox
1176 (imap-add-callback (imap-send-command "CLOSE")
1177 `(lambda (tag status)
1178 (message "IMAP mailbox `%s' closed... %s"
1179 imap-current-mailbox status)
1180 (when (eq ,imap-current-mailbox
1181 imap-current-mailbox)
1182 ;; Don't wipe out data if another mailbox
1184 (setq imap-current-mailbox nil
1185 imap-message-data nil
1186 imap-state 'auth))))
1187 (when (imap-ok-p (imap-send-command-wait "CLOSE"))
1188 (setq imap-current-mailbox nil
1189 imap-message-data nil
1193 (defun imap-mailbox-create-1 (mailbox)
1194 (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
1196 (defun imap-mailbox-create (mailbox &optional buffer)
1197 "Create MAILBOX on server in BUFFER.
1198 If BUFFER is nil the current buffer is assumed."
1199 (with-current-buffer (or buffer (current-buffer))
1200 (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
1202 (defun imap-mailbox-delete (mailbox &optional buffer)
1203 "Delete MAILBOX on server in BUFFER.
1204 If BUFFER is nil the current buffer is assumed."
1205 (let ((mailbox (imap-utf7-encode mailbox)))
1206 (with-current-buffer (or buffer (current-buffer))
1208 (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1210 (defun imap-mailbox-rename (oldname newname &optional buffer)
1211 "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1212 If BUFFER is nil the current buffer is assumed."
1213 (let ((oldname (imap-utf7-encode oldname))
1214 (newname (imap-utf7-encode newname)))
1215 (with-current-buffer (or buffer (current-buffer))
1217 (imap-send-command-wait (list "RENAME \"" oldname "\" "
1218 "\"" newname "\""))))))
1220 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1221 "Return a list of subscribed mailboxes on server in BUFFER.
1222 If ROOT is non-nil, only list matching mailboxes. If ADD-DELIMITER is
1223 non-nil, a hierarchy delimiter is added to root. REFERENCE is a
1224 implementation-specific string that has to be passed to lsub command."
1225 (with-current-buffer (or buffer (current-buffer))
1226 ;; Make sure we know the hierarchy separator for root's hierarchy
1227 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1228 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1229 (imap-utf7-encode root) "\"")))
1230 ;; clear list data (NB not delimiter and other stuff)
1231 (imap-mailbox-map-1 (lambda (mailbox)
1232 (imap-mailbox-put 'lsub nil mailbox)))
1234 (imap-send-command-wait
1235 (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1236 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1239 (imap-mailbox-map-1 (lambda (mailbox)
1240 (when (imap-mailbox-get-1 'lsub mailbox)
1241 (push (imap-utf7-decode mailbox) out))))
1244 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1245 "Return a list of mailboxes matching ROOT on server in BUFFER.
1246 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1247 root. REFERENCE is a implementation-specific string that has to be
1248 passed to list command."
1249 (with-current-buffer (or buffer (current-buffer))
1250 ;; Make sure we know the hierarchy separator for root's hierarchy
1251 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1252 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1253 (imap-utf7-encode root) "\"")))
1254 ;; clear list data (NB not delimiter and other stuff)
1255 (imap-mailbox-map-1 (lambda (mailbox)
1256 (imap-mailbox-put 'list nil mailbox)))
1258 (imap-send-command-wait
1259 (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1260 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1263 (imap-mailbox-map-1 (lambda (mailbox)
1264 (when (imap-mailbox-get-1 'list mailbox)
1265 (push (imap-utf7-decode mailbox) out))))
1268 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1269 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1270 Returns non-nil if successful."
1271 (with-current-buffer (or buffer (current-buffer))
1272 (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1273 (imap-utf7-encode mailbox)
1276 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1277 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1278 Returns non-nil if successful."
1279 (with-current-buffer (or buffer (current-buffer))
1280 (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1281 (imap-utf7-encode mailbox)
1284 (defun imap-mailbox-status (mailbox items &optional buffer)
1285 "Get status items ITEM in MAILBOX from server in BUFFER.
1286 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1287 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1288 or 'unseen. If ITEMS is a list of symbols, a list of values is
1289 returned, if ITEMS is a symbol only it's value is returned."
1290 (with-current-buffer (or buffer (current-buffer))
1292 (imap-send-command-wait (list "STATUS \""
1293 (imap-utf7-encode mailbox)
1300 (mapcar (lambda (item)
1301 (imap-mailbox-get item mailbox))
1303 (imap-mailbox-get items mailbox)))))
1305 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1306 "Get ACL on mailbox from server in BUFFER."
1307 (let ((mailbox (imap-utf7-encode mailbox)))
1308 (with-current-buffer (or buffer (current-buffer))
1310 (imap-send-command-wait (list "GETACL \""
1311 (or mailbox imap-current-mailbox)
1313 (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1315 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1316 "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
1317 (let ((mailbox (imap-utf7-encode mailbox)))
1318 (with-current-buffer (or buffer (current-buffer))
1320 (imap-send-command-wait (list "SETACL \""
1321 (or mailbox imap-current-mailbox)
1327 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1328 "Removes any <identifier,rights> pair for IDENTIFIER in MAILBOX from server in BUFFER."
1329 (let ((mailbox (imap-utf7-encode mailbox)))
1330 (with-current-buffer (or buffer (current-buffer))
1332 (imap-send-command-wait (list "DELETEACL \""
1333 (or mailbox imap-current-mailbox)
1338 ;; Message functions:
1340 (defun imap-current-message (&optional buffer)
1341 (with-current-buffer (or buffer (current-buffer))
1342 imap-current-message))
1344 (defun imap-list-to-message-set (list)
1345 (mapconcat (lambda (item)
1346 (number-to-string item))
1352 (defun imap-range-to-message-set (range)
1357 (car item) (cdr item))
1358 (format "%d" item)))
1359 (if (and (listp range) (not (listp (cdr range))))
1360 (list range) ;; make (1 . 2) into ((1 . 2))
1364 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1365 (with-current-buffer (or buffer (current-buffer))
1366 (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1368 (imap-list-to-message-set uids)
1372 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1373 "Fetch properties PROPS from message set UIDS from server in BUFFER.
1374 UIDS can be a string, number or a list of numbers. If RECEIVE
1375 is non-nil return theese properties."
1376 (with-current-buffer (or buffer (current-buffer))
1377 (when (imap-ok-p (imap-send-command-wait
1378 (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1380 (imap-list-to-message-set uids)
1383 (if (or (null receive) (stringp uids))
1386 (mapcar (lambda (uid)
1388 (mapcar (lambda (prop)
1389 (imap-message-get uid prop))
1391 (imap-message-get uid receive)))
1393 (imap-message-get uids receive))))))
1395 (defun imap-message-put (uid propname value &optional buffer)
1396 (with-current-buffer (or buffer (current-buffer))
1397 (if imap-message-data
1398 (put (intern (number-to-string uid) imap-message-data)
1400 (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1401 uid propname value (current-buffer)))
1404 (defun imap-message-get (uid propname &optional buffer)
1405 (with-current-buffer (or buffer (current-buffer))
1406 (get (intern-soft (number-to-string uid) imap-message-data)
1409 (defun imap-message-map (func propname &optional buffer)
1410 "Map a function across each mailbox in `imap-message-data', returning a list."
1411 (with-current-buffer (or buffer (current-buffer))
1415 (push (funcall func (get s 'UID) (get s propname)) result))
1419 (defmacro imap-message-envelope-date (uid &optional buffer)
1420 `(with-current-buffer (or ,buffer (current-buffer))
1421 (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1423 (defmacro imap-message-envelope-subject (uid &optional buffer)
1424 `(with-current-buffer (or ,buffer (current-buffer))
1425 (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1427 (defmacro imap-message-envelope-from (uid &optional buffer)
1428 `(with-current-buffer (or ,buffer (current-buffer))
1429 (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1431 (defmacro imap-message-envelope-sender (uid &optional buffer)
1432 `(with-current-buffer (or ,buffer (current-buffer))
1433 (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1435 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1436 `(with-current-buffer (or ,buffer (current-buffer))
1437 (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1439 (defmacro imap-message-envelope-to (uid &optional buffer)
1440 `(with-current-buffer (or ,buffer (current-buffer))
1441 (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1443 (defmacro imap-message-envelope-cc (uid &optional buffer)
1444 `(with-current-buffer (or ,buffer (current-buffer))
1445 (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1447 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1448 `(with-current-buffer (or ,buffer (current-buffer))
1449 (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1451 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1452 `(with-current-buffer (or ,buffer (current-buffer))
1453 (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1455 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1456 `(with-current-buffer (or ,buffer (current-buffer))
1457 (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1459 (defmacro imap-message-body (uid &optional buffer)
1460 `(with-current-buffer (or ,buffer (current-buffer))
1461 (imap-message-get ,uid 'BODY)))
1463 (defun imap-search (predicate &optional buffer)
1464 (with-current-buffer (or buffer (current-buffer))
1465 (imap-mailbox-put 'search 'dummy)
1466 (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1467 (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1469 (message "Missing SEARCH response to a SEARCH command (server not RFC compliant)...")
1471 (imap-mailbox-get-1 'search imap-current-mailbox)))))
1473 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1474 "Return t iff FLAG can be permanently (between IMAP sessions) saved on articles, in MAILBOX on server in BUFFER."
1475 (with-current-buffer (or buffer (current-buffer))
1476 (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1477 (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1479 (defun imap-message-flags-set (articles flags &optional silent buffer)
1480 (when (and articles flags)
1481 (with-current-buffer (or buffer (current-buffer))
1482 (imap-ok-p (imap-send-command-wait
1483 (concat "UID STORE " articles
1484 " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1486 (defun imap-message-flags-del (articles flags &optional silent buffer)
1487 (when (and articles flags)
1488 (with-current-buffer (or buffer (current-buffer))
1489 (imap-ok-p (imap-send-command-wait
1490 (concat "UID STORE " articles
1491 " -FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1493 (defun imap-message-flags-add (articles flags &optional silent buffer)
1494 (when (and articles flags)
1495 (with-current-buffer (or buffer (current-buffer))
1496 (imap-ok-p (imap-send-command-wait
1497 (concat "UID STORE " articles
1498 " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1500 (defun imap-message-copyuid-1 (mailbox)
1501 (if (imap-capability 'UIDPLUS)
1502 (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1503 (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1504 (let ((old-mailbox imap-current-mailbox)
1506 (imap-message-data (make-vector 2 0)))
1507 (when (imap-mailbox-examine-1 mailbox)
1509 (and (imap-fetch "*" "UID")
1510 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1511 (apply 'max (imap-message-map
1512 (lambda (uid prop) uid) 'UID))))
1514 (imap-mailbox-select old-mailbox (eq state 'examine))
1515 (imap-mailbox-unselect)))))))
1517 (defun imap-message-copyuid (mailbox &optional buffer)
1518 (with-current-buffer (or buffer (current-buffer))
1519 (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1521 (defun imap-message-copy (articles mailbox
1522 &optional dont-create no-copyuid buffer)
1523 "Copy ARTICLES (a string message set) to MAILBOX on server in
1524 BUFFER, creating mailbox if it doesn't exist. If dont-create is
1525 non-nil, it will not create a mailbox. On success, return a list with
1526 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1527 first element, rest of list contain the saved articles' UIDs."
1529 (with-current-buffer (or buffer (current-buffer))
1530 (let ((mailbox (imap-utf7-encode mailbox)))
1531 (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1532 (imap-current-target-mailbox mailbox))
1533 (if (imap-ok-p (imap-send-command-wait cmd))
1535 (when (and (not dont-create)
1536 ;; removed because of buggy Oracle server
1537 ;; that doesn't send TRYCREATE tags (which
1538 ;; is a MUST according to specifications):
1539 ;;(imap-mailbox-get-1 'trycreate mailbox)
1540 (imap-mailbox-create-1 mailbox))
1541 (imap-ok-p (imap-send-command-wait cmd)))))
1543 (imap-message-copyuid-1 mailbox)))))))
1545 (defun imap-message-appenduid-1 (mailbox)
1546 (if (imap-capability 'UIDPLUS)
1547 (imap-mailbox-get-1 'appenduid mailbox)
1548 (let ((old-mailbox imap-current-mailbox)
1550 (imap-message-data (make-vector 2 0)))
1551 (when (imap-mailbox-examine-1 mailbox)
1553 (and (imap-fetch "*" "UID")
1554 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1555 (apply 'max (imap-message-map
1556 (lambda (uid prop) uid) 'UID))))
1558 (imap-mailbox-select old-mailbox (eq state 'examine))
1559 (imap-mailbox-unselect)))))))
1561 (defun imap-message-appenduid (mailbox &optional buffer)
1562 (with-current-buffer (or buffer (current-buffer))
1563 (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1565 (defun imap-message-append (mailbox article &optional flags date-time buffer)
1566 "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1567 FLAGS and DATE-TIME is currently not used. Return a cons holding
1568 uidvalidity of MAILBOX and UID the newly created article got, or nil
1570 (let ((mailbox (imap-utf7-encode mailbox)))
1571 (with-current-buffer (or buffer (current-buffer))
1572 (and (let ((imap-current-target-mailbox mailbox))
1574 (imap-send-command-wait
1575 (list "APPEND \"" mailbox "\" " article))))
1576 (imap-message-appenduid-1 mailbox)))))
1578 (defun imap-body-lines (body)
1579 "Return number of lines in article by looking at the mime bodystructure BODY."
1581 (if (stringp (car body))
1582 (cond ((and (string= (upcase (car body)) "TEXT")
1583 (numberp (nth 7 body)))
1585 ((and (string= (upcase (car body)) "MESSAGE")
1586 (numberp (nth 9 body)))
1589 (apply '+ (mapcar 'imap-body-lines body)))
1592 (defun imap-envelope-from (from)
1593 "Return a from string line."
1595 (concat (aref from 0)
1596 (if (aref from 0) " <")
1600 (if (aref from 0) ">"))))
1603 ;; Internal functions.
1605 (defun imap-add-callback (tag func)
1606 (setq imap-callbacks (append (list (cons tag func)) imap-callbacks)))
1608 (defun imap-send-command-1 (cmdstr)
1609 (setq cmdstr (concat cmdstr imap-client-eol))
1611 (with-current-buffer (get-buffer-create imap-log-buffer)
1612 (imap-disable-multibyte)
1613 (buffer-disable-undo)
1614 (goto-char (point-max))
1616 (process-send-string imap-process cmdstr))
1618 (defun imap-send-command (command &optional buffer)
1619 (with-current-buffer (or buffer (current-buffer))
1620 (if (not (listp command)) (setq command (list command)))
1621 (let ((tag (setq imap-tag (1+ imap-tag)))
1623 (setq cmdstr (concat (number-to-string imap-tag) " "))
1624 (while (setq cmd (pop command))
1625 (cond ((stringp cmd)
1626 (setq cmdstr (concat cmdstr cmd)))
1628 (let ((eol imap-client-eol)
1629 (calcfirst imap-calculate-literal-size-first)
1631 (with-current-buffer cmd
1633 (setq size (buffer-size)))
1634 (when (not (equal eol "\r\n"))
1635 ;; XXX modifies buffer!
1636 (goto-char (point-min))
1637 (while (search-forward "\r\n" nil t)
1638 (replace-match eol)))
1640 (setq size (buffer-size))))
1642 (concat cmdstr (format "{%d}" size))))
1645 (imap-send-command-1 cmdstr)
1647 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1648 (setq command nil) ;; abort command if no cont-req
1649 (let ((process imap-process)
1650 (stream imap-stream)
1651 (eol imap-client-eol))
1652 (with-current-buffer cmd
1654 (with-current-buffer (get-buffer-create
1656 (imap-disable-multibyte)
1657 (buffer-disable-undo)
1658 (goto-char (point-max))
1659 (insert-buffer-substring cmd)))
1660 (process-send-region process (point-min)
1662 (process-send-string process imap-client-eol))))
1663 (setq imap-continuation nil)))
1665 (imap-send-command-1 cmdstr)
1668 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1669 (setq command nil) ;; abort command if no cont-req
1670 (setq command (cons (funcall cmd imap-continuation)
1672 (setq imap-continuation nil)))
1674 (error "Unknown command type"))))
1676 (imap-send-command-1 cmdstr))
1679 (defun imap-wait-for-tag (tag &optional buffer)
1680 (with-current-buffer (or buffer (current-buffer))
1681 (let (imap-have-messaged)
1682 (while (and (null imap-continuation)
1683 (memq (process-status imap-process) '(open run))
1684 (< imap-reached-tag tag))
1685 (let ((len (/ (point-max) 1024))
1688 (setq imap-have-messaged t)
1689 (message "imap read: %dk" len))
1690 (accept-process-output imap-process 1)))
1691 (when imap-have-messaged
1693 (and (memq (process-status imap-process) '(open run))
1694 (or (assq tag imap-failed-tags)
1695 (if imap-continuation
1699 (defun imap-sentinel (process string)
1700 (delete-process process))
1702 (defun imap-find-next-line ()
1703 "Return point at end of current line, taking into account literals.
1704 Return nil if no complete line has arrived."
1705 (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
1708 (if (match-string 1)
1709 (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1711 (goto-char (+ (point) (string-to-number (match-string 1))))
1712 (imap-find-next-line))
1715 (defun imap-arrival-filter (proc string)
1716 "IMAP process filter."
1717 (with-current-buffer (process-buffer proc)
1718 (goto-char (point-max))
1721 (with-current-buffer (get-buffer-create imap-log-buffer)
1722 (imap-disable-multibyte)
1723 (buffer-disable-undo)
1724 (goto-char (point-max))
1727 (goto-char (point-min))
1728 (while (setq end (imap-find-next-line))
1730 (narrow-to-region (point-min) end)
1731 (delete-backward-char (length imap-server-eol))
1732 (goto-char (point-min))
1734 (cond ((eq imap-state 'initial)
1735 (imap-parse-greeting))
1736 ((or (eq imap-state 'auth)
1737 (eq imap-state 'nonauth)
1738 (eq imap-state 'selected)
1739 (eq imap-state 'examine))
1740 (imap-parse-response))
1742 (message "Unknown state %s in arrival filter"
1744 (delete-region (point-min) (point-max))))))))
1749 (defsubst imap-forward ()
1750 (or (eobp) (forward-char)))
1753 ;; ; Unsigned 32-bit integer
1754 ;; ; (0 <= n < 4,294,967,296)
1756 (defsubst imap-parse-number ()
1757 (when (looking-at "[0-9]+")
1759 (string-to-number (match-string 0))
1760 (goto-char (match-end 0)))))
1762 ;; literal = "{" number "}" CRLF *CHAR8
1763 ;; ; Number represents the number of CHAR8s
1765 (defsubst imap-parse-literal ()
1766 (when (looking-at "{\\([0-9]+\\)}\r\n")
1767 (let ((pos (match-end 0))
1768 (len (string-to-number (match-string 1))))
1769 (if (< (point-max) (+ pos len))
1771 (goto-char (+ pos len))
1772 (buffer-substring pos (+ pos len))))))
1774 ;; string = quoted / literal
1776 ;; quoted = DQUOTE *QUOTED-CHAR DQUOTE
1778 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
1779 ;; "\" quoted-specials
1781 ;; quoted-specials = DQUOTE / "\"
1783 ;; TEXT-CHAR = <any CHAR except CR and LF>
1785 (defsubst imap-parse-string ()
1786 (cond ((eq (char-after) ?\")
1788 (let ((p (point)) (name ""))
1789 (skip-chars-forward "^\"\\\\")
1790 (setq name (buffer-substring p (point)))
1791 (while (eq (char-after) ?\\)
1792 (setq p (1+ (point)))
1794 (skip-chars-forward "^\"\\\\")
1795 (setq name (concat name (buffer-substring p (point)))))
1798 ((eq (char-after) ?{)
1799 (imap-parse-literal))))
1803 (defsubst imap-parse-nil ()
1804 (if (looking-at "NIL")
1805 (goto-char (match-end 0))))
1807 ;; nstring = string / nil
1809 (defsubst imap-parse-nstring ()
1810 (or (imap-parse-string)
1811 (and (imap-parse-nil)
1814 ;; astring = atom / string
1816 ;; atom = 1*ATOM-CHAR
1818 ;; ATOM-CHAR = <any CHAR except atom-specials>
1820 ;; atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards /
1823 ;; list-wildcards = "%" / "*"
1825 ;; quoted-specials = DQUOTE / "\"
1827 (defsubst imap-parse-astring ()
1828 (or (imap-parse-string)
1829 (buffer-substring (point)
1830 (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
1831 (goto-char (1- (match-end 0)))
1835 ;; address = "(" addr-name SP addr-adl SP addr-mailbox SP
1838 ;; addr-adl = nstring
1839 ;; ; Holds route from [RFC-822] route-addr if
1842 ;; addr-host = nstring
1843 ;; ; nil indicates [RFC-822] group syntax.
1844 ;; ; Otherwise, holds [RFC-822] domain name
1846 ;; addr-mailbox = nstring
1847 ;; ; nil indicates end of [RFC-822] group; if
1848 ;; ; non-nil and addr-host is nil, holds
1849 ;; ; [RFC-822] group name.
1850 ;; ; Otherwise, holds [RFC-822] local-part
1851 ;; ; after removing [RFC-822] quoting
1853 ;; addr-name = nstring
1854 ;; ; If non-nil, holds phrase from [RFC-822]
1855 ;; ; mailbox after removing [RFC-822] quoting
1858 (defsubst imap-parse-address ()
1860 (when (eq (char-after) ?\()
1862 (setq address (vector (prog1 (imap-parse-nstring)
1864 (prog1 (imap-parse-nstring)
1866 (prog1 (imap-parse-nstring)
1868 (imap-parse-nstring)))
1869 (when (eq (char-after) ?\))
1873 ;; address-list = "(" 1*address ")" / nil
1877 (defsubst imap-parse-address-list ()
1878 (if (eq (char-after) ?\()
1879 (let (address addresses)
1881 (while (and (not (eq (char-after) ?\)))
1882 ;; next line for MS Exchange bug
1883 (progn (and (eq (char-after) ? ) (imap-forward)) t)
1884 (setq address (imap-parse-address)))
1885 (setq addresses (cons address addresses)))
1886 (when (eq (char-after) ?\))
1888 (nreverse addresses)))
1889 (assert (imap-parse-nil) t "In imap-parse-address-list")))
1891 ;; mailbox = "INBOX" / astring
1892 ;; ; INBOX is case-insensitive. All case variants of
1893 ;; ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
1894 ;; ; not as an astring. An astring which consists of
1895 ;; ; the case-insensitive sequence "I" "N" "B" "O" "X"
1896 ;; ; is considered to be INBOX and not an astring.
1897 ;; ; Refer to section 5.1 for further
1898 ;; ; semantic details of mailbox names.
1900 (defsubst imap-parse-mailbox ()
1901 (let ((mailbox (imap-parse-astring)))
1902 (if (string-equal "INBOX" (upcase mailbox))
1906 ;; greeting = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
1908 ;; resp-cond-auth = ("OK" / "PREAUTH") SP resp-text
1909 ;; ; Authentication condition
1911 ;; resp-cond-bye = "BYE" SP resp-text
1913 (defun imap-parse-greeting ()
1914 "Parse a IMAP greeting."
1915 (cond ((looking-at "\\* OK ")
1916 (setq imap-state 'nonauth))
1917 ((looking-at "\\* PREAUTH ")
1918 (setq imap-state 'auth))
1919 ((looking-at "\\* BYE ")
1920 (setq imap-state 'closed))))
1922 ;; response = *(continue-req / response-data) response-done
1924 ;; continue-req = "+" SP (resp-text / base64) CRLF
1926 ;; response-data = "*" SP (resp-cond-state / resp-cond-bye /
1927 ;; mailbox-data / message-data / capability-data) CRLF
1929 ;; response-done = response-tagged / response-fatal
1931 ;; response-fatal = "*" SP resp-cond-bye CRLF
1932 ;; ; Server closes connection immediately
1934 ;; response-tagged = tag SP resp-cond-state CRLF
1936 ;; resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
1937 ;; ; Status condition
1939 ;; resp-cond-bye = "BYE" SP resp-text
1941 ;; mailbox-data = "FLAGS" SP flag-list /
1942 ;; "LIST" SP mailbox-list /
1943 ;; "LSUB" SP mailbox-list /
1944 ;; "SEARCH" *(SP nz-number) /
1945 ;; "STATUS" SP mailbox SP "("
1946 ;; [status-att SP number *(SP status-att SP number)] ")" /
1947 ;; number SP "EXISTS" /
1948 ;; number SP "RECENT"
1950 ;; message-data = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
1952 ;; capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
1954 ;; ; IMAP4rev1 servers which offer RFC 1730
1955 ;; ; compatibility MUST list "IMAP4" as the first
1958 (defun imap-parse-response ()
1959 "Parse a IMAP command response."
1961 (case (setq token (read (current-buffer)))
1962 (+ (setq imap-continuation
1963 (or (buffer-substring (min (point-max) (1+ (point)))
1966 (* (case (prog1 (setq token (read (current-buffer)))
1968 (OK (imap-parse-resp-text))
1969 (NO (imap-parse-resp-text))
1970 (BAD (imap-parse-resp-text))
1971 (BYE (imap-parse-resp-text))
1972 (FLAGS (imap-mailbox-put 'flags (imap-parse-flag-list)))
1973 (LIST (imap-parse-data-list 'list))
1974 (LSUB (imap-parse-data-list 'lsub))
1975 (SEARCH (imap-mailbox-put
1977 (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
1978 (STATUS (imap-parse-status))
1979 (CAPABILITY (setq imap-capability
1980 (read (concat "(" (upcase (buffer-substring
1981 (point) (point-max)))
1983 (ACL (imap-parse-acl))
1984 (t (case (prog1 (read (current-buffer))
1986 (EXISTS (imap-mailbox-put 'exists token))
1987 (RECENT (imap-mailbox-put 'recent token))
1989 (FETCH (imap-parse-fetch token))
1990 (t (message "Garbage: %s" (buffer-string)))))))
1992 (if (not (integerp token))
1993 (message "Garbage: %s" (buffer-string))
1994 (case (prog1 (setq status (read (current-buffer)))
1997 (setq imap-reached-tag (max imap-reached-tag token))
1998 (imap-parse-resp-text)))
2000 (setq imap-reached-tag (max imap-reached-tag token))
2002 (imap-parse-resp-text))
2004 (when (eq (char-after) ?\[)
2005 (setq code (buffer-substring (point)
2006 (search-forward "]")))
2008 (setq text (buffer-substring (point) (point-max)))
2009 (push (list token status code text)
2010 imap-failed-tags))))
2012 (setq imap-reached-tag (max imap-reached-tag token))
2014 (imap-parse-resp-text))
2016 (when (eq (char-after) ?\[)
2017 (setq code (buffer-substring (point)
2018 (search-forward "]")))
2020 (setq text (buffer-substring (point) (point-max)))
2021 (push (list token status code text) imap-failed-tags)
2022 (error "Internal error, tag %s status %s code %s text %s"
2023 token status code text))))
2024 (t (message "Garbage: %s" (buffer-string))))
2025 (when (assq token imap-callbacks)
2026 (funcall (cdr (assq token imap-callbacks)) token status)
2027 (setq imap-callbacks
2028 (imap-remassoc token imap-callbacks)))))))))
2030 ;; resp-text = ["[" resp-text-code "]" SP] text
2032 ;; text = 1*TEXT-CHAR
2034 ;; TEXT-CHAR = <any CHAR except CR and LF>
2036 (defun imap-parse-resp-text ()
2037 (imap-parse-resp-text-code))
2039 ;; resp-text-code = "ALERT" /
2040 ;; "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
2041 ;; "NEWNAME" SP string SP string /
2043 ;; "PERMANENTFLAGS" SP "("
2044 ;; [flag-perm *(SP flag-perm)] ")" /
2048 ;; "UIDNEXT" SP nz-number /
2049 ;; "UIDVALIDITY" SP nz-number /
2050 ;; "UNSEEN" SP nz-number /
2051 ;; resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
2053 ;; resp_code_apnd = "APPENDUID" SPACE nz_number SPACE uniqueid
2055 ;; resp_code_copy = "COPYUID" SPACE nz_number SPACE set SPACE set
2057 ;; set = sequence-num / (sequence-num ":" sequence-num) /
2059 ;; ; Identifies a set of messages. For message
2060 ;; ; sequence numbers, these are consecutive
2061 ;; ; numbers from 1 to the number of messages in
2063 ;; ; Comma delimits individual numbers, colon
2064 ;; ; delimits between two numbers inclusive.
2065 ;; ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
2066 ;; ; 14,15 for a mailbox with 15 messages.
2068 ;; sequence-num = nz-number / "*"
2069 ;; ; * is the largest number in use. For message
2070 ;; ; sequence numbers, it is the number of messages
2071 ;; ; in the mailbox. For unique identifiers, it is
2072 ;; ; the unique identifier of the last message in
2075 ;; flag-perm = flag / "\*"
2077 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2078 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2079 ;; ; Does not include "\Recent"
2081 ;; flag-extension = "\" atom
2082 ;; ; Future expansion. Client implementations
2083 ;; ; MUST accept flag-extension flags. Server
2084 ;; ; implementations MUST NOT generate
2085 ;; ; flag-extension flags except as defined by
2086 ;; ; future standard or standards-track
2087 ;; ; revisions of this specification.
2089 ;; flag-keyword = atom
2091 ;; resp-text-atom = 1*<any ATOM-CHAR except "]">
2093 (defun imap-parse-resp-text-code ()
2094 ;; xxx next line for stalker communigate pro 3.3.1 bug
2095 (when (looking-at " \\[")
2097 (when (eq (char-after) ?\[)
2099 (cond ((search-forward "PERMANENTFLAGS " nil t)
2100 (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2101 ((search-forward "UIDNEXT " nil t)
2102 (imap-mailbox-put 'uidnext (read (current-buffer))))
2103 ((search-forward "UNSEEN " nil t)
2104 (imap-mailbox-put 'unseen (read (current-buffer))))
2105 ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2106 (imap-mailbox-put 'uidvalidity (match-string 1)))
2107 ((search-forward "READ-ONLY" nil t)
2108 (imap-mailbox-put 'read-only t))
2109 ((search-forward "NEWNAME " nil t)
2110 (let (oldname newname)
2111 (setq oldname (imap-parse-string))
2113 (setq newname (imap-parse-string))
2114 (imap-mailbox-put 'newname newname oldname)))
2115 ((search-forward "TRYCREATE" nil t)
2116 (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2117 ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2118 (imap-mailbox-put 'appenduid
2119 (list (match-string 1)
2120 (string-to-number (match-string 2)))
2121 imap-current-target-mailbox))
2122 ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2123 (imap-mailbox-put 'copyuid (list (match-string 1)
2126 imap-current-target-mailbox))
2127 ((search-forward "ALERT] " nil t)
2128 (message "Imap server %s information: %s" imap-server
2129 (buffer-substring (point) (point-max)))))))
2131 ;; mailbox-list = "(" [mbx-list-flags] ")" SP
2132 ;; (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2134 ;; mbx-list-flags = *(mbx-list-oflag SP) mbx-list-sflag
2135 ;; *(SP mbx-list-oflag) /
2136 ;; mbx-list-oflag *(SP mbx-list-oflag)
2138 ;; mbx-list-oflag = "\Noinferiors" / flag-extension
2139 ;; ; Other flags; multiple possible per LIST response
2141 ;; mbx-list-sflag = "\Noselect" / "\Marked" / "\Unmarked"
2142 ;; ; Selectability flags; only one per LIST response
2144 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2145 ;; "\" quoted-specials
2147 ;; quoted-specials = DQUOTE / "\"
2149 (defun imap-parse-data-list (type)
2150 (let (flags delimiter mailbox)
2151 (setq flags (imap-parse-flag-list))
2152 (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2153 (setq delimiter (match-string 1))
2154 (goto-char (1+ (match-end 0)))
2155 (when (setq mailbox (imap-parse-mailbox))
2156 (imap-mailbox-put type t mailbox)
2157 (imap-mailbox-put 'list-flags flags mailbox)
2158 (imap-mailbox-put 'delimiter delimiter mailbox)))))
2160 ;; msg_att ::= "(" 1#("ENVELOPE" SPACE envelope /
2161 ;; "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2162 ;; "INTERNALDATE" SPACE date_time /
2163 ;; "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2164 ;; "RFC822.SIZE" SPACE number /
2165 ;; "BODY" ["STRUCTURE"] SPACE body /
2166 ;; "BODY" section ["<" number ">"] SPACE nstring /
2167 ;; "UID" SPACE uniqueid) ")"
2169 ;; date_time ::= <"> date_day_fixed "-" date_month "-" date_year
2170 ;; SPACE time SPACE zone <">
2172 ;; section ::= "[" [section_text / (nz_number *["." nz_number]
2173 ;; ["." (section_text / "MIME")])] "]"
2175 ;; section_text ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2176 ;; SPACE header_list / "TEXT"
2178 ;; header_fld_name ::= astring
2180 ;; header_list ::= "(" 1#header_fld_name ")"
2182 (defsubst imap-parse-header-list ()
2183 (when (eq (char-after) ?\()
2185 (while (not (eq (char-after) ?\)))
2187 (push (imap-parse-astring) strlist))
2189 (nreverse strlist))))
2191 (defsubst imap-parse-fetch-body-section ()
2193 (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2194 (if (eq (char-before) ? )
2196 (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2197 (search-forward "]" nil t))
2200 (defun imap-parse-fetch (response)
2201 (when (eq (char-after) ?\()
2202 (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2203 rfc822size body bodydetail bodystructure flags-empty)
2204 (while (not (eq (char-after) ?\)))
2206 (let ((token (read (current-buffer))))
2208 (cond ((eq token 'UID)
2209 (setq uid (condition-case ()
2210 (read (current-buffer))
2213 (setq flags (imap-parse-flag-list))
2215 (setq flags-empty 't)))
2216 ((eq token 'ENVELOPE)
2217 (setq envelope (imap-parse-envelope)))
2218 ((eq token 'INTERNALDATE)
2219 (setq internaldate (imap-parse-string)))
2221 (setq rfc822 (imap-parse-nstring)))
2222 ((eq token 'RFC822.HEADER)
2223 (setq rfc822header (imap-parse-nstring)))
2224 ((eq token 'RFC822.TEXT)
2225 (setq rfc822text (imap-parse-nstring)))
2226 ((eq token 'RFC822.SIZE)
2227 (setq rfc822size (read (current-buffer))))
2229 (if (eq (char-before) ?\[)
2231 (upcase (imap-parse-fetch-body-section))
2232 (and (eq (char-after) ?<)
2233 (buffer-substring (1+ (point))
2234 (search-forward ">" nil t)))
2235 (progn (imap-forward)
2236 (imap-parse-nstring)))
2238 (setq body (imap-parse-body))))
2239 ((eq token 'BODYSTRUCTURE)
2240 (setq bodystructure (imap-parse-body))))))
2242 (setq imap-current-message uid)
2243 (imap-message-put uid 'UID uid)
2244 (and (or flags flags-empty) (imap-message-put uid 'FLAGS flags))
2245 (and envelope (imap-message-put uid 'ENVELOPE envelope))
2246 (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2247 (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2248 (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2249 (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2250 (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2251 (and body (imap-message-put uid 'BODY body))
2252 (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2253 (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2254 (run-hooks 'imap-fetch-data-hook)))))
2256 ;; mailbox-data = ...
2257 ;; "STATUS" SP mailbox SP "("
2258 ;; [status-att SP number
2259 ;; *(SP status-att SP number)] ")"
2262 ;; status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2265 (defun imap-parse-status ()
2266 (let ((mailbox (imap-parse-mailbox)))
2267 (when (and mailbox (search-forward "(" nil t))
2268 (while (not (eq (char-after) ?\)))
2269 (let ((token (read (current-buffer))))
2270 (cond ((eq token 'MESSAGES)
2271 (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2273 (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2274 ((eq token 'UIDNEXT)
2275 (imap-mailbox-put 'uidnext (read (current-buffer)) mailbox))
2276 ((eq token 'UIDVALIDITY)
2277 (and (looking-at " \\([0-9]+\\)")
2278 (imap-mailbox-put 'uidvalidity (match-string 1) mailbox)
2279 (goto-char (match-end 1))))
2281 (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2283 (message "Unknown status data %s in mailbox %s ignored"
2284 token mailbox))))))))
2286 ;; acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2289 ;; identifier ::= astring
2291 ;; rights ::= astring
2293 (defun imap-parse-acl ()
2294 (let ((mailbox (imap-parse-mailbox))
2295 identifier rights acl)
2296 (while (eq (char-after) ?\ )
2298 (setq identifier (imap-parse-astring))
2300 (setq rights (imap-parse-astring))
2301 (setq acl (append acl (list (cons identifier rights)))))
2302 (imap-mailbox-put 'acl acl mailbox)))
2304 ;; flag-list = "(" [flag *(SP flag)] ")"
2306 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2307 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2308 ;; ; Does not include "\Recent"
2310 ;; flag-keyword = atom
2312 ;; flag-extension = "\" atom
2313 ;; ; Future expansion. Client implementations
2314 ;; ; MUST accept flag-extension flags. Server
2315 ;; ; implementations MUST NOT generate
2316 ;; ; flag-extension flags except as defined by
2317 ;; ; future standard or standards-track
2318 ;; ; revisions of this specification.
2320 (defun imap-parse-flag-list ()
2321 (let (flag-list start)
2322 (assert (eq (char-after) ?\() t "In imap-parse-flag-list")
2323 (while (and (not (eq (char-after) ?\)))
2326 ;; next line for Courier IMAP bug.
2327 (skip-chars-forward " ")
2329 (> (skip-chars-forward "^ )" (imap-point-at-eol)) 0))
2330 (push (buffer-substring start (point)) flag-list))
2331 (assert (eq (char-after) ?\)) t "In imap-parse-flag-list")
2333 (nreverse flag-list)))
2335 ;; envelope = "(" env-date SP env-subject SP env-from SP env-sender SP
2336 ;; env-reply-to SP env-to SP env-cc SP env-bcc SP
2337 ;; env-in-reply-to SP env-message-id ")"
2339 ;; env-bcc = "(" 1*address ")" / nil
2341 ;; env-cc = "(" 1*address ")" / nil
2343 ;; env-date = nstring
2345 ;; env-from = "(" 1*address ")" / nil
2347 ;; env-in-reply-to = nstring
2349 ;; env-message-id = nstring
2351 ;; env-reply-to = "(" 1*address ")" / nil
2353 ;; env-sender = "(" 1*address ")" / nil
2355 ;; env-subject = nstring
2357 ;; env-to = "(" 1*address ")" / nil
2359 (defun imap-parse-envelope ()
2360 (when (eq (char-after) ?\()
2362 (vector (prog1 (imap-parse-nstring) ;; date
2364 (prog1 (imap-parse-nstring) ;; subject
2366 (prog1 (imap-parse-address-list) ;; from
2368 (prog1 (imap-parse-address-list) ;; sender
2370 (prog1 (imap-parse-address-list) ;; reply-to
2372 (prog1 (imap-parse-address-list) ;; to
2374 (prog1 (imap-parse-address-list) ;; cc
2376 (prog1 (imap-parse-address-list) ;; bcc
2378 (prog1 (imap-parse-nstring) ;; in-reply-to
2380 (prog1 (imap-parse-nstring) ;; message-id
2383 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2385 (defsubst imap-parse-string-list ()
2386 (cond ((eq (char-after) ?\() ;; body-fld-param
2389 (while (setq str (imap-parse-string))
2391 ;; buggy stalker communigate pro 3.0 doesn't print SPC
2392 ;; between body-fld-param's sometimes
2393 (or (eq (char-after) ?\")
2395 (nreverse strlist)))
2399 ;; body-extension = nstring / number /
2400 ;; "(" body-extension *(SP body-extension) ")"
2401 ;; ; Future expansion. Client implementations
2402 ;; ; MUST accept body-extension fields. Server
2403 ;; ; implementations MUST NOT generate
2404 ;; ; body-extension fields except as defined by
2405 ;; ; future standard or standards-track
2406 ;; ; revisions of this specification.
2408 (defun imap-parse-body-extension ()
2409 (if (eq (char-after) ?\()
2412 (push (imap-parse-body-extension) b-e)
2413 (while (eq (char-after) ?\ )
2415 (push (imap-parse-body-extension) b-e))
2416 (assert (eq (char-after) ?\)) t "In imap-parse-body-extension")
2419 (or (imap-parse-number)
2420 (imap-parse-nstring))))
2422 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2423 ;; *(SP body-extension)]]
2424 ;; ; MUST NOT be returned on non-extensible
2427 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2428 ;; *(SP body-extension)]]
2429 ;; ; MUST NOT be returned on non-extensible
2432 (defsubst imap-parse-body-ext ()
2434 (when (eq (char-after) ?\ ) ;; body-fld-dsp
2437 (if (eq (char-after) ?\()
2440 (push (imap-parse-string) dsp)
2442 (push (imap-parse-string-list) dsp)
2444 (assert (imap-parse-nil) t "In imap-parse-body-ext"))
2445 (push (nreverse dsp) ext))
2446 (when (eq (char-after) ?\ ) ;; body-fld-lang
2448 (if (eq (char-after) ?\()
2449 (push (imap-parse-string-list) ext)
2450 (push (imap-parse-nstring) ext))
2451 (while (eq (char-after) ?\ ) ;; body-extension
2453 (setq ext (append (imap-parse-body-extension) ext)))))
2456 ;; body = "(" body-type-1part / body-type-mpart ")"
2458 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2459 ;; *(SP body-extension)]]
2460 ;; ; MUST NOT be returned on non-extensible
2463 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2464 ;; *(SP body-extension)]]
2465 ;; ; MUST NOT be returned on non-extensible
2468 ;; body-fields = body-fld-param SP body-fld-id SP body-fld-desc SP
2469 ;; body-fld-enc SP body-fld-octets
2471 ;; body-fld-desc = nstring
2473 ;; body-fld-dsp = "(" string SP body-fld-param ")" / nil
2475 ;; body-fld-enc = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2476 ;; "QUOTED-PRINTABLE") DQUOTE) / string
2478 ;; body-fld-id = nstring
2480 ;; body-fld-lang = nstring / "(" string *(SP string) ")"
2482 ;; body-fld-lines = number
2484 ;; body-fld-md5 = nstring
2486 ;; body-fld-octets = number
2488 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2490 ;; body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2491 ;; [SP body-ext-1part]
2493 ;; body-type-basic = media-basic SP body-fields
2494 ;; ; MESSAGE subtype MUST NOT be "RFC822"
2496 ;; body-type-msg = media-message SP body-fields SP envelope
2497 ;; SP body SP body-fld-lines
2499 ;; body-type-text = media-text SP body-fields SP body-fld-lines
2501 ;; body-type-mpart = 1*body SP media-subtype
2502 ;; [SP body-ext-mpart]
2504 ;; media-basic = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2505 ;; "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2506 ;; ; Defined in [MIME-IMT]
2508 ;; media-message = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2509 ;; ; Defined in [MIME-IMT]
2511 ;; media-subtype = string
2512 ;; ; Defined in [MIME-IMT]
2514 ;; media-text = DQUOTE "TEXT" DQUOTE SP media-subtype
2515 ;; ; Defined in [MIME-IMT]
2517 (defun imap-parse-body ()
2519 (when (eq (char-after) ?\()
2521 (if (eq (char-after) ?\()
2523 (while (and (eq (char-after) ?\()
2524 (setq subbody (imap-parse-body)))
2525 ;; buggy stalker communigate pro 3.0 insert a SPC between
2526 ;; parts in multiparts
2527 (when (and (eq (char-after) ?\ )
2528 (eq (char-after (1+ (point))) ?\())
2530 (push subbody body))
2532 (push (imap-parse-string) body) ;; media-subtype
2533 (when (eq (char-after) ?\ ) ;; body-ext-mpart:
2535 (if (eq (char-after) ?\() ;; body-fld-param
2536 (push (imap-parse-string-list) body)
2537 (push (and (imap-parse-nil) nil) body))
2539 (append (imap-parse-body-ext) body))) ;; body-ext-...
2540 (assert (eq (char-after) ?\)) t "In imap-parse-body")
2544 (push (imap-parse-string) body) ;; media-type
2546 (push (imap-parse-string) body) ;; media-subtype
2548 ;; next line for Sun SIMS bug
2549 (and (eq (char-after) ? ) (imap-forward))
2550 (if (eq (char-after) ?\() ;; body-fld-param
2551 (push (imap-parse-string-list) body)
2552 (push (and (imap-parse-nil) nil) body))
2554 (push (imap-parse-nstring) body) ;; body-fld-id
2556 (push (imap-parse-nstring) body) ;; body-fld-desc
2558 ;; next `or' for Sun SIMS bug, it regard body-fld-enc as a
2559 ;; nstring and return nil instead of defaulting back to 7BIT
2560 ;; as the standard says.
2561 (push (or (imap-parse-nstring) "7BIT") body) ;; body-fld-enc
2563 (push (imap-parse-number) body) ;; body-fld-octets
2565 ;; ok, we're done parsing the required parts, what comes now is one
2568 ;; envelope (then we're parsing body-type-msg)
2569 ;; body-fld-lines (then we're parsing body-type-text)
2570 ;; body-ext-1part (then we're parsing body-type-basic)
2572 ;; the problem is that the two first are in turn optionally followed
2573 ;; by the third. So we parse the first two here (if there are any)...
2575 (when (eq (char-after) ?\ )
2578 (cond ((eq (char-after) ?\() ;; body-type-msg:
2579 (push (imap-parse-envelope) body) ;; envelope
2581 (push (imap-parse-body) body) ;; body
2582 ;; buggy stalker communigate pro 3.0 doesn't print
2583 ;; number of lines in message/rfc822 attachment
2584 (if (eq (char-after) ?\))
2587 (push (imap-parse-number) body))) ;; body-fld-lines
2588 ((setq lines (imap-parse-number)) ;; body-type-text:
2589 (push lines body)) ;; body-fld-lines
2591 (backward-char))))) ;; no match...
2593 ;; ...and then parse the third one here...
2595 (when (eq (char-after) ?\ ) ;; body-ext-1part:
2597 (push (imap-parse-nstring) body) ;; body-fld-md5
2598 (setq body (append (imap-parse-body-ext) body))) ;; body-ext-1part..
2600 (assert (eq (char-after) ?\)) t "In imap-parse-body 2")
2604 (when imap-debug ; (untrace-all)
2606 (buffer-disable-undo (get-buffer-create imap-debug-buffer))
2607 (mapcar (lambda (f) (trace-function-background f imap-debug-buffer))
2619 imap-interactive-login
2635 imap-send-command-wait
2640 imap-current-mailbox
2641 imap-current-mailbox-p-1
2642 imap-current-mailbox-p
2643 imap-mailbox-select-1
2645 imap-mailbox-examine-1
2646 imap-mailbox-examine
2647 imap-mailbox-unselect
2648 imap-mailbox-expunge
2650 imap-mailbox-create-1
2656 imap-mailbox-subscribe
2657 imap-mailbox-unsubscribe
2659 imap-mailbox-acl-get
2660 imap-mailbox-acl-set
2661 imap-mailbox-acl-delete
2662 imap-current-message
2663 imap-list-to-message-set
2670 imap-message-flag-permanent-p
2671 imap-message-flags-set
2672 imap-message-flags-del
2673 imap-message-flags-add
2674 imap-message-copyuid-1
2675 imap-message-copyuid
2677 imap-message-appenduid-1
2678 imap-message-appenduid
2690 imap-parse-resp-text
2691 imap-parse-resp-text-code
2692 imap-parse-data-list
2696 imap-parse-flag-list
2698 imap-parse-body-extension
2704 ;;; imap.el ends here