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 (and (imap-capability 'STARTTLS buffer)
720 (call-process "starttls"))
723 (defun imap-starttls-open (name buffer server port)
724 (let* ((port (or port imap-default-port))
725 (coding-system-for-read imap-coding-system-for-read)
726 (coding-system-for-write imap-coding-system-for-write)
727 (process (starttls-open-stream name buffer server port))
729 (message "imap: Connecting with STARTTLS...")
731 (while (and (memq (process-status process) '(open run))
732 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
733 (goto-char (point-min))
734 (not (imap-parse-greeting)))
735 (accept-process-output process 1)
738 (with-current-buffer (get-buffer-create imap-log-buffer)
739 (buffer-disable-undo)
740 (goto-char (point-max))
741 (insert-buffer-substring buffer)))
742 (let ((imap-process process))
745 (set-process-filter imap-process 'imap-arrival-filter)
746 (when (and (eq imap-stream 'starttls)
747 (imap-ok-p (imap-send-command-wait "STARTTLS")))
748 (starttls-negotiate imap-process)))
749 (set-process-filter imap-process nil)))
750 (when (memq (process-status process) '(open run))
751 (setq done process)))
754 (message "imap: Connecting with STARTTLS...done")
756 (message "imap: Connecting with STARTTLS...failed")
759 ;; Server functions; authenticator stuff:
761 (defun imap-interactive-login (buffer loginfunc)
762 "Login to server in BUFFER.
763 LOGINFUNC is passed a username and a password, it should return t if
764 it where sucessful authenticating itself to the server, nil otherwise.
765 Returns t if login was successful, nil otherwise."
766 (with-current-buffer buffer
767 (make-local-variable 'imap-username)
768 (make-local-variable 'imap-password)
769 (let (user passwd ret)
770 ;; (condition-case ()
771 (while (or (not user) (not passwd))
772 (setq user (or imap-username
773 (read-from-minibuffer
774 (concat "IMAP username for " imap-server ": ")
775 (or user imap-default-user))))
776 (setq passwd (or imap-password
778 (concat "IMAP password for " user "@"
780 (when (and user passwd)
781 (if (funcall loginfunc user passwd)
785 (if (and (not imap-password)
786 (y-or-n-p "Store password for this session? "))
787 (setq imap-password passwd)))
788 (message "Login failed...")
791 ;; (quit (with-current-buffer buffer
794 ;; (error (with-current-buffer buffer
799 (defun imap-gssapi-auth-p (buffer)
800 (and (imap-capability 'AUTH=GSSAPI buffer)
802 (let (prg (prgs imap-gssapi-program))
803 (while (setq prg (pop prgs))
805 (and (call-process (substring prg 0 (string-match " " prg)))
806 (throw 'imtest-found t))
809 (defun imap-gssapi-auth (buffer)
810 (message "imap: Authenticating using GSSAPI...%s"
811 (if (eq imap-stream 'gssapi) "done" "failed"))
812 (eq imap-stream 'gssapi))
814 (defun imap-kerberos4-auth-p (buffer)
815 (and (imap-capability 'AUTH=KERBEROS_V4 buffer)
817 (let (prg (prgs imap-kerberos4-program))
818 (while (setq prg (pop prgs))
820 (and (call-process (substring prg 0 (string-match " " prg)))
821 (throw 'imtest-found t))
824 (defun imap-kerberos4-auth (buffer)
825 (message "imap: Authenticating using Kerberos 4...%s"
826 (if (eq imap-stream 'kerberos4) "done" "failed"))
827 (eq imap-stream 'kerberos4))
829 (defun imap-cram-md5-p (buffer)
830 (imap-capability 'AUTH=CRAM-MD5 buffer))
832 (defun imap-cram-md5-auth (buffer)
833 "Login to server using the AUTH CRAM-MD5 method."
834 (message "imap: Authenticating using CRAM-MD5...")
835 (let ((done (imap-interactive-login
837 (lambda (user passwd)
839 (imap-send-command-wait
841 "AUTHENTICATE CRAM-MD5"
843 (let* ((decoded (base64-decode-string challenge))
844 (hash (rfc2104-hash 'md5 64 16 passwd decoded))
845 (response (concat user " " hash))
846 (encoded (base64-encode-string response)))
849 (message "imap: Authenticating using CRAM-MD5...done")
850 (message "imap: Authenticating using CRAM-MD5...failed"))))
852 (defun imap-login-p (buffer)
853 (and (not (imap-capability 'LOGINDISABLED buffer))
854 (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
856 (defun imap-login-auth (buffer)
857 "Login to server using the LOGIN command."
858 (message "imap: Plaintext authentication...")
859 (imap-interactive-login buffer
860 (lambda (user passwd)
861 (imap-ok-p (imap-send-command-wait
862 (concat "LOGIN \"" user "\" \""
865 (defun imap-anonymous-p (buffer)
868 (defun imap-anonymous-auth (buffer)
869 (message "imap: Loging in anonymously...")
870 (with-current-buffer buffer
871 (imap-ok-p (imap-send-command-wait
872 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
873 (system-name)) "\"")))))
875 (defun imap-digest-md5-p (buffer)
876 (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
878 (require 'digest-md5)
881 (defun imap-digest-md5-auth (buffer)
882 "Login to server using the AUTH DIGEST-MD5 method."
883 (message "imap: Authenticating using DIGEST-MD5...")
884 (imap-interactive-login
886 (lambda (user passwd)
890 "AUTHENTICATE DIGEST-MD5"
892 (digest-md5-parse-digest-challenge
893 (base64-decode-string challenge))
895 (digest-md5-digest-uri
896 "imap" (digest-md5-challenge 'realm)))
898 (digest-md5-digest-response
899 user passwd digest-uri)))
900 (base64-encode-string response 'no-line-break))))
902 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
904 (setq imap-continuation nil)
905 (imap-send-command-1 "")
906 (imap-ok-p (imap-wait-for-tag tag)))))))
910 (defun imap-open-1 (buffer)
911 (with-current-buffer buffer
913 (setq imap-current-mailbox nil
914 imap-current-message nil
916 imap-process (condition-case ()
917 (funcall (nth 2 (assq imap-stream
919 "imap" buffer imap-server imap-port)
922 (set-process-filter imap-process 'imap-arrival-filter)
923 (set-process-sentinel imap-process 'imap-sentinel)
924 (while (and (eq imap-state 'initial)
925 (memq (process-status imap-process) '(open run)))
926 (message "Waiting for response from %s..." imap-server)
927 (accept-process-output imap-process 1))
928 (message "Waiting for response from %s...done" imap-server)
929 (and (memq (process-status imap-process) '(open run))
932 (defun imap-open (server &optional port stream auth buffer)
933 "Open a IMAP connection to host SERVER at PORT returning a buffer.
934 If PORT is unspecified, a default value is used (143 except
935 for SSL which use 993).
936 STREAM indicates the stream to use, see `imap-streams' for available
937 streams. If nil, it choices the best stream the server is capable of.
938 AUTH indicates authenticator to use, see `imap-authenticators' for
939 available authenticators. If nil, it choices the best stream the
940 server is capable of.
941 BUFFER can be a buffer or a name of a buffer, which is created if
942 necessery. If nil, the buffer name is generated."
943 (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
944 (with-current-buffer (get-buffer-create buffer)
945 (if (imap-opened buffer)
947 (mapcar 'make-local-variable imap-local-variables)
948 (imap-disable-multibyte)
949 (buffer-disable-undo)
950 (setq imap-server (or server imap-server))
951 (setq imap-port (or port imap-port))
952 (setq imap-auth (or auth imap-auth))
953 (setq imap-stream (or stream imap-stream))
954 (message "imap: Connecting to %s..." imap-server)
955 (if (let ((imap-stream (or imap-stream imap-default-stream)))
956 (imap-open-1 buffer))
958 (let (stream-changed)
959 (message "imap: Connecting to %s...done" imap-server)
960 (when (null imap-stream)
961 (let ((streams imap-streams))
962 (while (setq stream (pop streams))
963 (if (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
964 (setq stream-changed (not (eq (or imap-stream
970 (error "Couldn't figure out a stream for server"))))
972 (message "imap: Reconnecting with stream `%s'..." imap-stream)
974 (if (imap-open-1 buffer)
975 (message "imap: Reconnecting with stream `%s'...done"
977 (message "imap: Reconnecting with stream `%s'...failed"
979 (setq imap-capability nil))
980 (if (imap-opened buffer)
981 ;; Choose authenticator
982 (when (and (null imap-auth) (not (eq imap-state 'auth)))
983 (let ((auths imap-authenticators))
984 (while (setq auth (pop auths))
985 (if (funcall (nth 1 (assq auth imap-authenticator-alist))
990 (error "Couldn't figure out authenticator for server"))))))
991 (message "imap: Connecting to %s...failed" imap-server))
992 (when (imap-opened buffer)
993 (setq imap-mailbox-data (make-vector imap-mailbox-prime 0))
996 (defun imap-opened (&optional buffer)
997 "Return non-nil if connection to imap server in BUFFER is open.
998 If BUFFER is nil then the current buffer is used."
999 (and (setq buffer (get-buffer (or buffer (current-buffer))))
1000 (buffer-live-p buffer)
1001 (with-current-buffer buffer
1003 (memq (process-status imap-process) '(open run))))))
1005 (defun imap-authenticate (&optional user passwd buffer)
1006 "Authenticate to server in BUFFER, using current buffer if nil.
1007 It uses the authenticator specified when opening the server. If the
1008 authenticator requires username/passwords, they are queried from the
1009 user and optionally stored in the buffer. If USER and/or PASSWD is
1010 specified, the user will not be questioned and the username and/or
1011 password is remembered in the buffer."
1012 (with-current-buffer (or buffer (current-buffer))
1013 (if (not (eq imap-state 'nonauth))
1014 (or (eq imap-state 'auth)
1015 (eq imap-state 'select)
1016 (eq imap-state 'examine))
1017 (make-local-variable 'imap-username)
1018 (make-local-variable 'imap-password)
1019 (if user (setq imap-username user))
1020 (if passwd (setq imap-password passwd))
1021 (if (funcall (nth 2 (assq imap-auth imap-authenticator-alist)) buffer)
1022 (setq imap-state 'auth)))))
1024 (defun imap-close (&optional buffer)
1025 "Close connection to server in BUFFER.
1026 If BUFFER is nil, the current buffer is used."
1027 (with-current-buffer (or buffer (current-buffer))
1030 (imap-send-command-wait "LOGOUT")
1032 (when (and imap-process
1033 (memq (process-status imap-process) '(open run)))
1034 (delete-process imap-process))
1035 (setq imap-current-mailbox nil
1036 imap-current-message nil
1041 (defun imap-capability (&optional identifier buffer)
1042 "Return a list of identifiers which server in BUFFER support.
1043 If IDENTIFIER, return non-nil if it's among the servers capabilities.
1044 If BUFFER is nil, the current buffer is assumed."
1045 (with-current-buffer (or buffer (current-buffer))
1046 (unless imap-capability
1047 (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
1048 (setq imap-capability '(IMAP2))))
1050 (memq (intern (upcase (symbol-name identifier))) imap-capability)
1053 (defun imap-namespace (&optional buffer)
1054 "Return a namespace hierarchy at server in BUFFER.
1055 If BUFFER is nil, the current buffer is assumed."
1056 (with-current-buffer (or buffer (current-buffer))
1057 (unless imap-namespace
1058 (when (imap-capability 'NAMESPACE)
1059 (imap-send-command-wait "NAMESPACE")))
1062 (defun imap-send-command-wait (command &optional buffer)
1063 (imap-wait-for-tag (imap-send-command command buffer) buffer))
1066 ;; Mailbox functions:
1068 (defun imap-mailbox-put (propname value &optional mailbox buffer)
1069 (with-current-buffer (or buffer (current-buffer))
1070 (if imap-mailbox-data
1071 (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
1073 (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
1074 propname value mailbox (current-buffer)))
1077 (defsubst imap-mailbox-get-1 (propname &optional mailbox)
1078 (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
1081 (defun imap-mailbox-get (propname &optional mailbox buffer)
1082 (let ((mailbox (imap-utf7-encode mailbox)))
1083 (with-current-buffer (or buffer (current-buffer))
1084 (imap-mailbox-get-1 propname (or mailbox imap-current-mailbox)))))
1086 (defun imap-mailbox-map-1 (func &optional mailbox-decoder buffer)
1087 (with-current-buffer (or buffer (current-buffer))
1091 (push (funcall func (if mailbox-decoder
1092 (funcall mailbox-decoder (symbol-name s))
1093 (symbol-name s))) result))
1097 (defun imap-mailbox-map (func &optional buffer)
1098 "Map a function across each mailbox in `imap-mailbox-data', returning a list.
1099 Function should take a mailbox name (a string) as
1101 (imap-mailbox-map-1 func 'imap-utf7-decode buffer))
1103 (defun imap-current-mailbox (&optional buffer)
1104 (with-current-buffer (or buffer (current-buffer))
1105 (imap-utf7-decode imap-current-mailbox)))
1107 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
1108 (and (string= mailbox imap-current-mailbox)
1110 (eq imap-state 'examine))
1112 (eq imap-state 'selected)))))
1114 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
1115 (with-current-buffer (or buffer (current-buffer))
1116 (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
1118 (defun imap-mailbox-select-1 (mailbox &optional examine)
1119 "Select MAILBOX on server in BUFFER.
1120 If EXAMINE is non-nil, do a read-only select."
1121 (if (imap-current-mailbox-p-1 mailbox examine)
1122 imap-current-mailbox
1123 (setq imap-current-mailbox mailbox)
1124 (if (imap-ok-p (imap-send-command-wait
1125 (concat (if examine "EXAMINE" "SELECT") " \""
1128 (setq imap-message-data (make-vector imap-message-prime 0)
1129 imap-state (if examine 'examine 'selected))
1130 imap-current-mailbox)
1131 ;; Failed SELECT/EXAMINE unselects current mailbox
1132 (setq imap-current-mailbox nil))))
1134 (defun imap-mailbox-select (mailbox &optional examine buffer)
1135 (with-current-buffer (or buffer (current-buffer))
1137 (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
1139 (defun imap-mailbox-examine-1 (mailbox &optional buffer)
1140 (with-current-buffer (or buffer (current-buffer))
1141 (imap-mailbox-select-1 mailbox 'examine)))
1143 (defun imap-mailbox-examine (mailbox &optional buffer)
1144 "Examine MAILBOX on server in BUFFER."
1145 (imap-mailbox-select mailbox 'examine buffer))
1147 (defun imap-mailbox-unselect (&optional buffer)
1148 "Close current folder in BUFFER, without expunging articles."
1149 (with-current-buffer (or buffer (current-buffer))
1150 (when (or (eq imap-state 'auth)
1151 (and (imap-capability 'UNSELECT)
1152 (imap-ok-p (imap-send-command-wait "UNSELECT")))
1154 (imap-send-command-wait (concat "EXAMINE \""
1155 imap-current-mailbox
1157 (imap-ok-p (imap-send-command-wait "CLOSE"))))
1158 (setq imap-current-mailbox nil
1159 imap-message-data nil
1163 (defun imap-mailbox-expunge (&optional asynch buffer)
1164 "Expunge articles in current folder in BUFFER.
1165 If ASYNCH, do not wait for succesful completion of the command.
1166 If BUFFER is nil the current buffer is assumed."
1167 (with-current-buffer (or buffer (current-buffer))
1168 (when (and imap-current-mailbox (not (eq imap-state 'examine)))
1170 (imap-send-command "EXPUNGE")
1171 (imap-ok-p (imap-send-command-wait "EXPUNGE"))))))
1173 (defun imap-mailbox-close (&optional asynch buffer)
1174 "Expunge articles and close current folder in BUFFER.
1175 If ASYNCH, do not wait for succesful completion of the command.
1176 If BUFFER is nil the current buffer is assumed."
1177 (with-current-buffer (or buffer (current-buffer))
1178 (when imap-current-mailbox
1180 (imap-add-callback (imap-send-command "CLOSE")
1181 `(lambda (tag status)
1182 (message "IMAP mailbox `%s' closed... %s"
1183 imap-current-mailbox status)
1184 (when (eq ,imap-current-mailbox
1185 imap-current-mailbox)
1186 ;; Don't wipe out data if another mailbox
1188 (setq imap-current-mailbox nil
1189 imap-message-data nil
1190 imap-state 'auth))))
1191 (when (imap-ok-p (imap-send-command-wait "CLOSE"))
1192 (setq imap-current-mailbox nil
1193 imap-message-data nil
1197 (defun imap-mailbox-create-1 (mailbox)
1198 (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
1200 (defun imap-mailbox-create (mailbox &optional buffer)
1201 "Create MAILBOX on server in BUFFER.
1202 If BUFFER is nil the current buffer is assumed."
1203 (with-current-buffer (or buffer (current-buffer))
1204 (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
1206 (defun imap-mailbox-delete (mailbox &optional buffer)
1207 "Delete MAILBOX on server in BUFFER.
1208 If BUFFER is nil the current buffer is assumed."
1209 (let ((mailbox (imap-utf7-encode mailbox)))
1210 (with-current-buffer (or buffer (current-buffer))
1212 (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1214 (defun imap-mailbox-rename (oldname newname &optional buffer)
1215 "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1216 If BUFFER is nil the current buffer is assumed."
1217 (let ((oldname (imap-utf7-encode oldname))
1218 (newname (imap-utf7-encode newname)))
1219 (with-current-buffer (or buffer (current-buffer))
1221 (imap-send-command-wait (list "RENAME \"" oldname "\" "
1222 "\"" newname "\""))))))
1224 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1225 "Return a list of subscribed mailboxes on server in BUFFER.
1226 If ROOT is non-nil, only list matching mailboxes. If ADD-DELIMITER is
1227 non-nil, a hierarchy delimiter is added to root. REFERENCE is a
1228 implementation-specific string that has to be passed to lsub command."
1229 (with-current-buffer (or buffer (current-buffer))
1230 ;; Make sure we know the hierarchy separator for root's hierarchy
1231 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1232 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1233 (imap-utf7-encode root) "\"")))
1234 ;; clear list data (NB not delimiter and other stuff)
1235 (imap-mailbox-map-1 (lambda (mailbox)
1236 (imap-mailbox-put 'lsub nil mailbox)))
1238 (imap-send-command-wait
1239 (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1240 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1243 (imap-mailbox-map-1 (lambda (mailbox)
1244 (when (imap-mailbox-get-1 'lsub mailbox)
1245 (push (imap-utf7-decode mailbox) out))))
1248 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1249 "Return a list of mailboxes matching ROOT on server in BUFFER.
1250 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1251 root. REFERENCE is a implementation-specific string that has to be
1252 passed to list command."
1253 (with-current-buffer (or buffer (current-buffer))
1254 ;; Make sure we know the hierarchy separator for root's hierarchy
1255 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1256 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1257 (imap-utf7-encode root) "\"")))
1258 ;; clear list data (NB not delimiter and other stuff)
1259 (imap-mailbox-map-1 (lambda (mailbox)
1260 (imap-mailbox-put 'list nil mailbox)))
1262 (imap-send-command-wait
1263 (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1264 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1267 (imap-mailbox-map-1 (lambda (mailbox)
1268 (when (imap-mailbox-get-1 'list mailbox)
1269 (push (imap-utf7-decode mailbox) out))))
1272 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1273 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1274 Returns non-nil if successful."
1275 (with-current-buffer (or buffer (current-buffer))
1276 (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1277 (imap-utf7-encode mailbox)
1280 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1281 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1282 Returns non-nil if successful."
1283 (with-current-buffer (or buffer (current-buffer))
1284 (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1285 (imap-utf7-encode mailbox)
1288 (defun imap-mailbox-status (mailbox items &optional buffer)
1289 "Get status items ITEM in MAILBOX from server in BUFFER.
1290 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1291 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1292 or 'unseen. If ITEMS is a list of symbols, a list of values is
1293 returned, if ITEMS is a symbol only it's value is returned."
1294 (with-current-buffer (or buffer (current-buffer))
1296 (imap-send-command-wait (list "STATUS \""
1297 (imap-utf7-encode mailbox)
1304 (mapcar (lambda (item)
1305 (imap-mailbox-get item mailbox))
1307 (imap-mailbox-get items mailbox)))))
1309 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1310 "Get ACL on mailbox from server in BUFFER."
1311 (let ((mailbox (imap-utf7-encode mailbox)))
1312 (with-current-buffer (or buffer (current-buffer))
1314 (imap-send-command-wait (list "GETACL \""
1315 (or mailbox imap-current-mailbox)
1317 (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1319 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1320 "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
1321 (let ((mailbox (imap-utf7-encode mailbox)))
1322 (with-current-buffer (or buffer (current-buffer))
1324 (imap-send-command-wait (list "SETACL \""
1325 (or mailbox imap-current-mailbox)
1331 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1332 "Removes any <identifier,rights> pair for IDENTIFIER in MAILBOX from server in BUFFER."
1333 (let ((mailbox (imap-utf7-encode mailbox)))
1334 (with-current-buffer (or buffer (current-buffer))
1336 (imap-send-command-wait (list "DELETEACL \""
1337 (or mailbox imap-current-mailbox)
1342 ;; Message functions:
1344 (defun imap-current-message (&optional buffer)
1345 (with-current-buffer (or buffer (current-buffer))
1346 imap-current-message))
1348 (defun imap-list-to-message-set (list)
1349 (mapconcat (lambda (item)
1350 (number-to-string item))
1356 (defun imap-range-to-message-set (range)
1361 (car item) (cdr item))
1362 (format "%d" item)))
1363 (if (and (listp range) (not (listp (cdr range))))
1364 (list range) ;; make (1 . 2) into ((1 . 2))
1368 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1369 (with-current-buffer (or buffer (current-buffer))
1370 (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1372 (imap-list-to-message-set uids)
1376 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1377 "Fetch properties PROPS from message set UIDS from server in BUFFER.
1378 UIDS can be a string, number or a list of numbers. If RECEIVE
1379 is non-nil return theese properties."
1380 (with-current-buffer (or buffer (current-buffer))
1381 (when (imap-ok-p (imap-send-command-wait
1382 (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1384 (imap-list-to-message-set uids)
1387 (if (or (null receive) (stringp uids))
1390 (mapcar (lambda (uid)
1392 (mapcar (lambda (prop)
1393 (imap-message-get uid prop))
1395 (imap-message-get uid receive)))
1397 (imap-message-get uids receive))))))
1399 (defun imap-message-put (uid propname value &optional buffer)
1400 (with-current-buffer (or buffer (current-buffer))
1401 (if imap-message-data
1402 (put (intern (number-to-string uid) imap-message-data)
1404 (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1405 uid propname value (current-buffer)))
1408 (defun imap-message-get (uid propname &optional buffer)
1409 (with-current-buffer (or buffer (current-buffer))
1410 (get (intern-soft (number-to-string uid) imap-message-data)
1413 (defun imap-message-map (func propname &optional buffer)
1414 "Map a function across each mailbox in `imap-message-data', returning a list."
1415 (with-current-buffer (or buffer (current-buffer))
1419 (push (funcall func (get s 'UID) (get s propname)) result))
1423 (defmacro imap-message-envelope-date (uid &optional buffer)
1424 `(with-current-buffer (or ,buffer (current-buffer))
1425 (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1427 (defmacro imap-message-envelope-subject (uid &optional buffer)
1428 `(with-current-buffer (or ,buffer (current-buffer))
1429 (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1431 (defmacro imap-message-envelope-from (uid &optional buffer)
1432 `(with-current-buffer (or ,buffer (current-buffer))
1433 (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1435 (defmacro imap-message-envelope-sender (uid &optional buffer)
1436 `(with-current-buffer (or ,buffer (current-buffer))
1437 (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1439 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1440 `(with-current-buffer (or ,buffer (current-buffer))
1441 (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1443 (defmacro imap-message-envelope-to (uid &optional buffer)
1444 `(with-current-buffer (or ,buffer (current-buffer))
1445 (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1447 (defmacro imap-message-envelope-cc (uid &optional buffer)
1448 `(with-current-buffer (or ,buffer (current-buffer))
1449 (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1451 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1452 `(with-current-buffer (or ,buffer (current-buffer))
1453 (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1455 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1456 `(with-current-buffer (or ,buffer (current-buffer))
1457 (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1459 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1460 `(with-current-buffer (or ,buffer (current-buffer))
1461 (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1463 (defmacro imap-message-body (uid &optional buffer)
1464 `(with-current-buffer (or ,buffer (current-buffer))
1465 (imap-message-get ,uid 'BODY)))
1467 (defun imap-search (predicate &optional buffer)
1468 (with-current-buffer (or buffer (current-buffer))
1469 (imap-mailbox-put 'search 'dummy)
1470 (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1471 (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1473 (message "Missing SEARCH response to a SEARCH command (server not RFC compliant)...")
1475 (imap-mailbox-get-1 'search imap-current-mailbox)))))
1477 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1478 "Return t iff FLAG can be permanently (between IMAP sessions) saved on articles, in MAILBOX on server in BUFFER."
1479 (with-current-buffer (or buffer (current-buffer))
1480 (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1481 (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1483 (defun imap-message-flags-set (articles flags &optional silent buffer)
1484 (when (and articles flags)
1485 (with-current-buffer (or buffer (current-buffer))
1486 (imap-ok-p (imap-send-command-wait
1487 (concat "UID STORE " articles
1488 " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1490 (defun imap-message-flags-del (articles flags &optional silent buffer)
1491 (when (and articles flags)
1492 (with-current-buffer (or buffer (current-buffer))
1493 (imap-ok-p (imap-send-command-wait
1494 (concat "UID STORE " articles
1495 " -FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1497 (defun imap-message-flags-add (articles flags &optional silent buffer)
1498 (when (and articles flags)
1499 (with-current-buffer (or buffer (current-buffer))
1500 (imap-ok-p (imap-send-command-wait
1501 (concat "UID STORE " articles
1502 " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1504 (defun imap-message-copyuid-1 (mailbox)
1505 (if (imap-capability 'UIDPLUS)
1506 (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1507 (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1508 (let ((old-mailbox imap-current-mailbox)
1510 (imap-message-data (make-vector 2 0)))
1511 (when (imap-mailbox-examine-1 mailbox)
1513 (and (imap-fetch "*" "UID")
1514 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1515 (apply 'max (imap-message-map
1516 (lambda (uid prop) uid) 'UID))))
1518 (imap-mailbox-select old-mailbox (eq state 'examine))
1519 (imap-mailbox-unselect)))))))
1521 (defun imap-message-copyuid (mailbox &optional buffer)
1522 (with-current-buffer (or buffer (current-buffer))
1523 (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1525 (defun imap-message-copy (articles mailbox
1526 &optional dont-create no-copyuid buffer)
1527 "Copy ARTICLES (a string message set) to MAILBOX on server in
1528 BUFFER, creating mailbox if it doesn't exist. If dont-create is
1529 non-nil, it will not create a mailbox. On success, return a list with
1530 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1531 first element, rest of list contain the saved articles' UIDs."
1533 (with-current-buffer (or buffer (current-buffer))
1534 (let ((mailbox (imap-utf7-encode mailbox)))
1535 (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1536 (imap-current-target-mailbox mailbox))
1537 (if (imap-ok-p (imap-send-command-wait cmd))
1539 (when (and (not dont-create)
1540 ;; removed because of buggy Oracle server
1541 ;; that doesn't send TRYCREATE tags (which
1542 ;; is a MUST according to specifications):
1543 ;;(imap-mailbox-get-1 'trycreate mailbox)
1544 (imap-mailbox-create-1 mailbox))
1545 (imap-ok-p (imap-send-command-wait cmd)))))
1547 (imap-message-copyuid-1 mailbox)))))))
1549 (defun imap-message-appenduid-1 (mailbox)
1550 (if (imap-capability 'UIDPLUS)
1551 (imap-mailbox-get-1 'appenduid mailbox)
1552 (let ((old-mailbox imap-current-mailbox)
1554 (imap-message-data (make-vector 2 0)))
1555 (when (imap-mailbox-examine-1 mailbox)
1557 (and (imap-fetch "*" "UID")
1558 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1559 (apply 'max (imap-message-map
1560 (lambda (uid prop) uid) 'UID))))
1562 (imap-mailbox-select old-mailbox (eq state 'examine))
1563 (imap-mailbox-unselect)))))))
1565 (defun imap-message-appenduid (mailbox &optional buffer)
1566 (with-current-buffer (or buffer (current-buffer))
1567 (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1569 (defun imap-message-append (mailbox article &optional flags date-time buffer)
1570 "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1571 FLAGS and DATE-TIME is currently not used. Return a cons holding
1572 uidvalidity of MAILBOX and UID the newly created article got, or nil
1574 (let ((mailbox (imap-utf7-encode mailbox)))
1575 (with-current-buffer (or buffer (current-buffer))
1576 (and (let ((imap-current-target-mailbox mailbox))
1578 (imap-send-command-wait
1579 (list "APPEND \"" mailbox "\" " article))))
1580 (imap-message-appenduid-1 mailbox)))))
1582 (defun imap-body-lines (body)
1583 "Return number of lines in article by looking at the mime bodystructure BODY."
1585 (if (stringp (car body))
1586 (cond ((and (string= (upcase (car body)) "TEXT")
1587 (numberp (nth 7 body)))
1589 ((and (string= (upcase (car body)) "MESSAGE")
1590 (numberp (nth 9 body)))
1593 (apply '+ (mapcar 'imap-body-lines body)))
1596 (defun imap-envelope-from (from)
1597 "Return a from string line."
1599 (concat (aref from 0)
1600 (if (aref from 0) " <")
1604 (if (aref from 0) ">"))))
1607 ;; Internal functions.
1609 (defun imap-add-callback (tag func)
1610 (setq imap-callbacks (append (list (cons tag func)) imap-callbacks)))
1612 (defun imap-send-command-1 (cmdstr)
1613 (setq cmdstr (concat cmdstr imap-client-eol))
1615 (with-current-buffer (get-buffer-create imap-log-buffer)
1616 (imap-disable-multibyte)
1617 (buffer-disable-undo)
1618 (goto-char (point-max))
1620 (process-send-string imap-process cmdstr))
1622 (defun imap-send-command (command &optional buffer)
1623 (with-current-buffer (or buffer (current-buffer))
1624 (if (not (listp command)) (setq command (list command)))
1625 (let ((tag (setq imap-tag (1+ imap-tag)))
1627 (setq cmdstr (concat (number-to-string imap-tag) " "))
1628 (while (setq cmd (pop command))
1629 (cond ((stringp cmd)
1630 (setq cmdstr (concat cmdstr cmd)))
1632 (let ((eol imap-client-eol)
1633 (calcfirst imap-calculate-literal-size-first)
1635 (with-current-buffer cmd
1637 (setq size (buffer-size)))
1638 (when (not (equal eol "\r\n"))
1639 ;; XXX modifies buffer!
1640 (goto-char (point-min))
1641 (while (search-forward "\r\n" nil t)
1642 (replace-match eol)))
1644 (setq size (buffer-size))))
1646 (concat cmdstr (format "{%d}" size))))
1649 (imap-send-command-1 cmdstr)
1651 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1652 (setq command nil) ;; abort command if no cont-req
1653 (let ((process imap-process)
1654 (stream imap-stream)
1655 (eol imap-client-eol))
1656 (with-current-buffer cmd
1658 (with-current-buffer (get-buffer-create
1660 (imap-disable-multibyte)
1661 (buffer-disable-undo)
1662 (goto-char (point-max))
1663 (insert-buffer-substring cmd)))
1664 (process-send-region process (point-min)
1666 (process-send-string process imap-client-eol))))
1667 (setq imap-continuation nil)))
1669 (imap-send-command-1 cmdstr)
1672 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1673 (setq command nil) ;; abort command if no cont-req
1674 (setq command (cons (funcall cmd imap-continuation)
1676 (setq imap-continuation nil)))
1678 (error "Unknown command type"))))
1680 (imap-send-command-1 cmdstr))
1683 (defun imap-wait-for-tag (tag &optional buffer)
1684 (with-current-buffer (or buffer (current-buffer))
1685 (let (imap-have-messaged)
1686 (while (and (null imap-continuation)
1687 (memq (process-status imap-process) '(open run))
1688 (< imap-reached-tag tag))
1689 (let ((len (/ (point-max) 1024))
1692 (setq imap-have-messaged t)
1693 (message "imap read: %dk" len))
1694 (accept-process-output imap-process 1)))
1695 (when imap-have-messaged
1697 (and (memq (process-status imap-process) '(open run))
1698 (or (assq tag imap-failed-tags)
1699 (if imap-continuation
1703 (defun imap-sentinel (process string)
1704 (delete-process process))
1706 (defun imap-find-next-line ()
1707 "Return point at end of current line, taking into account literals.
1708 Return nil if no complete line has arrived."
1709 (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
1712 (if (match-string 1)
1713 (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1715 (goto-char (+ (point) (string-to-number (match-string 1))))
1716 (imap-find-next-line))
1719 (defun imap-arrival-filter (proc string)
1720 "IMAP process filter."
1721 (with-current-buffer (process-buffer proc)
1722 (goto-char (point-max))
1725 (with-current-buffer (get-buffer-create imap-log-buffer)
1726 (imap-disable-multibyte)
1727 (buffer-disable-undo)
1728 (goto-char (point-max))
1731 (goto-char (point-min))
1732 (while (setq end (imap-find-next-line))
1734 (narrow-to-region (point-min) end)
1735 (delete-backward-char (length imap-server-eol))
1736 (goto-char (point-min))
1738 (cond ((eq imap-state 'initial)
1739 (imap-parse-greeting))
1740 ((or (eq imap-state 'auth)
1741 (eq imap-state 'nonauth)
1742 (eq imap-state 'selected)
1743 (eq imap-state 'examine))
1744 (imap-parse-response))
1746 (message "Unknown state %s in arrival filter"
1748 (delete-region (point-min) (point-max))))))))
1753 (defsubst imap-forward ()
1754 (or (eobp) (forward-char)))
1757 ;; ; Unsigned 32-bit integer
1758 ;; ; (0 <= n < 4,294,967,296)
1760 (defsubst imap-parse-number ()
1761 (when (looking-at "[0-9]+")
1763 (string-to-number (match-string 0))
1764 (goto-char (match-end 0)))))
1766 ;; literal = "{" number "}" CRLF *CHAR8
1767 ;; ; Number represents the number of CHAR8s
1769 (defsubst imap-parse-literal ()
1770 (when (looking-at "{\\([0-9]+\\)}\r\n")
1771 (let ((pos (match-end 0))
1772 (len (string-to-number (match-string 1))))
1773 (if (< (point-max) (+ pos len))
1775 (goto-char (+ pos len))
1776 (buffer-substring pos (+ pos len))))))
1778 ;; string = quoted / literal
1780 ;; quoted = DQUOTE *QUOTED-CHAR DQUOTE
1782 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
1783 ;; "\" quoted-specials
1785 ;; quoted-specials = DQUOTE / "\"
1787 ;; TEXT-CHAR = <any CHAR except CR and LF>
1789 (defsubst imap-parse-string ()
1790 (cond ((eq (char-after) ?\")
1792 (let ((p (point)) (name ""))
1793 (skip-chars-forward "^\"\\\\")
1794 (setq name (buffer-substring p (point)))
1795 (while (eq (char-after) ?\\)
1796 (setq p (1+ (point)))
1798 (skip-chars-forward "^\"\\\\")
1799 (setq name (concat name (buffer-substring p (point)))))
1802 ((eq (char-after) ?{)
1803 (imap-parse-literal))))
1807 (defsubst imap-parse-nil ()
1808 (if (looking-at "NIL")
1809 (goto-char (match-end 0))))
1811 ;; nstring = string / nil
1813 (defsubst imap-parse-nstring ()
1814 (or (imap-parse-string)
1815 (and (imap-parse-nil)
1818 ;; astring = atom / string
1820 ;; atom = 1*ATOM-CHAR
1822 ;; ATOM-CHAR = <any CHAR except atom-specials>
1824 ;; atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards /
1827 ;; list-wildcards = "%" / "*"
1829 ;; quoted-specials = DQUOTE / "\"
1831 (defsubst imap-parse-astring ()
1832 (or (imap-parse-string)
1833 (buffer-substring (point)
1834 (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
1835 (goto-char (1- (match-end 0)))
1839 ;; address = "(" addr-name SP addr-adl SP addr-mailbox SP
1842 ;; addr-adl = nstring
1843 ;; ; Holds route from [RFC-822] route-addr if
1846 ;; addr-host = nstring
1847 ;; ; nil indicates [RFC-822] group syntax.
1848 ;; ; Otherwise, holds [RFC-822] domain name
1850 ;; addr-mailbox = nstring
1851 ;; ; nil indicates end of [RFC-822] group; if
1852 ;; ; non-nil and addr-host is nil, holds
1853 ;; ; [RFC-822] group name.
1854 ;; ; Otherwise, holds [RFC-822] local-part
1855 ;; ; after removing [RFC-822] quoting
1857 ;; addr-name = nstring
1858 ;; ; If non-nil, holds phrase from [RFC-822]
1859 ;; ; mailbox after removing [RFC-822] quoting
1862 (defsubst imap-parse-address ()
1864 (when (eq (char-after) ?\()
1866 (setq address (vector (prog1 (imap-parse-nstring)
1868 (prog1 (imap-parse-nstring)
1870 (prog1 (imap-parse-nstring)
1872 (imap-parse-nstring)))
1873 (when (eq (char-after) ?\))
1877 ;; address-list = "(" 1*address ")" / nil
1881 (defsubst imap-parse-address-list ()
1882 (if (eq (char-after) ?\()
1883 (let (address addresses)
1885 (while (and (not (eq (char-after) ?\)))
1886 ;; next line for MS Exchange bug
1887 (progn (and (eq (char-after) ? ) (imap-forward)) t)
1888 (setq address (imap-parse-address)))
1889 (setq addresses (cons address addresses)))
1890 (when (eq (char-after) ?\))
1892 (nreverse addresses)))
1893 (assert (imap-parse-nil) t "In imap-parse-address-list")))
1895 ;; mailbox = "INBOX" / astring
1896 ;; ; INBOX is case-insensitive. All case variants of
1897 ;; ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
1898 ;; ; not as an astring. An astring which consists of
1899 ;; ; the case-insensitive sequence "I" "N" "B" "O" "X"
1900 ;; ; is considered to be INBOX and not an astring.
1901 ;; ; Refer to section 5.1 for further
1902 ;; ; semantic details of mailbox names.
1904 (defsubst imap-parse-mailbox ()
1905 (let ((mailbox (imap-parse-astring)))
1906 (if (string-equal "INBOX" (upcase mailbox))
1910 ;; greeting = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
1912 ;; resp-cond-auth = ("OK" / "PREAUTH") SP resp-text
1913 ;; ; Authentication condition
1915 ;; resp-cond-bye = "BYE" SP resp-text
1917 (defun imap-parse-greeting ()
1918 "Parse a IMAP greeting."
1919 (cond ((looking-at "\\* OK ")
1920 (setq imap-state 'nonauth))
1921 ((looking-at "\\* PREAUTH ")
1922 (setq imap-state 'auth))
1923 ((looking-at "\\* BYE ")
1924 (setq imap-state 'closed))))
1926 ;; response = *(continue-req / response-data) response-done
1928 ;; continue-req = "+" SP (resp-text / base64) CRLF
1930 ;; response-data = "*" SP (resp-cond-state / resp-cond-bye /
1931 ;; mailbox-data / message-data / capability-data) CRLF
1933 ;; response-done = response-tagged / response-fatal
1935 ;; response-fatal = "*" SP resp-cond-bye CRLF
1936 ;; ; Server closes connection immediately
1938 ;; response-tagged = tag SP resp-cond-state CRLF
1940 ;; resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
1941 ;; ; Status condition
1943 ;; resp-cond-bye = "BYE" SP resp-text
1945 ;; mailbox-data = "FLAGS" SP flag-list /
1946 ;; "LIST" SP mailbox-list /
1947 ;; "LSUB" SP mailbox-list /
1948 ;; "SEARCH" *(SP nz-number) /
1949 ;; "STATUS" SP mailbox SP "("
1950 ;; [status-att SP number *(SP status-att SP number)] ")" /
1951 ;; number SP "EXISTS" /
1952 ;; number SP "RECENT"
1954 ;; message-data = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
1956 ;; capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
1958 ;; ; IMAP4rev1 servers which offer RFC 1730
1959 ;; ; compatibility MUST list "IMAP4" as the first
1962 (defun imap-parse-response ()
1963 "Parse a IMAP command response."
1965 (case (setq token (read (current-buffer)))
1966 (+ (setq imap-continuation
1967 (or (buffer-substring (min (point-max) (1+ (point)))
1970 (* (case (prog1 (setq token (read (current-buffer)))
1972 (OK (imap-parse-resp-text))
1973 (NO (imap-parse-resp-text))
1974 (BAD (imap-parse-resp-text))
1975 (BYE (imap-parse-resp-text))
1976 (FLAGS (imap-mailbox-put 'flags (imap-parse-flag-list)))
1977 (LIST (imap-parse-data-list 'list))
1978 (LSUB (imap-parse-data-list 'lsub))
1979 (SEARCH (imap-mailbox-put
1981 (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
1982 (STATUS (imap-parse-status))
1983 (CAPABILITY (setq imap-capability
1984 (read (concat "(" (upcase (buffer-substring
1985 (point) (point-max)))
1987 (ACL (imap-parse-acl))
1988 (t (case (prog1 (read (current-buffer))
1990 (EXISTS (imap-mailbox-put 'exists token))
1991 (RECENT (imap-mailbox-put 'recent token))
1993 (FETCH (imap-parse-fetch token))
1994 (t (message "Garbage: %s" (buffer-string)))))))
1996 (if (not (integerp token))
1997 (message "Garbage: %s" (buffer-string))
1998 (case (prog1 (setq status (read (current-buffer)))
2001 (setq imap-reached-tag (max imap-reached-tag token))
2002 (imap-parse-resp-text)))
2004 (setq imap-reached-tag (max imap-reached-tag token))
2006 (imap-parse-resp-text))
2008 (when (eq (char-after) ?\[)
2009 (setq code (buffer-substring (point)
2010 (search-forward "]")))
2012 (setq text (buffer-substring (point) (point-max)))
2013 (push (list token status code text)
2014 imap-failed-tags))))
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) imap-failed-tags)
2026 (error "Internal error, tag %s status %s code %s text %s"
2027 token status code text))))
2028 (t (message "Garbage: %s" (buffer-string))))
2029 (when (assq token imap-callbacks)
2030 (funcall (cdr (assq token imap-callbacks)) token status)
2031 (setq imap-callbacks
2032 (imap-remassoc token imap-callbacks)))))))))
2034 ;; resp-text = ["[" resp-text-code "]" SP] text
2036 ;; text = 1*TEXT-CHAR
2038 ;; TEXT-CHAR = <any CHAR except CR and LF>
2040 (defun imap-parse-resp-text ()
2041 (imap-parse-resp-text-code))
2043 ;; resp-text-code = "ALERT" /
2044 ;; "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
2045 ;; "NEWNAME" SP string SP string /
2047 ;; "PERMANENTFLAGS" SP "("
2048 ;; [flag-perm *(SP flag-perm)] ")" /
2052 ;; "UIDNEXT" SP nz-number /
2053 ;; "UIDVALIDITY" SP nz-number /
2054 ;; "UNSEEN" SP nz-number /
2055 ;; resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
2057 ;; resp_code_apnd = "APPENDUID" SPACE nz_number SPACE uniqueid
2059 ;; resp_code_copy = "COPYUID" SPACE nz_number SPACE set SPACE set
2061 ;; set = sequence-num / (sequence-num ":" sequence-num) /
2063 ;; ; Identifies a set of messages. For message
2064 ;; ; sequence numbers, these are consecutive
2065 ;; ; numbers from 1 to the number of messages in
2067 ;; ; Comma delimits individual numbers, colon
2068 ;; ; delimits between two numbers inclusive.
2069 ;; ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
2070 ;; ; 14,15 for a mailbox with 15 messages.
2072 ;; sequence-num = nz-number / "*"
2073 ;; ; * is the largest number in use. For message
2074 ;; ; sequence numbers, it is the number of messages
2075 ;; ; in the mailbox. For unique identifiers, it is
2076 ;; ; the unique identifier of the last message in
2079 ;; flag-perm = flag / "\*"
2081 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2082 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2083 ;; ; Does not include "\Recent"
2085 ;; flag-extension = "\" atom
2086 ;; ; Future expansion. Client implementations
2087 ;; ; MUST accept flag-extension flags. Server
2088 ;; ; implementations MUST NOT generate
2089 ;; ; flag-extension flags except as defined by
2090 ;; ; future standard or standards-track
2091 ;; ; revisions of this specification.
2093 ;; flag-keyword = atom
2095 ;; resp-text-atom = 1*<any ATOM-CHAR except "]">
2097 (defun imap-parse-resp-text-code ()
2098 ;; xxx next line for stalker communigate pro 3.3.1 bug
2099 (when (looking-at " \\[")
2101 (when (eq (char-after) ?\[)
2103 (cond ((search-forward "PERMANENTFLAGS " nil t)
2104 (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2105 ((search-forward "UIDNEXT " nil t)
2106 (imap-mailbox-put 'uidnext (read (current-buffer))))
2107 ((search-forward "UNSEEN " nil t)
2108 (imap-mailbox-put 'unseen (read (current-buffer))))
2109 ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2110 (imap-mailbox-put 'uidvalidity (match-string 1)))
2111 ((search-forward "READ-ONLY" nil t)
2112 (imap-mailbox-put 'read-only t))
2113 ((search-forward "NEWNAME " nil t)
2114 (let (oldname newname)
2115 (setq oldname (imap-parse-string))
2117 (setq newname (imap-parse-string))
2118 (imap-mailbox-put 'newname newname oldname)))
2119 ((search-forward "TRYCREATE" nil t)
2120 (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2121 ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2122 (imap-mailbox-put 'appenduid
2123 (list (match-string 1)
2124 (string-to-number (match-string 2)))
2125 imap-current-target-mailbox))
2126 ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2127 (imap-mailbox-put 'copyuid (list (match-string 1)
2130 imap-current-target-mailbox))
2131 ((search-forward "ALERT] " nil t)
2132 (message "Imap server %s information: %s" imap-server
2133 (buffer-substring (point) (point-max)))))))
2135 ;; mailbox-list = "(" [mbx-list-flags] ")" SP
2136 ;; (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2138 ;; mbx-list-flags = *(mbx-list-oflag SP) mbx-list-sflag
2139 ;; *(SP mbx-list-oflag) /
2140 ;; mbx-list-oflag *(SP mbx-list-oflag)
2142 ;; mbx-list-oflag = "\Noinferiors" / flag-extension
2143 ;; ; Other flags; multiple possible per LIST response
2145 ;; mbx-list-sflag = "\Noselect" / "\Marked" / "\Unmarked"
2146 ;; ; Selectability flags; only one per LIST response
2148 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2149 ;; "\" quoted-specials
2151 ;; quoted-specials = DQUOTE / "\"
2153 (defun imap-parse-data-list (type)
2154 (let (flags delimiter mailbox)
2155 (setq flags (imap-parse-flag-list))
2156 (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2157 (setq delimiter (match-string 1))
2158 (goto-char (1+ (match-end 0)))
2159 (when (setq mailbox (imap-parse-mailbox))
2160 (imap-mailbox-put type t mailbox)
2161 (imap-mailbox-put 'list-flags flags mailbox)
2162 (imap-mailbox-put 'delimiter delimiter mailbox)))))
2164 ;; msg_att ::= "(" 1#("ENVELOPE" SPACE envelope /
2165 ;; "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2166 ;; "INTERNALDATE" SPACE date_time /
2167 ;; "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2168 ;; "RFC822.SIZE" SPACE number /
2169 ;; "BODY" ["STRUCTURE"] SPACE body /
2170 ;; "BODY" section ["<" number ">"] SPACE nstring /
2171 ;; "UID" SPACE uniqueid) ")"
2173 ;; date_time ::= <"> date_day_fixed "-" date_month "-" date_year
2174 ;; SPACE time SPACE zone <">
2176 ;; section ::= "[" [section_text / (nz_number *["." nz_number]
2177 ;; ["." (section_text / "MIME")])] "]"
2179 ;; section_text ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2180 ;; SPACE header_list / "TEXT"
2182 ;; header_fld_name ::= astring
2184 ;; header_list ::= "(" 1#header_fld_name ")"
2186 (defsubst imap-parse-header-list ()
2187 (when (eq (char-after) ?\()
2189 (while (not (eq (char-after) ?\)))
2191 (push (imap-parse-astring) strlist))
2193 (nreverse strlist))))
2195 (defsubst imap-parse-fetch-body-section ()
2197 (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2198 (if (eq (char-before) ? )
2200 (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2201 (search-forward "]" nil t))
2204 (defun imap-parse-fetch (response)
2205 (when (eq (char-after) ?\()
2206 (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2207 rfc822size body bodydetail bodystructure flags-empty)
2208 (while (not (eq (char-after) ?\)))
2210 (let ((token (read (current-buffer))))
2212 (cond ((eq token 'UID)
2213 (setq uid (condition-case ()
2214 (read (current-buffer))
2217 (setq flags (imap-parse-flag-list))
2219 (setq flags-empty 't)))
2220 ((eq token 'ENVELOPE)
2221 (setq envelope (imap-parse-envelope)))
2222 ((eq token 'INTERNALDATE)
2223 (setq internaldate (imap-parse-string)))
2225 (setq rfc822 (imap-parse-nstring)))
2226 ((eq token 'RFC822.HEADER)
2227 (setq rfc822header (imap-parse-nstring)))
2228 ((eq token 'RFC822.TEXT)
2229 (setq rfc822text (imap-parse-nstring)))
2230 ((eq token 'RFC822.SIZE)
2231 (setq rfc822size (read (current-buffer))))
2233 (if (eq (char-before) ?\[)
2235 (upcase (imap-parse-fetch-body-section))
2236 (and (eq (char-after) ?<)
2237 (buffer-substring (1+ (point))
2238 (search-forward ">" nil t)))
2239 (progn (imap-forward)
2240 (imap-parse-nstring)))
2242 (setq body (imap-parse-body))))
2243 ((eq token 'BODYSTRUCTURE)
2244 (setq bodystructure (imap-parse-body))))))
2246 (setq imap-current-message uid)
2247 (imap-message-put uid 'UID uid)
2248 (and (or flags flags-empty) (imap-message-put uid 'FLAGS flags))
2249 (and envelope (imap-message-put uid 'ENVELOPE envelope))
2250 (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2251 (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2252 (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2253 (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2254 (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2255 (and body (imap-message-put uid 'BODY body))
2256 (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2257 (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2258 (run-hooks 'imap-fetch-data-hook)))))
2260 ;; mailbox-data = ...
2261 ;; "STATUS" SP mailbox SP "("
2262 ;; [status-att SP number
2263 ;; *(SP status-att SP number)] ")"
2266 ;; status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2269 (defun imap-parse-status ()
2270 (let ((mailbox (imap-parse-mailbox)))
2271 (when (and mailbox (search-forward "(" nil t))
2272 (while (not (eq (char-after) ?\)))
2273 (let ((token (read (current-buffer))))
2274 (cond ((eq token 'MESSAGES)
2275 (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2277 (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2278 ((eq token 'UIDNEXT)
2279 (imap-mailbox-put 'uidnext (read (current-buffer)) mailbox))
2280 ((eq token 'UIDVALIDITY)
2281 (and (looking-at " \\([0-9]+\\)")
2282 (imap-mailbox-put 'uidvalidity (match-string 1) mailbox)
2283 (goto-char (match-end 1))))
2285 (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2287 (message "Unknown status data %s in mailbox %s ignored"
2288 token mailbox))))))))
2290 ;; acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2293 ;; identifier ::= astring
2295 ;; rights ::= astring
2297 (defun imap-parse-acl ()
2298 (let ((mailbox (imap-parse-mailbox))
2299 identifier rights acl)
2300 (while (eq (char-after) ?\ )
2302 (setq identifier (imap-parse-astring))
2304 (setq rights (imap-parse-astring))
2305 (setq acl (append acl (list (cons identifier rights)))))
2306 (imap-mailbox-put 'acl acl mailbox)))
2308 ;; flag-list = "(" [flag *(SP flag)] ")"
2310 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2311 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2312 ;; ; Does not include "\Recent"
2314 ;; flag-keyword = atom
2316 ;; flag-extension = "\" atom
2317 ;; ; Future expansion. Client implementations
2318 ;; ; MUST accept flag-extension flags. Server
2319 ;; ; implementations MUST NOT generate
2320 ;; ; flag-extension flags except as defined by
2321 ;; ; future standard or standards-track
2322 ;; ; revisions of this specification.
2324 (defun imap-parse-flag-list ()
2325 (let (flag-list start)
2326 (assert (eq (char-after) ?\() t "In imap-parse-flag-list")
2327 (while (and (not (eq (char-after) ?\)))
2330 ;; next line for Courier IMAP bug.
2331 (skip-chars-forward " ")
2333 (> (skip-chars-forward "^ )" (imap-point-at-eol)) 0))
2334 (push (buffer-substring start (point)) flag-list))
2335 (assert (eq (char-after) ?\)) t "In imap-parse-flag-list")
2337 (nreverse flag-list)))
2339 ;; envelope = "(" env-date SP env-subject SP env-from SP env-sender SP
2340 ;; env-reply-to SP env-to SP env-cc SP env-bcc SP
2341 ;; env-in-reply-to SP env-message-id ")"
2343 ;; env-bcc = "(" 1*address ")" / nil
2345 ;; env-cc = "(" 1*address ")" / nil
2347 ;; env-date = nstring
2349 ;; env-from = "(" 1*address ")" / nil
2351 ;; env-in-reply-to = nstring
2353 ;; env-message-id = nstring
2355 ;; env-reply-to = "(" 1*address ")" / nil
2357 ;; env-sender = "(" 1*address ")" / nil
2359 ;; env-subject = nstring
2361 ;; env-to = "(" 1*address ")" / nil
2363 (defun imap-parse-envelope ()
2364 (when (eq (char-after) ?\()
2366 (vector (prog1 (imap-parse-nstring) ;; date
2368 (prog1 (imap-parse-nstring) ;; subject
2370 (prog1 (imap-parse-address-list) ;; from
2372 (prog1 (imap-parse-address-list) ;; sender
2374 (prog1 (imap-parse-address-list) ;; reply-to
2376 (prog1 (imap-parse-address-list) ;; to
2378 (prog1 (imap-parse-address-list) ;; cc
2380 (prog1 (imap-parse-address-list) ;; bcc
2382 (prog1 (imap-parse-nstring) ;; in-reply-to
2384 (prog1 (imap-parse-nstring) ;; message-id
2387 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2389 (defsubst imap-parse-string-list ()
2390 (cond ((eq (char-after) ?\() ;; body-fld-param
2393 (while (setq str (imap-parse-string))
2395 ;; buggy stalker communigate pro 3.0 doesn't print SPC
2396 ;; between body-fld-param's sometimes
2397 (or (eq (char-after) ?\")
2399 (nreverse strlist)))
2403 ;; body-extension = nstring / number /
2404 ;; "(" body-extension *(SP body-extension) ")"
2405 ;; ; Future expansion. Client implementations
2406 ;; ; MUST accept body-extension fields. Server
2407 ;; ; implementations MUST NOT generate
2408 ;; ; body-extension fields except as defined by
2409 ;; ; future standard or standards-track
2410 ;; ; revisions of this specification.
2412 (defun imap-parse-body-extension ()
2413 (if (eq (char-after) ?\()
2416 (push (imap-parse-body-extension) b-e)
2417 (while (eq (char-after) ?\ )
2419 (push (imap-parse-body-extension) b-e))
2420 (assert (eq (char-after) ?\)) t "In imap-parse-body-extension")
2423 (or (imap-parse-number)
2424 (imap-parse-nstring))))
2426 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2427 ;; *(SP body-extension)]]
2428 ;; ; MUST NOT be returned on non-extensible
2431 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2432 ;; *(SP body-extension)]]
2433 ;; ; MUST NOT be returned on non-extensible
2436 (defsubst imap-parse-body-ext ()
2438 (when (eq (char-after) ?\ ) ;; body-fld-dsp
2441 (if (eq (char-after) ?\()
2444 (push (imap-parse-string) dsp)
2446 (push (imap-parse-string-list) dsp)
2448 (assert (imap-parse-nil) t "In imap-parse-body-ext"))
2449 (push (nreverse dsp) ext))
2450 (when (eq (char-after) ?\ ) ;; body-fld-lang
2452 (if (eq (char-after) ?\()
2453 (push (imap-parse-string-list) ext)
2454 (push (imap-parse-nstring) ext))
2455 (while (eq (char-after) ?\ ) ;; body-extension
2457 (setq ext (append (imap-parse-body-extension) ext)))))
2460 ;; body = "(" body-type-1part / body-type-mpart ")"
2462 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2463 ;; *(SP body-extension)]]
2464 ;; ; MUST NOT be returned on non-extensible
2467 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2468 ;; *(SP body-extension)]]
2469 ;; ; MUST NOT be returned on non-extensible
2472 ;; body-fields = body-fld-param SP body-fld-id SP body-fld-desc SP
2473 ;; body-fld-enc SP body-fld-octets
2475 ;; body-fld-desc = nstring
2477 ;; body-fld-dsp = "(" string SP body-fld-param ")" / nil
2479 ;; body-fld-enc = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2480 ;; "QUOTED-PRINTABLE") DQUOTE) / string
2482 ;; body-fld-id = nstring
2484 ;; body-fld-lang = nstring / "(" string *(SP string) ")"
2486 ;; body-fld-lines = number
2488 ;; body-fld-md5 = nstring
2490 ;; body-fld-octets = number
2492 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2494 ;; body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2495 ;; [SP body-ext-1part]
2497 ;; body-type-basic = media-basic SP body-fields
2498 ;; ; MESSAGE subtype MUST NOT be "RFC822"
2500 ;; body-type-msg = media-message SP body-fields SP envelope
2501 ;; SP body SP body-fld-lines
2503 ;; body-type-text = media-text SP body-fields SP body-fld-lines
2505 ;; body-type-mpart = 1*body SP media-subtype
2506 ;; [SP body-ext-mpart]
2508 ;; media-basic = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2509 ;; "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2510 ;; ; Defined in [MIME-IMT]
2512 ;; media-message = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2513 ;; ; Defined in [MIME-IMT]
2515 ;; media-subtype = string
2516 ;; ; Defined in [MIME-IMT]
2518 ;; media-text = DQUOTE "TEXT" DQUOTE SP media-subtype
2519 ;; ; Defined in [MIME-IMT]
2521 (defun imap-parse-body ()
2523 (when (eq (char-after) ?\()
2525 (if (eq (char-after) ?\()
2527 (while (and (eq (char-after) ?\()
2528 (setq subbody (imap-parse-body)))
2529 ;; buggy stalker communigate pro 3.0 insert a SPC between
2530 ;; parts in multiparts
2531 (when (and (eq (char-after) ?\ )
2532 (eq (char-after (1+ (point))) ?\())
2534 (push subbody body))
2536 (push (imap-parse-string) body) ;; media-subtype
2537 (when (eq (char-after) ?\ ) ;; body-ext-mpart:
2539 (if (eq (char-after) ?\() ;; body-fld-param
2540 (push (imap-parse-string-list) body)
2541 (push (and (imap-parse-nil) nil) body))
2543 (append (imap-parse-body-ext) body))) ;; body-ext-...
2544 (assert (eq (char-after) ?\)) t "In imap-parse-body")
2548 (push (imap-parse-string) body) ;; media-type
2550 (push (imap-parse-string) body) ;; media-subtype
2552 ;; next line for Sun SIMS bug
2553 (and (eq (char-after) ? ) (imap-forward))
2554 (if (eq (char-after) ?\() ;; body-fld-param
2555 (push (imap-parse-string-list) body)
2556 (push (and (imap-parse-nil) nil) body))
2558 (push (imap-parse-nstring) body) ;; body-fld-id
2560 (push (imap-parse-nstring) body) ;; body-fld-desc
2562 ;; next `or' for Sun SIMS bug, it regard body-fld-enc as a
2563 ;; nstring and return nil instead of defaulting back to 7BIT
2564 ;; as the standard says.
2565 (push (or (imap-parse-nstring) "7BIT") body) ;; body-fld-enc
2567 (push (imap-parse-number) body) ;; body-fld-octets
2569 ;; ok, we're done parsing the required parts, what comes now is one
2572 ;; envelope (then we're parsing body-type-msg)
2573 ;; body-fld-lines (then we're parsing body-type-text)
2574 ;; body-ext-1part (then we're parsing body-type-basic)
2576 ;; the problem is that the two first are in turn optionally followed
2577 ;; by the third. So we parse the first two here (if there are any)...
2579 (when (eq (char-after) ?\ )
2582 (cond ((eq (char-after) ?\() ;; body-type-msg:
2583 (push (imap-parse-envelope) body) ;; envelope
2585 (push (imap-parse-body) body) ;; body
2586 ;; buggy stalker communigate pro 3.0 doesn't print
2587 ;; number of lines in message/rfc822 attachment
2588 (if (eq (char-after) ?\))
2591 (push (imap-parse-number) body))) ;; body-fld-lines
2592 ((setq lines (imap-parse-number)) ;; body-type-text:
2593 (push lines body)) ;; body-fld-lines
2595 (backward-char))))) ;; no match...
2597 ;; ...and then parse the third one here...
2599 (when (eq (char-after) ?\ ) ;; body-ext-1part:
2601 (push (imap-parse-nstring) body) ;; body-fld-md5
2602 (setq body (append (imap-parse-body-ext) body))) ;; body-ext-1part..
2604 (assert (eq (char-after) ?\)) t "In imap-parse-body 2")
2608 (when imap-debug ; (untrace-all)
2610 (buffer-disable-undo (get-buffer-create imap-debug-buffer))
2611 (mapcar (lambda (f) (trace-function-background f imap-debug-buffer))
2623 imap-interactive-login
2639 imap-send-command-wait
2644 imap-current-mailbox
2645 imap-current-mailbox-p-1
2646 imap-current-mailbox-p
2647 imap-mailbox-select-1
2649 imap-mailbox-examine-1
2650 imap-mailbox-examine
2651 imap-mailbox-unselect
2652 imap-mailbox-expunge
2654 imap-mailbox-create-1
2660 imap-mailbox-subscribe
2661 imap-mailbox-unsubscribe
2663 imap-mailbox-acl-get
2664 imap-mailbox-acl-set
2665 imap-mailbox-acl-delete
2666 imap-current-message
2667 imap-list-to-message-set
2674 imap-message-flag-permanent-p
2675 imap-message-flags-set
2676 imap-message-flags-del
2677 imap-message-flags-add
2678 imap-message-copyuid-1
2679 imap-message-copyuid
2681 imap-message-appenduid-1
2682 imap-message-appenduid
2694 imap-parse-resp-text
2695 imap-parse-resp-text-code
2696 imap-parse-data-list
2700 imap-parse-flag-list
2702 imap-parse-body-extension
2708 ;;; imap.el ends here