1 ;;; imap.el --- imap library
2 ;; Copyright (C) 1998, 1999, 2000, 2001
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)))
604 (ignore-errors (require 'ssl))
605 (while (and (not done) (setq cmd (pop cmds)))
606 (message "imap: Opening SSL connection with `%s'..." cmd)
607 (let* ((port (or port imap-default-ssl-port))
608 (coding-system-for-read imap-coding-system-for-read)
609 (coding-system-for-write imap-coding-system-for-write)
610 (ssl-program-name shell-file-name)
611 (ssl-program-arguments
612 (list shell-command-switch
613 (format-spec cmd (format-spec-make
615 ?p (number-to-string port)))))
617 (when (setq process (ignore-errors (open-ssl-stream
618 name buffer server port)))
619 (with-current-buffer buffer
620 (goto-char (point-min))
621 (while (and (memq (process-status process) '(open run))
622 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
623 (goto-char (point-max))
625 (not (imap-parse-greeting)))
626 (accept-process-output process 1)
629 (with-current-buffer (get-buffer-create imap-log-buffer)
630 (imap-disable-multibyte)
631 (buffer-disable-undo)
632 (goto-char (point-max))
633 (insert-buffer-substring buffer)))
635 (when (memq (process-status process) '(open run))
636 (setq done process))))))
639 (message "imap: Opening SSL connection with `%s'...done" cmd)
641 (message "imap: Opening SSL connection with `%s'...failed" cmd)
644 (defun imap-network-p (buffer)
647 (defun imap-network-open (name buffer server port)
648 (let* ((port (or port imap-default-port))
649 (coding-system-for-read imap-coding-system-for-read)
650 (coding-system-for-write imap-coding-system-for-write)
651 (process (open-network-stream name buffer server port)))
653 (while (and (memq (process-status process) '(open run))
654 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
655 (goto-char (point-min))
656 (not (imap-parse-greeting)))
657 (accept-process-output process 1)
660 (with-current-buffer (get-buffer-create imap-log-buffer)
661 (imap-disable-multibyte)
662 (buffer-disable-undo)
663 (goto-char (point-max))
664 (insert-buffer-substring buffer)))
665 (when (memq (process-status process) '(open run))
668 (defun imap-shell-p (buffer)
671 (defun imap-shell-open (name buffer server port)
672 (let ((cmds imap-shell-program)
674 (while (and (not done) (setq cmd (pop cmds)))
675 (message "imap: Opening IMAP connection with `%s'..." cmd)
676 (setq imap-client-eol "\n")
677 (let* ((port (or port imap-default-port))
678 (coding-system-for-read imap-coding-system-for-read)
679 (coding-system-for-write imap-coding-system-for-write)
680 (process (start-process
681 name buffer shell-file-name shell-command-switch
687 ?p (number-to-string port)
688 ?l imap-default-user)))))
690 (while (and (memq (process-status process) '(open run))
691 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
692 (goto-char (point-min))
693 (not (imap-parse-greeting)))
694 (accept-process-output process 1)
697 (with-current-buffer (get-buffer-create imap-log-buffer)
698 (imap-disable-multibyte)
699 (buffer-disable-undo)
700 (goto-char (point-max))
701 (insert-buffer-substring buffer)))
703 (when (memq (process-status process) '(open run))
704 (setq done process)))))
707 (message "imap: Opening IMAP connection with `%s'...done" cmd)
709 (message "imap: Opening IMAP connection with `%s'...failed" cmd)
712 (defun imap-starttls-p (buffer)
713 (and (imap-capability 'STARTTLS buffer)
717 (call-process "starttls"))
720 (defun imap-starttls-open (name buffer server port)
721 (let* ((port (or port imap-default-port))
722 (coding-system-for-read imap-coding-system-for-read)
723 (coding-system-for-write imap-coding-system-for-write)
724 (process (starttls-open-stream name buffer server port))
726 (message "imap: Connecting with STARTTLS...")
728 (while (and (memq (process-status process) '(open run))
729 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
730 (goto-char (point-min))
731 (not (imap-parse-greeting)))
732 (accept-process-output process 1)
735 (with-current-buffer (get-buffer-create imap-log-buffer)
736 (buffer-disable-undo)
737 (goto-char (point-max))
738 (insert-buffer-substring buffer)))
739 (let ((imap-process process))
742 (set-process-filter imap-process 'imap-arrival-filter)
743 (when (and (eq imap-stream 'starttls)
744 (imap-ok-p (imap-send-command-wait "STARTTLS")))
745 (starttls-negotiate imap-process)))
746 (set-process-filter imap-process nil)))
747 (when (memq (process-status process) '(open run))
748 (setq done process)))
751 (message "imap: Connecting with STARTTLS...done")
753 (message "imap: Connecting with STARTTLS...failed")
756 ;; Server functions; authenticator stuff:
758 (defun imap-interactive-login (buffer loginfunc)
759 "Login to server in BUFFER.
760 LOGINFUNC is passed a username and a password, it should return t if
761 it where sucessful authenticating itself to the server, nil otherwise.
762 Returns t if login was successful, nil otherwise."
763 (with-current-buffer buffer
764 (make-local-variable 'imap-username)
765 (make-local-variable 'imap-password)
766 (let (user passwd ret)
767 ;; (condition-case ()
768 (while (or (not user) (not passwd))
769 (setq user (or imap-username
770 (read-from-minibuffer
771 (concat "IMAP username for " imap-server ": ")
772 (or user imap-default-user))))
773 (setq passwd (or imap-password
775 (concat "IMAP password for " user "@"
777 (when (and user passwd)
778 (if (funcall loginfunc user passwd)
782 (if (and (not imap-password)
783 (y-or-n-p "Store password for this session? "))
784 (setq imap-password passwd)))
785 (message "Login failed...")
788 ;; (quit (with-current-buffer buffer
791 ;; (error (with-current-buffer buffer
796 (defun imap-gssapi-auth-p (buffer)
797 (and (imap-capability 'AUTH=GSSAPI buffer)
799 (let (prg (prgs imap-gssapi-program))
800 (while (setq prg (pop prgs))
802 (and (call-process (substring prg 0 (string-match " " prg)))
803 (throw 'imtest-found t))
806 (defun imap-gssapi-auth (buffer)
807 (message "imap: Authenticating using GSSAPI...%s"
808 (if (eq imap-stream 'gssapi) "done" "failed"))
809 (eq imap-stream 'gssapi))
811 (defun imap-kerberos4-auth-p (buffer)
812 (and (imap-capability 'AUTH=KERBEROS_V4 buffer)
814 (let (prg (prgs imap-kerberos4-program))
815 (while (setq prg (pop prgs))
817 (and (call-process (substring prg 0 (string-match " " prg)))
818 (throw 'imtest-found t))
821 (defun imap-kerberos4-auth (buffer)
822 (message "imap: Authenticating using Kerberos 4...%s"
823 (if (eq imap-stream 'kerberos4) "done" "failed"))
824 (eq imap-stream 'kerberos4))
826 (defun imap-cram-md5-p (buffer)
827 (imap-capability 'AUTH=CRAM-MD5 buffer))
829 (defun imap-cram-md5-auth (buffer)
830 "Login to server using the AUTH CRAM-MD5 method."
831 (message "imap: Authenticating using CRAM-MD5...")
832 (let ((done (imap-interactive-login
834 (lambda (user passwd)
836 (imap-send-command-wait
838 "AUTHENTICATE CRAM-MD5"
840 (let* ((decoded (base64-decode-string challenge))
841 (hash (rfc2104-hash 'md5 64 16 passwd decoded))
842 (response (concat user " " hash))
843 (encoded (base64-encode-string response)))
846 (message "imap: Authenticating using CRAM-MD5...done")
847 (message "imap: Authenticating using CRAM-MD5...failed"))))
849 (defun imap-login-p (buffer)
850 (and (not (imap-capability 'LOGINDISABLED buffer))
851 (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
853 (defun imap-login-auth (buffer)
854 "Login to server using the LOGIN command."
855 (message "imap: Plaintext authentication...")
856 (imap-interactive-login buffer
857 (lambda (user passwd)
858 (imap-ok-p (imap-send-command-wait
859 (concat "LOGIN \"" user "\" \""
862 (defun imap-anonymous-p (buffer)
865 (defun imap-anonymous-auth (buffer)
866 (message "imap: Loging in anonymously...")
867 (with-current-buffer buffer
868 (imap-ok-p (imap-send-command-wait
869 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
870 (system-name)) "\"")))))
872 (defun imap-digest-md5-p (buffer)
873 (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
875 (require 'digest-md5)
878 (defun imap-digest-md5-auth (buffer)
879 "Login to server using the AUTH DIGEST-MD5 method."
880 (message "imap: Authenticating using DIGEST-MD5...")
881 (imap-interactive-login
883 (lambda (user passwd)
887 "AUTHENTICATE DIGEST-MD5"
889 (digest-md5-parse-digest-challenge
890 (base64-decode-string challenge))
892 (digest-md5-digest-uri
893 "imap" (digest-md5-challenge 'realm)))
895 (digest-md5-digest-response
896 user passwd digest-uri)))
897 (base64-encode-string response 'no-line-break))))
899 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
901 (setq imap-continuation nil)
902 (imap-send-command-1 "")
903 (imap-ok-p (imap-wait-for-tag tag)))))))
907 (defun imap-open-1 (buffer)
908 (with-current-buffer buffer
910 (setq imap-current-mailbox nil
911 imap-current-message nil
913 imap-process (condition-case ()
914 (funcall (nth 2 (assq imap-stream
916 "imap" buffer imap-server imap-port)
919 (set-process-filter imap-process 'imap-arrival-filter)
920 (set-process-sentinel imap-process 'imap-sentinel)
921 (while (and (eq imap-state 'initial)
922 (memq (process-status imap-process) '(open run)))
923 (message "Waiting for response from %s..." imap-server)
924 (accept-process-output imap-process 1))
925 (message "Waiting for response from %s...done" imap-server)
926 (and (memq (process-status imap-process) '(open run))
929 (defun imap-open (server &optional port stream auth buffer)
930 "Open a IMAP connection to host SERVER at PORT returning a buffer.
931 If PORT is unspecified, a default value is used (143 except
932 for SSL which use 993).
933 STREAM indicates the stream to use, see `imap-streams' for available
934 streams. If nil, it choices the best stream the server is capable of.
935 AUTH indicates authenticator to use, see `imap-authenticators' for
936 available authenticators. If nil, it choices the best stream the
937 server is capable of.
938 BUFFER can be a buffer or a name of a buffer, which is created if
939 necessery. If nil, the buffer name is generated."
940 (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
941 (with-current-buffer (get-buffer-create buffer)
942 (if (imap-opened buffer)
944 (mapcar 'make-local-variable imap-local-variables)
945 (imap-disable-multibyte)
946 (buffer-disable-undo)
947 (setq imap-server (or server imap-server))
948 (setq imap-port (or port imap-port))
949 (setq imap-auth (or auth imap-auth))
950 (setq imap-stream (or stream imap-stream))
951 (message "imap: Connecting to %s..." imap-server)
952 (if (let ((imap-stream (or imap-stream imap-default-stream)))
953 (imap-open-1 buffer))
955 (let (stream-changed)
956 (message "imap: Connecting to %s...done" imap-server)
957 (when (null imap-stream)
958 (let ((streams imap-streams))
959 (while (setq stream (pop streams))
960 (if (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
961 (setq stream-changed (not (eq (or imap-stream
967 (error "Couldn't figure out a stream for server"))))
969 (message "imap: Reconnecting with stream `%s'..." imap-stream)
971 (if (imap-open-1 buffer)
972 (message "imap: Reconnecting with stream `%s'...done"
974 (message "imap: Reconnecting with stream `%s'...failed"
976 (setq imap-capability nil))
977 (if (imap-opened buffer)
978 ;; Choose authenticator
979 (when (and (null imap-auth) (not (eq imap-state 'auth)))
980 (let ((auths imap-authenticators))
981 (while (setq auth (pop auths))
982 (if (funcall (nth 1 (assq auth imap-authenticator-alist))
987 (error "Couldn't figure out authenticator for server"))))))
988 (message "imap: Connecting to %s...failed" imap-server))
989 (when (imap-opened buffer)
990 (setq imap-mailbox-data (make-vector imap-mailbox-prime 0))
993 (defun imap-opened (&optional buffer)
994 "Return non-nil if connection to imap server in BUFFER is open.
995 If BUFFER is nil then the current buffer is used."
996 (and (setq buffer (get-buffer (or buffer (current-buffer))))
997 (buffer-live-p buffer)
998 (with-current-buffer buffer
1000 (memq (process-status imap-process) '(open run))))))
1002 (defun imap-authenticate (&optional user passwd buffer)
1003 "Authenticate to server in BUFFER, using current buffer if nil.
1004 It uses the authenticator specified when opening the server. If the
1005 authenticator requires username/passwords, they are queried from the
1006 user and optionally stored in the buffer. If USER and/or PASSWD is
1007 specified, the user will not be questioned and the username and/or
1008 password is remembered in the buffer."
1009 (with-current-buffer (or buffer (current-buffer))
1010 (if (not (eq imap-state 'nonauth))
1011 (or (eq imap-state 'auth)
1012 (eq imap-state 'select)
1013 (eq imap-state 'examine))
1014 (make-local-variable 'imap-username)
1015 (make-local-variable 'imap-password)
1016 (if user (setq imap-username user))
1017 (if passwd (setq imap-password passwd))
1018 (if (funcall (nth 2 (assq imap-auth imap-authenticator-alist)) buffer)
1019 (setq imap-state 'auth)))))
1021 (defun imap-close (&optional buffer)
1022 "Close connection to server in BUFFER.
1023 If BUFFER is nil, the current buffer is used."
1024 (with-current-buffer (or buffer (current-buffer))
1026 (imap-send-command-wait "LOGOUT"))
1027 (when (and imap-process
1028 (memq (process-status imap-process) '(open run)))
1029 (delete-process imap-process))
1030 (setq imap-current-mailbox nil
1031 imap-current-message nil
1036 (defun imap-capability (&optional identifier buffer)
1037 "Return a list of identifiers which server in BUFFER support.
1038 If IDENTIFIER, return non-nil if it's among the servers capabilities.
1039 If BUFFER is nil, the current buffer is assumed."
1040 (with-current-buffer (or buffer (current-buffer))
1041 (unless imap-capability
1042 (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
1043 (setq imap-capability '(IMAP2))))
1045 (memq (intern (upcase (symbol-name identifier))) imap-capability)
1048 (defun imap-namespace (&optional buffer)
1049 "Return a namespace hierarchy at server in BUFFER.
1050 If BUFFER is nil, the current buffer is assumed."
1051 (with-current-buffer (or buffer (current-buffer))
1052 (unless imap-namespace
1053 (when (imap-capability 'NAMESPACE)
1054 (imap-send-command-wait "NAMESPACE")))
1057 (defun imap-send-command-wait (command &optional buffer)
1058 (imap-wait-for-tag (imap-send-command command buffer) buffer))
1061 ;; Mailbox functions:
1063 (defun imap-mailbox-put (propname value &optional mailbox buffer)
1064 (with-current-buffer (or buffer (current-buffer))
1065 (if imap-mailbox-data
1066 (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
1068 (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
1069 propname value mailbox (current-buffer)))
1072 (defsubst imap-mailbox-get-1 (propname &optional mailbox)
1073 (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
1076 (defun imap-mailbox-get (propname &optional mailbox buffer)
1077 (let ((mailbox (imap-utf7-encode mailbox)))
1078 (with-current-buffer (or buffer (current-buffer))
1079 (imap-mailbox-get-1 propname (or mailbox imap-current-mailbox)))))
1081 (defun imap-mailbox-map-1 (func &optional mailbox-decoder buffer)
1082 (with-current-buffer (or buffer (current-buffer))
1086 (push (funcall func (if mailbox-decoder
1087 (funcall mailbox-decoder (symbol-name s))
1088 (symbol-name s))) result))
1092 (defun imap-mailbox-map (func &optional buffer)
1093 "Map a function across each mailbox in `imap-mailbox-data', returning a list.
1094 Function should take a mailbox name (a string) as
1096 (imap-mailbox-map-1 func 'imap-utf7-decode buffer))
1098 (defun imap-current-mailbox (&optional buffer)
1099 (with-current-buffer (or buffer (current-buffer))
1100 (imap-utf7-decode imap-current-mailbox)))
1102 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
1103 (and (string= mailbox imap-current-mailbox)
1105 (eq imap-state 'examine))
1107 (eq imap-state 'selected)))))
1109 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
1110 (with-current-buffer (or buffer (current-buffer))
1111 (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
1113 (defun imap-mailbox-select-1 (mailbox &optional examine)
1114 "Select MAILBOX on server in BUFFER.
1115 If EXAMINE is non-nil, do a read-only select."
1116 (if (imap-current-mailbox-p-1 mailbox examine)
1117 imap-current-mailbox
1118 (setq imap-current-mailbox mailbox)
1119 (if (imap-ok-p (imap-send-command-wait
1120 (concat (if examine "EXAMINE" "SELECT") " \""
1123 (setq imap-message-data (make-vector imap-message-prime 0)
1124 imap-state (if examine 'examine 'selected))
1125 imap-current-mailbox)
1126 ;; Failed SELECT/EXAMINE unselects current mailbox
1127 (setq imap-current-mailbox nil))))
1129 (defun imap-mailbox-select (mailbox &optional examine buffer)
1130 (with-current-buffer (or buffer (current-buffer))
1132 (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
1134 (defun imap-mailbox-examine-1 (mailbox &optional buffer)
1135 (with-current-buffer (or buffer (current-buffer))
1136 (imap-mailbox-select-1 mailbox 'examine)))
1138 (defun imap-mailbox-examine (mailbox &optional buffer)
1139 "Examine MAILBOX on server in BUFFER."
1140 (imap-mailbox-select mailbox 'examine buffer))
1142 (defun imap-mailbox-unselect (&optional buffer)
1143 "Close current folder in BUFFER, without expunging articles."
1144 (with-current-buffer (or buffer (current-buffer))
1145 (when (or (eq imap-state 'auth)
1146 (and (imap-capability 'UNSELECT)
1147 (imap-ok-p (imap-send-command-wait "UNSELECT")))
1149 (imap-send-command-wait (concat "EXAMINE \""
1150 imap-current-mailbox
1152 (imap-ok-p (imap-send-command-wait "CLOSE"))))
1153 (setq imap-current-mailbox nil
1154 imap-message-data nil
1158 (defun imap-mailbox-expunge (&optional asynch buffer)
1159 "Expunge articles in current folder in BUFFER.
1160 If ASYNCH, do not wait for succesful completion of the command.
1161 If BUFFER is nil the current buffer is assumed."
1162 (with-current-buffer (or buffer (current-buffer))
1163 (when (and imap-current-mailbox (not (eq imap-state 'examine)))
1165 (imap-send-command "EXPUNGE")
1166 (imap-ok-p (imap-send-command-wait "EXPUNGE"))))))
1168 (defun imap-mailbox-close (&optional asynch buffer)
1169 "Expunge articles and close current folder in BUFFER.
1170 If ASYNCH, do not wait for succesful completion of the command.
1171 If BUFFER is nil the current buffer is assumed."
1172 (with-current-buffer (or buffer (current-buffer))
1173 (when imap-current-mailbox
1175 (imap-add-callback (imap-send-command "CLOSE")
1176 `(lambda (tag status)
1177 (message "IMAP mailbox `%s' closed... %s"
1178 imap-current-mailbox status)
1179 (when (eq ,imap-current-mailbox
1180 imap-current-mailbox)
1181 ;; Don't wipe out data if another mailbox
1183 (setq imap-current-mailbox nil
1184 imap-message-data nil
1185 imap-state 'auth))))
1186 (when (imap-ok-p (imap-send-command-wait "CLOSE"))
1187 (setq imap-current-mailbox nil
1188 imap-message-data nil
1192 (defun imap-mailbox-create-1 (mailbox)
1193 (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
1195 (defun imap-mailbox-create (mailbox &optional buffer)
1196 "Create MAILBOX on server in BUFFER.
1197 If BUFFER is nil the current buffer is assumed."
1198 (with-current-buffer (or buffer (current-buffer))
1199 (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
1201 (defun imap-mailbox-delete (mailbox &optional buffer)
1202 "Delete MAILBOX on server in BUFFER.
1203 If BUFFER is nil the current buffer is assumed."
1204 (let ((mailbox (imap-utf7-encode mailbox)))
1205 (with-current-buffer (or buffer (current-buffer))
1207 (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1209 (defun imap-mailbox-rename (oldname newname &optional buffer)
1210 "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1211 If BUFFER is nil the current buffer is assumed."
1212 (let ((oldname (imap-utf7-encode oldname))
1213 (newname (imap-utf7-encode newname)))
1214 (with-current-buffer (or buffer (current-buffer))
1216 (imap-send-command-wait (list "RENAME \"" oldname "\" "
1217 "\"" newname "\""))))))
1219 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1220 "Return a list of subscribed mailboxes on server in BUFFER.
1221 If ROOT is non-nil, only list matching mailboxes. If ADD-DELIMITER is
1222 non-nil, a hierarchy delimiter is added to root. REFERENCE is a
1223 implementation-specific string that has to be passed to lsub command."
1224 (with-current-buffer (or buffer (current-buffer))
1225 ;; Make sure we know the hierarchy separator for root's hierarchy
1226 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1227 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1228 (imap-utf7-encode root) "\"")))
1229 ;; clear list data (NB not delimiter and other stuff)
1230 (imap-mailbox-map-1 (lambda (mailbox)
1231 (imap-mailbox-put 'lsub nil mailbox)))
1233 (imap-send-command-wait
1234 (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1235 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1238 (imap-mailbox-map-1 (lambda (mailbox)
1239 (when (imap-mailbox-get-1 'lsub mailbox)
1240 (push (imap-utf7-decode mailbox) out))))
1243 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1244 "Return a list of mailboxes matching ROOT on server in BUFFER.
1245 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1246 root. REFERENCE is a implementation-specific string that has to be
1247 passed to list command."
1248 (with-current-buffer (or buffer (current-buffer))
1249 ;; Make sure we know the hierarchy separator for root's hierarchy
1250 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1251 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1252 (imap-utf7-encode root) "\"")))
1253 ;; clear list data (NB not delimiter and other stuff)
1254 (imap-mailbox-map-1 (lambda (mailbox)
1255 (imap-mailbox-put 'list nil mailbox)))
1257 (imap-send-command-wait
1258 (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1259 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1262 (imap-mailbox-map-1 (lambda (mailbox)
1263 (when (imap-mailbox-get-1 'list mailbox)
1264 (push (imap-utf7-decode mailbox) out))))
1267 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1268 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1269 Returns non-nil if successful."
1270 (with-current-buffer (or buffer (current-buffer))
1271 (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1272 (imap-utf7-encode mailbox)
1275 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1276 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1277 Returns non-nil if successful."
1278 (with-current-buffer (or buffer (current-buffer))
1279 (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1280 (imap-utf7-encode mailbox)
1283 (defun imap-mailbox-status (mailbox items &optional buffer)
1284 "Get status items ITEM in MAILBOX from server in BUFFER.
1285 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1286 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1287 or 'unseen. If ITEMS is a list of symbols, a list of values is
1288 returned, if ITEMS is a symbol only it's value is returned."
1289 (with-current-buffer (or buffer (current-buffer))
1291 (imap-send-command-wait (list "STATUS \""
1292 (imap-utf7-encode mailbox)
1299 (mapcar (lambda (item)
1300 (imap-mailbox-get item mailbox))
1302 (imap-mailbox-get items mailbox)))))
1304 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1305 "Get ACL on mailbox from server in BUFFER."
1306 (let ((mailbox (imap-utf7-encode mailbox)))
1307 (with-current-buffer (or buffer (current-buffer))
1309 (imap-send-command-wait (list "GETACL \""
1310 (or mailbox imap-current-mailbox)
1312 (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1314 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1315 "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
1316 (let ((mailbox (imap-utf7-encode mailbox)))
1317 (with-current-buffer (or buffer (current-buffer))
1319 (imap-send-command-wait (list "SETACL \""
1320 (or mailbox imap-current-mailbox)
1326 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1327 "Removes any <identifier,rights> pair for IDENTIFIER in MAILBOX from server in BUFFER."
1328 (let ((mailbox (imap-utf7-encode mailbox)))
1329 (with-current-buffer (or buffer (current-buffer))
1331 (imap-send-command-wait (list "DELETEACL \""
1332 (or mailbox imap-current-mailbox)
1337 ;; Message functions:
1339 (defun imap-current-message (&optional buffer)
1340 (with-current-buffer (or buffer (current-buffer))
1341 imap-current-message))
1343 (defun imap-list-to-message-set (list)
1344 (mapconcat (lambda (item)
1345 (number-to-string item))
1351 (defun imap-range-to-message-set (range)
1356 (car item) (cdr item))
1357 (format "%d" item)))
1358 (if (and (listp range) (not (listp (cdr range))))
1359 (list range) ;; make (1 . 2) into ((1 . 2))
1363 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1364 (with-current-buffer (or buffer (current-buffer))
1365 (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1367 (imap-list-to-message-set uids)
1371 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1372 "Fetch properties PROPS from message set UIDS from server in BUFFER.
1373 UIDS can be a string, number or a list of numbers. If RECEIVE
1374 is non-nil return theese properties."
1375 (with-current-buffer (or buffer (current-buffer))
1376 (when (imap-ok-p (imap-send-command-wait
1377 (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1379 (imap-list-to-message-set uids)
1382 (if (or (null receive) (stringp uids))
1385 (mapcar (lambda (uid)
1387 (mapcar (lambda (prop)
1388 (imap-message-get uid prop))
1390 (imap-message-get uid receive)))
1392 (imap-message-get uids receive))))))
1394 (defun imap-message-put (uid propname value &optional buffer)
1395 (with-current-buffer (or buffer (current-buffer))
1396 (if imap-message-data
1397 (put (intern (number-to-string uid) imap-message-data)
1399 (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1400 uid propname value (current-buffer)))
1403 (defun imap-message-get (uid propname &optional buffer)
1404 (with-current-buffer (or buffer (current-buffer))
1405 (get (intern-soft (number-to-string uid) imap-message-data)
1408 (defun imap-message-map (func propname &optional buffer)
1409 "Map a function across each mailbox in `imap-message-data', returning a list."
1410 (with-current-buffer (or buffer (current-buffer))
1414 (push (funcall func (get s 'UID) (get s propname)) result))
1418 (defmacro imap-message-envelope-date (uid &optional buffer)
1419 `(with-current-buffer (or ,buffer (current-buffer))
1420 (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1422 (defmacro imap-message-envelope-subject (uid &optional buffer)
1423 `(with-current-buffer (or ,buffer (current-buffer))
1424 (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1426 (defmacro imap-message-envelope-from (uid &optional buffer)
1427 `(with-current-buffer (or ,buffer (current-buffer))
1428 (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1430 (defmacro imap-message-envelope-sender (uid &optional buffer)
1431 `(with-current-buffer (or ,buffer (current-buffer))
1432 (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1434 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1435 `(with-current-buffer (or ,buffer (current-buffer))
1436 (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1438 (defmacro imap-message-envelope-to (uid &optional buffer)
1439 `(with-current-buffer (or ,buffer (current-buffer))
1440 (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1442 (defmacro imap-message-envelope-cc (uid &optional buffer)
1443 `(with-current-buffer (or ,buffer (current-buffer))
1444 (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1446 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1447 `(with-current-buffer (or ,buffer (current-buffer))
1448 (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1450 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1451 `(with-current-buffer (or ,buffer (current-buffer))
1452 (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1454 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1455 `(with-current-buffer (or ,buffer (current-buffer))
1456 (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1458 (defmacro imap-message-body (uid &optional buffer)
1459 `(with-current-buffer (or ,buffer (current-buffer))
1460 (imap-message-get ,uid 'BODY)))
1462 (defun imap-search (predicate &optional buffer)
1463 (with-current-buffer (or buffer (current-buffer))
1464 (imap-mailbox-put 'search 'dummy)
1465 (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1466 (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1468 (message "Missing SEARCH response to a SEARCH command (server not RFC compliant)...")
1470 (imap-mailbox-get-1 'search imap-current-mailbox)))))
1472 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1473 "Return t iff FLAG can be permanently (between IMAP sessions) saved on articles, in MAILBOX on server in BUFFER."
1474 (with-current-buffer (or buffer (current-buffer))
1475 (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1476 (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1478 (defun imap-message-flags-set (articles flags &optional silent buffer)
1479 (when (and articles flags)
1480 (with-current-buffer (or buffer (current-buffer))
1481 (imap-ok-p (imap-send-command-wait
1482 (concat "UID STORE " articles
1483 " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1485 (defun imap-message-flags-del (articles flags &optional silent buffer)
1486 (when (and articles flags)
1487 (with-current-buffer (or buffer (current-buffer))
1488 (imap-ok-p (imap-send-command-wait
1489 (concat "UID STORE " articles
1490 " -FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1492 (defun imap-message-flags-add (articles flags &optional silent buffer)
1493 (when (and articles flags)
1494 (with-current-buffer (or buffer (current-buffer))
1495 (imap-ok-p (imap-send-command-wait
1496 (concat "UID STORE " articles
1497 " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1499 (defun imap-message-copyuid-1 (mailbox)
1500 (if (imap-capability 'UIDPLUS)
1501 (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1502 (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1503 (let ((old-mailbox imap-current-mailbox)
1505 (imap-message-data (make-vector 2 0)))
1506 (when (imap-mailbox-examine-1 mailbox)
1508 (and (imap-fetch "*" "UID")
1509 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1510 (apply 'max (imap-message-map
1511 (lambda (uid prop) uid) 'UID))))
1513 (imap-mailbox-select old-mailbox (eq state 'examine))
1514 (imap-mailbox-unselect)))))))
1516 (defun imap-message-copyuid (mailbox &optional buffer)
1517 (with-current-buffer (or buffer (current-buffer))
1518 (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1520 (defun imap-message-copy (articles mailbox
1521 &optional dont-create no-copyuid buffer)
1522 "Copy ARTICLES (a string message set) to MAILBOX on server in
1523 BUFFER, creating mailbox if it doesn't exist. If dont-create is
1524 non-nil, it will not create a mailbox. On success, return a list with
1525 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1526 first element, rest of list contain the saved articles' UIDs."
1528 (with-current-buffer (or buffer (current-buffer))
1529 (let ((mailbox (imap-utf7-encode mailbox)))
1530 (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1531 (imap-current-target-mailbox mailbox))
1532 (if (imap-ok-p (imap-send-command-wait cmd))
1534 (when (and (not dont-create)
1535 ;; removed because of buggy Oracle server
1536 ;; that doesn't send TRYCREATE tags (which
1537 ;; is a MUST according to specifications):
1538 ;;(imap-mailbox-get-1 'trycreate mailbox)
1539 (imap-mailbox-create-1 mailbox))
1540 (imap-ok-p (imap-send-command-wait cmd)))))
1542 (imap-message-copyuid-1 mailbox)))))))
1544 (defun imap-message-appenduid-1 (mailbox)
1545 (if (imap-capability 'UIDPLUS)
1546 (imap-mailbox-get-1 'appenduid mailbox)
1547 (let ((old-mailbox imap-current-mailbox)
1549 (imap-message-data (make-vector 2 0)))
1550 (when (imap-mailbox-examine-1 mailbox)
1552 (and (imap-fetch "*" "UID")
1553 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1554 (apply 'max (imap-message-map
1555 (lambda (uid prop) uid) 'UID))))
1557 (imap-mailbox-select old-mailbox (eq state 'examine))
1558 (imap-mailbox-unselect)))))))
1560 (defun imap-message-appenduid (mailbox &optional buffer)
1561 (with-current-buffer (or buffer (current-buffer))
1562 (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1564 (defun imap-message-append (mailbox article &optional flags date-time buffer)
1565 "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1566 FLAGS and DATE-TIME is currently not used. Return a cons holding
1567 uidvalidity of MAILBOX and UID the newly created article got, or nil
1569 (let ((mailbox (imap-utf7-encode mailbox)))
1570 (with-current-buffer (or buffer (current-buffer))
1571 (and (let ((imap-current-target-mailbox mailbox))
1573 (imap-send-command-wait
1574 (list "APPEND \"" mailbox "\" " article))))
1575 (imap-message-appenduid-1 mailbox)))))
1577 (defun imap-body-lines (body)
1578 "Return number of lines in article by looking at the mime bodystructure BODY."
1580 (if (stringp (car body))
1581 (cond ((and (string= (upcase (car body)) "TEXT")
1582 (numberp (nth 7 body)))
1584 ((and (string= (upcase (car body)) "MESSAGE")
1585 (numberp (nth 9 body)))
1588 (apply '+ (mapcar 'imap-body-lines body)))
1591 (defun imap-envelope-from (from)
1592 "Return a from string line."
1594 (concat (aref from 0)
1595 (if (aref from 0) " <")
1599 (if (aref from 0) ">"))))
1602 ;; Internal functions.
1604 (defun imap-add-callback (tag func)
1605 (setq imap-callbacks (append (list (cons tag func)) imap-callbacks)))
1607 (defun imap-send-command-1 (cmdstr)
1608 (setq cmdstr (concat cmdstr imap-client-eol))
1610 (with-current-buffer (get-buffer-create imap-log-buffer)
1611 (imap-disable-multibyte)
1612 (buffer-disable-undo)
1613 (goto-char (point-max))
1615 (process-send-string imap-process cmdstr))
1617 (defun imap-send-command (command &optional buffer)
1618 (with-current-buffer (or buffer (current-buffer))
1619 (if (not (listp command)) (setq command (list command)))
1620 (let ((tag (setq imap-tag (1+ imap-tag)))
1622 (setq cmdstr (concat (number-to-string imap-tag) " "))
1623 (while (setq cmd (pop command))
1624 (cond ((stringp cmd)
1625 (setq cmdstr (concat cmdstr cmd)))
1627 (let ((eol imap-client-eol)
1628 (calcfirst imap-calculate-literal-size-first)
1630 (with-current-buffer cmd
1632 (setq size (buffer-size)))
1633 (when (not (equal eol "\r\n"))
1634 ;; XXX modifies buffer!
1635 (goto-char (point-min))
1636 (while (search-forward "\r\n" nil t)
1637 (replace-match eol)))
1639 (setq size (buffer-size))))
1641 (concat cmdstr (format "{%d}" size))))
1644 (imap-send-command-1 cmdstr)
1646 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1647 (setq command nil) ;; abort command if no cont-req
1648 (let ((process imap-process)
1649 (stream imap-stream)
1650 (eol imap-client-eol))
1651 (with-current-buffer cmd
1653 (with-current-buffer (get-buffer-create
1655 (imap-disable-multibyte)
1656 (buffer-disable-undo)
1657 (goto-char (point-max))
1658 (insert-buffer-substring cmd)))
1659 (process-send-region process (point-min)
1661 (process-send-string process imap-client-eol))))
1662 (setq imap-continuation nil)))
1664 (imap-send-command-1 cmdstr)
1667 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1668 (setq command nil) ;; abort command if no cont-req
1669 (setq command (cons (funcall cmd imap-continuation)
1671 (setq imap-continuation nil)))
1673 (error "Unknown command type"))))
1675 (imap-send-command-1 cmdstr))
1678 (defun imap-wait-for-tag (tag &optional buffer)
1679 (with-current-buffer (or buffer (current-buffer))
1680 (let (imap-have-messaged)
1681 (while (and (null imap-continuation)
1682 (memq (process-status imap-process) '(open run))
1683 (< imap-reached-tag tag))
1684 (let ((len (/ (point-max) 1024))
1687 (setq imap-have-messaged t)
1688 (message "imap read: %dk" len))
1689 (accept-process-output imap-process 1)))
1690 (when imap-have-messaged
1692 (and (memq (process-status imap-process) '(open run))
1693 (or (assq tag imap-failed-tags)
1694 (if imap-continuation
1698 (defun imap-sentinel (process string)
1699 (delete-process process))
1701 (defun imap-find-next-line ()
1702 "Return point at end of current line, taking into account literals.
1703 Return nil if no complete line has arrived."
1704 (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
1707 (if (match-string 1)
1708 (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1710 (goto-char (+ (point) (string-to-number (match-string 1))))
1711 (imap-find-next-line))
1714 (defun imap-arrival-filter (proc string)
1715 "IMAP process filter."
1716 (with-current-buffer (process-buffer proc)
1717 (goto-char (point-max))
1720 (with-current-buffer (get-buffer-create imap-log-buffer)
1721 (imap-disable-multibyte)
1722 (buffer-disable-undo)
1723 (goto-char (point-max))
1726 (goto-char (point-min))
1727 (while (setq end (imap-find-next-line))
1729 (narrow-to-region (point-min) end)
1730 (delete-backward-char (length imap-server-eol))
1731 (goto-char (point-min))
1733 (cond ((eq imap-state 'initial)
1734 (imap-parse-greeting))
1735 ((or (eq imap-state 'auth)
1736 (eq imap-state 'nonauth)
1737 (eq imap-state 'selected)
1738 (eq imap-state 'examine))
1739 (imap-parse-response))
1741 (message "Unknown state %s in arrival filter"
1743 (delete-region (point-min) (point-max))))))))
1748 (defsubst imap-forward ()
1749 (or (eobp) (forward-char)))
1752 ;; ; Unsigned 32-bit integer
1753 ;; ; (0 <= n < 4,294,967,296)
1755 (defsubst imap-parse-number ()
1756 (when (looking-at "[0-9]+")
1758 (string-to-number (match-string 0))
1759 (goto-char (match-end 0)))))
1761 ;; literal = "{" number "}" CRLF *CHAR8
1762 ;; ; Number represents the number of CHAR8s
1764 (defsubst imap-parse-literal ()
1765 (when (looking-at "{\\([0-9]+\\)}\r\n")
1766 (let ((pos (match-end 0))
1767 (len (string-to-number (match-string 1))))
1768 (if (< (point-max) (+ pos len))
1770 (goto-char (+ pos len))
1771 (buffer-substring pos (+ pos len))))))
1773 ;; string = quoted / literal
1775 ;; quoted = DQUOTE *QUOTED-CHAR DQUOTE
1777 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
1778 ;; "\" quoted-specials
1780 ;; quoted-specials = DQUOTE / "\"
1782 ;; TEXT-CHAR = <any CHAR except CR and LF>
1784 (defsubst imap-parse-string ()
1785 (cond ((eq (char-after) ?\")
1787 (let ((p (point)) (name ""))
1788 (skip-chars-forward "^\"\\\\")
1789 (setq name (buffer-substring p (point)))
1790 (while (eq (char-after) ?\\)
1791 (setq p (1+ (point)))
1793 (skip-chars-forward "^\"\\\\")
1794 (setq name (concat name (buffer-substring p (point)))))
1797 ((eq (char-after) ?{)
1798 (imap-parse-literal))))
1802 (defsubst imap-parse-nil ()
1803 (if (looking-at "NIL")
1804 (goto-char (match-end 0))))
1806 ;; nstring = string / nil
1808 (defsubst imap-parse-nstring ()
1809 (or (imap-parse-string)
1810 (and (imap-parse-nil)
1813 ;; astring = atom / string
1815 ;; atom = 1*ATOM-CHAR
1817 ;; ATOM-CHAR = <any CHAR except atom-specials>
1819 ;; atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards /
1822 ;; list-wildcards = "%" / "*"
1824 ;; quoted-specials = DQUOTE / "\"
1826 (defsubst imap-parse-astring ()
1827 (or (imap-parse-string)
1828 (buffer-substring (point)
1829 (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
1830 (goto-char (1- (match-end 0)))
1834 ;; address = "(" addr-name SP addr-adl SP addr-mailbox SP
1837 ;; addr-adl = nstring
1838 ;; ; Holds route from [RFC-822] route-addr if
1841 ;; addr-host = nstring
1842 ;; ; NIL indicates [RFC-822] group syntax.
1843 ;; ; Otherwise, holds [RFC-822] domain name
1845 ;; addr-mailbox = nstring
1846 ;; ; NIL indicates end of [RFC-822] group; if
1847 ;; ; non-NIL and addr-host is NIL, holds
1848 ;; ; [RFC-822] group name.
1849 ;; ; Otherwise, holds [RFC-822] local-part
1850 ;; ; after removing [RFC-822] quoting
1852 ;; addr-name = nstring
1853 ;; ; If non-NIL, holds phrase from [RFC-822]
1854 ;; ; mailbox after removing [RFC-822] quoting
1857 (defsubst imap-parse-address ()
1859 (when (eq (char-after) ?\()
1861 (setq address (vector (prog1 (imap-parse-nstring)
1863 (prog1 (imap-parse-nstring)
1865 (prog1 (imap-parse-nstring)
1867 (imap-parse-nstring)))
1868 (when (eq (char-after) ?\))
1872 ;; address-list = "(" 1*address ")" / nil
1876 (defsubst imap-parse-address-list ()
1877 (if (eq (char-after) ?\()
1878 (let (address addresses)
1880 (while (and (not (eq (char-after) ?\)))
1881 ;; next line for MS Exchange bug
1882 (progn (and (eq (char-after) ? ) (imap-forward)) t)
1883 (setq address (imap-parse-address)))
1884 (setq addresses (cons address addresses)))
1885 (when (eq (char-after) ?\))
1887 (nreverse addresses)))
1888 (assert (imap-parse-nil) t "In imap-parse-address-list")))
1890 ;; mailbox = "INBOX" / astring
1891 ;; ; INBOX is case-insensitive. All case variants of
1892 ;; ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
1893 ;; ; not as an astring. An astring which consists of
1894 ;; ; the case-insensitive sequence "I" "N" "B" "O" "X"
1895 ;; ; is considered to be INBOX and not an astring.
1896 ;; ; Refer to section 5.1 for further
1897 ;; ; semantic details of mailbox names.
1899 (defsubst imap-parse-mailbox ()
1900 (let ((mailbox (imap-parse-astring)))
1901 (if (string-equal "INBOX" (upcase mailbox))
1905 ;; greeting = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
1907 ;; resp-cond-auth = ("OK" / "PREAUTH") SP resp-text
1908 ;; ; Authentication condition
1910 ;; resp-cond-bye = "BYE" SP resp-text
1912 (defun imap-parse-greeting ()
1913 "Parse a IMAP greeting."
1914 (cond ((looking-at "\\* OK ")
1915 (setq imap-state 'nonauth))
1916 ((looking-at "\\* PREAUTH ")
1917 (setq imap-state 'auth))
1918 ((looking-at "\\* BYE ")
1919 (setq imap-state 'closed))))
1921 ;; response = *(continue-req / response-data) response-done
1923 ;; continue-req = "+" SP (resp-text / base64) CRLF
1925 ;; response-data = "*" SP (resp-cond-state / resp-cond-bye /
1926 ;; mailbox-data / message-data / capability-data) CRLF
1928 ;; response-done = response-tagged / response-fatal
1930 ;; response-fatal = "*" SP resp-cond-bye CRLF
1931 ;; ; Server closes connection immediately
1933 ;; response-tagged = tag SP resp-cond-state CRLF
1935 ;; resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
1936 ;; ; Status condition
1938 ;; resp-cond-bye = "BYE" SP resp-text
1940 ;; mailbox-data = "FLAGS" SP flag-list /
1941 ;; "LIST" SP mailbox-list /
1942 ;; "LSUB" SP mailbox-list /
1943 ;; "SEARCH" *(SP nz-number) /
1944 ;; "STATUS" SP mailbox SP "("
1945 ;; [status-att SP number *(SP status-att SP number)] ")" /
1946 ;; number SP "EXISTS" /
1947 ;; number SP "RECENT"
1949 ;; message-data = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
1951 ;; capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
1953 ;; ; IMAP4rev1 servers which offer RFC 1730
1954 ;; ; compatibility MUST list "IMAP4" as the first
1957 (defun imap-parse-response ()
1958 "Parse a IMAP command response."
1960 (case (setq token (read (current-buffer)))
1961 (+ (setq imap-continuation
1962 (or (buffer-substring (min (point-max) (1+ (point)))
1965 (* (case (prog1 (setq token (read (current-buffer)))
1967 (OK (imap-parse-resp-text))
1968 (NO (imap-parse-resp-text))
1969 (BAD (imap-parse-resp-text))
1970 (BYE (imap-parse-resp-text))
1971 (FLAGS (imap-mailbox-put 'flags (imap-parse-flag-list)))
1972 (LIST (imap-parse-data-list 'list))
1973 (LSUB (imap-parse-data-list 'lsub))
1974 (SEARCH (imap-mailbox-put
1976 (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
1977 (STATUS (imap-parse-status))
1978 (CAPABILITY (setq imap-capability
1979 (read (concat "(" (upcase (buffer-substring
1980 (point) (point-max)))
1982 (ACL (imap-parse-acl))
1983 (t (case (prog1 (read (current-buffer))
1985 (EXISTS (imap-mailbox-put 'exists token))
1986 (RECENT (imap-mailbox-put 'recent token))
1988 (FETCH (imap-parse-fetch token))
1989 (t (message "Garbage: %s" (buffer-string)))))))
1991 (if (not (integerp token))
1992 (message "Garbage: %s" (buffer-string))
1993 (case (prog1 (setq status (read (current-buffer)))
1996 (setq imap-reached-tag (max imap-reached-tag token))
1997 (imap-parse-resp-text)))
1999 (setq imap-reached-tag (max imap-reached-tag token))
2001 (imap-parse-resp-text))
2003 (when (eq (char-after) ?\[)
2004 (setq code (buffer-substring (point)
2005 (search-forward "]")))
2007 (setq text (buffer-substring (point) (point-max)))
2008 (push (list token status code text)
2009 imap-failed-tags))))
2011 (setq imap-reached-tag (max imap-reached-tag token))
2013 (imap-parse-resp-text))
2015 (when (eq (char-after) ?\[)
2016 (setq code (buffer-substring (point)
2017 (search-forward "]")))
2019 (setq text (buffer-substring (point) (point-max)))
2020 (push (list token status code text) imap-failed-tags)
2021 (error "Internal error, tag %s status %s code %s text %s"
2022 token status code text))))
2023 (t (message "Garbage: %s" (buffer-string))))
2024 (when (assq token imap-callbacks)
2025 (funcall (cdr (assq token imap-callbacks)) token status)
2026 (setq imap-callbacks
2027 (imap-remassoc token imap-callbacks)))))))))
2029 ;; resp-text = ["[" resp-text-code "]" SP] text
2031 ;; text = 1*TEXT-CHAR
2033 ;; TEXT-CHAR = <any CHAR except CR and LF>
2035 (defun imap-parse-resp-text ()
2036 (imap-parse-resp-text-code))
2038 ;; resp-text-code = "ALERT" /
2039 ;; "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
2040 ;; "NEWNAME" SP string SP string /
2042 ;; "PERMANENTFLAGS" SP "("
2043 ;; [flag-perm *(SP flag-perm)] ")" /
2047 ;; "UIDNEXT" SP nz-number /
2048 ;; "UIDVALIDITY" SP nz-number /
2049 ;; "UNSEEN" SP nz-number /
2050 ;; resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
2052 ;; resp_code_apnd = "APPENDUID" SPACE nz_number SPACE uniqueid
2054 ;; resp_code_copy = "COPYUID" SPACE nz_number SPACE set SPACE set
2056 ;; set = sequence-num / (sequence-num ":" sequence-num) /
2058 ;; ; Identifies a set of messages. For message
2059 ;; ; sequence numbers, these are consecutive
2060 ;; ; numbers from 1 to the number of messages in
2062 ;; ; Comma delimits individual numbers, colon
2063 ;; ; delimits between two numbers inclusive.
2064 ;; ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
2065 ;; ; 14,15 for a mailbox with 15 messages.
2067 ;; sequence-num = nz-number / "*"
2068 ;; ; * is the largest number in use. For message
2069 ;; ; sequence numbers, it is the number of messages
2070 ;; ; in the mailbox. For unique identifiers, it is
2071 ;; ; the unique identifier of the last message in
2074 ;; flag-perm = flag / "\*"
2076 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2077 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2078 ;; ; Does not include "\Recent"
2080 ;; flag-extension = "\" atom
2081 ;; ; Future expansion. Client implementations
2082 ;; ; MUST accept flag-extension flags. Server
2083 ;; ; implementations MUST NOT generate
2084 ;; ; flag-extension flags except as defined by
2085 ;; ; future standard or standards-track
2086 ;; ; revisions of this specification.
2088 ;; flag-keyword = atom
2090 ;; resp-text-atom = 1*<any ATOM-CHAR except "]">
2092 (defun imap-parse-resp-text-code ()
2093 ;; xxx next line for stalker communigate pro 3.3.1 bug
2094 (when (looking-at " \\[")
2096 (when (eq (char-after) ?\[)
2098 (cond ((search-forward "PERMANENTFLAGS " nil t)
2099 (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2100 ((search-forward "UIDNEXT " nil t)
2101 (imap-mailbox-put 'uidnext (read (current-buffer))))
2102 ((search-forward "UNSEEN " nil t)
2103 (imap-mailbox-put 'unseen (read (current-buffer))))
2104 ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2105 (imap-mailbox-put 'uidvalidity (match-string 1)))
2106 ((search-forward "READ-ONLY" nil t)
2107 (imap-mailbox-put 'read-only t))
2108 ((search-forward "NEWNAME " nil t)
2109 (let (oldname newname)
2110 (setq oldname (imap-parse-string))
2112 (setq newname (imap-parse-string))
2113 (imap-mailbox-put 'newname newname oldname)))
2114 ((search-forward "TRYCREATE" nil t)
2115 (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2116 ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2117 (imap-mailbox-put 'appenduid
2118 (list (match-string 1)
2119 (string-to-number (match-string 2)))
2120 imap-current-target-mailbox))
2121 ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2122 (imap-mailbox-put 'copyuid (list (match-string 1)
2125 imap-current-target-mailbox))
2126 ((search-forward "ALERT] " nil t)
2127 (message "Imap server %s information: %s" imap-server
2128 (buffer-substring (point) (point-max)))))))
2130 ;; mailbox-list = "(" [mbx-list-flags] ")" SP
2131 ;; (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2133 ;; mbx-list-flags = *(mbx-list-oflag SP) mbx-list-sflag
2134 ;; *(SP mbx-list-oflag) /
2135 ;; mbx-list-oflag *(SP mbx-list-oflag)
2137 ;; mbx-list-oflag = "\Noinferiors" / flag-extension
2138 ;; ; Other flags; multiple possible per LIST response
2140 ;; mbx-list-sflag = "\Noselect" / "\Marked" / "\Unmarked"
2141 ;; ; Selectability flags; only one per LIST response
2143 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2144 ;; "\" quoted-specials
2146 ;; quoted-specials = DQUOTE / "\"
2148 (defun imap-parse-data-list (type)
2149 (let (flags delimiter mailbox)
2150 (setq flags (imap-parse-flag-list))
2151 (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2152 (setq delimiter (match-string 1))
2153 (goto-char (1+ (match-end 0)))
2154 (when (setq mailbox (imap-parse-mailbox))
2155 (imap-mailbox-put type t mailbox)
2156 (imap-mailbox-put 'list-flags flags mailbox)
2157 (imap-mailbox-put 'delimiter delimiter mailbox)))))
2159 ;; msg_att ::= "(" 1#("ENVELOPE" SPACE envelope /
2160 ;; "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2161 ;; "INTERNALDATE" SPACE date_time /
2162 ;; "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2163 ;; "RFC822.SIZE" SPACE number /
2164 ;; "BODY" ["STRUCTURE"] SPACE body /
2165 ;; "BODY" section ["<" number ">"] SPACE nstring /
2166 ;; "UID" SPACE uniqueid) ")"
2168 ;; date_time ::= <"> date_day_fixed "-" date_month "-" date_year
2169 ;; SPACE time SPACE zone <">
2171 ;; section ::= "[" [section_text / (nz_number *["." nz_number]
2172 ;; ["." (section_text / "MIME")])] "]"
2174 ;; section_text ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2175 ;; SPACE header_list / "TEXT"
2177 ;; header_fld_name ::= astring
2179 ;; header_list ::= "(" 1#header_fld_name ")"
2181 (defsubst imap-parse-header-list ()
2182 (when (eq (char-after) ?\()
2184 (while (not (eq (char-after) ?\)))
2186 (push (imap-parse-astring) strlist))
2188 (nreverse strlist))))
2190 (defsubst imap-parse-fetch-body-section ()
2192 (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2193 (if (eq (char-before) ? )
2195 (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2196 (search-forward "]" nil t))
2199 (defun imap-parse-fetch (response)
2200 (when (eq (char-after) ?\()
2201 (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2202 rfc822size body bodydetail bodystructure)
2203 (while (not (eq (char-after) ?\)))
2205 (let ((token (read (current-buffer))))
2207 (cond ((eq token 'UID)
2208 (setq uid (ignore-errors (read (current-buffer)))))
2210 (setq flags (imap-parse-flag-list)))
2211 ((eq token 'ENVELOPE)
2212 (setq envelope (imap-parse-envelope)))
2213 ((eq token 'INTERNALDATE)
2214 (setq internaldate (imap-parse-string)))
2216 (setq rfc822 (imap-parse-nstring)))
2217 ((eq token 'RFC822.HEADER)
2218 (setq rfc822header (imap-parse-nstring)))
2219 ((eq token 'RFC822.TEXT)
2220 (setq rfc822text (imap-parse-nstring)))
2221 ((eq token 'RFC822.SIZE)
2222 (setq rfc822size (read (current-buffer))))
2224 (if (eq (char-before) ?\[)
2226 (upcase (imap-parse-fetch-body-section))
2227 (and (eq (char-after) ?<)
2228 (buffer-substring (1+ (point))
2229 (search-forward ">" nil t)))
2230 (progn (imap-forward)
2231 (imap-parse-nstring)))
2233 (setq body (imap-parse-body))))
2234 ((eq token 'BODYSTRUCTURE)
2235 (setq bodystructure (imap-parse-body))))))
2237 (setq imap-current-message uid)
2238 (imap-message-put uid 'UID uid)
2239 (and flags (imap-message-put uid 'FLAGS flags))
2240 (and envelope (imap-message-put uid 'ENVELOPE envelope))
2241 (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2242 (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2243 (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2244 (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2245 (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2246 (and body (imap-message-put uid 'BODY body))
2247 (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2248 (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2249 (run-hooks 'imap-fetch-data-hook)))))
2251 ;; mailbox-data = ...
2252 ;; "STATUS" SP mailbox SP "("
2253 ;; [status-att SP number
2254 ;; *(SP status-att SP number)] ")"
2257 ;; status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2260 (defun imap-parse-status ()
2261 (let ((mailbox (imap-parse-mailbox)))
2262 (when (and mailbox (search-forward "(" nil t))
2263 (while (not (eq (char-after) ?\)))
2264 (let ((token (read (current-buffer))))
2265 (cond ((eq token 'MESSAGES)
2266 (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2268 (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2269 ((eq token 'UIDNEXT)
2270 (imap-mailbox-put 'uidnext (read (current-buffer)) mailbox))
2271 ((eq token 'UIDVALIDITY)
2272 (and (looking-at " \\([0-9]+\\)")
2273 (imap-mailbox-put 'uidvalidity (match-string 1) mailbox)
2274 (goto-char (match-end 1))))
2276 (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2278 (message "Unknown status data %s in mailbox %s ignored"
2279 token mailbox))))))))
2281 ;; acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2284 ;; identifier ::= astring
2286 ;; rights ::= astring
2288 (defun imap-parse-acl ()
2289 (let ((mailbox (imap-parse-mailbox))
2290 identifier rights acl)
2291 (while (eq (char-after) ?\ )
2293 (setq identifier (imap-parse-astring))
2295 (setq rights (imap-parse-astring))
2296 (setq acl (append acl (list (cons identifier rights)))))
2297 (imap-mailbox-put 'acl acl mailbox)))
2299 ;; flag-list = "(" [flag *(SP flag)] ")"
2301 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2302 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2303 ;; ; Does not include "\Recent"
2305 ;; flag-keyword = atom
2307 ;; flag-extension = "\" atom
2308 ;; ; Future expansion. Client implementations
2309 ;; ; MUST accept flag-extension flags. Server
2310 ;; ; implementations MUST NOT generate
2311 ;; ; flag-extension flags except as defined by
2312 ;; ; future standard or standards-track
2313 ;; ; revisions of this specification.
2315 (defun imap-parse-flag-list ()
2316 (let (flag-list start)
2317 (assert (eq (char-after) ?\() t "In imap-parse-flag-list")
2318 (while (and (not (eq (char-after) ?\)))
2321 ;; next line for Courier IMAP bug.
2322 (skip-chars-forward " ")
2324 (> (skip-chars-forward "^ )" (imap-point-at-eol)) 0))
2325 (push (buffer-substring start (point)) flag-list))
2326 (assert (eq (char-after) ?\)) t "In imap-parse-flag-list")
2328 (nreverse flag-list)))
2330 ;; envelope = "(" env-date SP env-subject SP env-from SP env-sender SP
2331 ;; env-reply-to SP env-to SP env-cc SP env-bcc SP
2332 ;; env-in-reply-to SP env-message-id ")"
2334 ;; env-bcc = "(" 1*address ")" / nil
2336 ;; env-cc = "(" 1*address ")" / nil
2338 ;; env-date = nstring
2340 ;; env-from = "(" 1*address ")" / nil
2342 ;; env-in-reply-to = nstring
2344 ;; env-message-id = nstring
2346 ;; env-reply-to = "(" 1*address ")" / nil
2348 ;; env-sender = "(" 1*address ")" / nil
2350 ;; env-subject = nstring
2352 ;; env-to = "(" 1*address ")" / nil
2354 (defun imap-parse-envelope ()
2355 (when (eq (char-after) ?\()
2357 (vector (prog1 (imap-parse-nstring) ;; date
2359 (prog1 (imap-parse-nstring) ;; subject
2361 (prog1 (imap-parse-address-list) ;; from
2363 (prog1 (imap-parse-address-list) ;; sender
2365 (prog1 (imap-parse-address-list) ;; reply-to
2367 (prog1 (imap-parse-address-list) ;; to
2369 (prog1 (imap-parse-address-list) ;; cc
2371 (prog1 (imap-parse-address-list) ;; bcc
2373 (prog1 (imap-parse-nstring) ;; in-reply-to
2375 (prog1 (imap-parse-nstring) ;; message-id
2378 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2380 (defsubst imap-parse-string-list ()
2381 (cond ((eq (char-after) ?\() ;; body-fld-param
2384 (while (setq str (imap-parse-string))
2386 ;; buggy stalker communigate pro 3.0 doesn't print SPC
2387 ;; between body-fld-param's sometimes
2388 (or (eq (char-after) ?\")
2390 (nreverse strlist)))
2394 ;; body-extension = nstring / number /
2395 ;; "(" body-extension *(SP body-extension) ")"
2396 ;; ; Future expansion. Client implementations
2397 ;; ; MUST accept body-extension fields. Server
2398 ;; ; implementations MUST NOT generate
2399 ;; ; body-extension fields except as defined by
2400 ;; ; future standard or standards-track
2401 ;; ; revisions of this specification.
2403 (defun imap-parse-body-extension ()
2404 (if (eq (char-after) ?\()
2407 (push (imap-parse-body-extension) b-e)
2408 (while (eq (char-after) ?\ )
2410 (push (imap-parse-body-extension) b-e))
2411 (assert (eq (char-after) ?\)) t "In imap-parse-body-extension")
2414 (or (imap-parse-number)
2415 (imap-parse-nstring))))
2417 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2418 ;; *(SP body-extension)]]
2419 ;; ; MUST NOT be returned on non-extensible
2422 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2423 ;; *(SP body-extension)]]
2424 ;; ; MUST NOT be returned on non-extensible
2427 (defsubst imap-parse-body-ext ()
2429 (when (eq (char-after) ?\ ) ;; body-fld-dsp
2432 (if (eq (char-after) ?\()
2435 (push (imap-parse-string) dsp)
2437 (push (imap-parse-string-list) dsp)
2439 (assert (imap-parse-nil) t "In imap-parse-body-ext"))
2440 (push (nreverse dsp) ext))
2441 (when (eq (char-after) ?\ ) ;; body-fld-lang
2443 (if (eq (char-after) ?\()
2444 (push (imap-parse-string-list) ext)
2445 (push (imap-parse-nstring) ext))
2446 (while (eq (char-after) ?\ ) ;; body-extension
2448 (setq ext (append (imap-parse-body-extension) ext)))))
2451 ;; body = "(" body-type-1part / body-type-mpart ")"
2453 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2454 ;; *(SP body-extension)]]
2455 ;; ; MUST NOT be returned on non-extensible
2458 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2459 ;; *(SP body-extension)]]
2460 ;; ; MUST NOT be returned on non-extensible
2463 ;; body-fields = body-fld-param SP body-fld-id SP body-fld-desc SP
2464 ;; body-fld-enc SP body-fld-octets
2466 ;; body-fld-desc = nstring
2468 ;; body-fld-dsp = "(" string SP body-fld-param ")" / nil
2470 ;; body-fld-enc = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2471 ;; "QUOTED-PRINTABLE") DQUOTE) / string
2473 ;; body-fld-id = nstring
2475 ;; body-fld-lang = nstring / "(" string *(SP string) ")"
2477 ;; body-fld-lines = number
2479 ;; body-fld-md5 = nstring
2481 ;; body-fld-octets = number
2483 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2485 ;; body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2486 ;; [SP body-ext-1part]
2488 ;; body-type-basic = media-basic SP body-fields
2489 ;; ; MESSAGE subtype MUST NOT be "RFC822"
2491 ;; body-type-msg = media-message SP body-fields SP envelope
2492 ;; SP body SP body-fld-lines
2494 ;; body-type-text = media-text SP body-fields SP body-fld-lines
2496 ;; body-type-mpart = 1*body SP media-subtype
2497 ;; [SP body-ext-mpart]
2499 ;; media-basic = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2500 ;; "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2501 ;; ; Defined in [MIME-IMT]
2503 ;; media-message = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2504 ;; ; Defined in [MIME-IMT]
2506 ;; media-subtype = string
2507 ;; ; Defined in [MIME-IMT]
2509 ;; media-text = DQUOTE "TEXT" DQUOTE SP media-subtype
2510 ;; ; Defined in [MIME-IMT]
2512 (defun imap-parse-body ()
2514 (when (eq (char-after) ?\()
2516 (if (eq (char-after) ?\()
2518 (while (and (eq (char-after) ?\()
2519 (setq subbody (imap-parse-body)))
2520 ;; buggy stalker communigate pro 3.0 insert a SPC between
2521 ;; parts in multiparts
2522 (when (and (eq (char-after) ?\ )
2523 (eq (char-after (1+ (point))) ?\())
2525 (push subbody body))
2527 (push (imap-parse-string) body) ;; media-subtype
2528 (when (eq (char-after) ?\ ) ;; body-ext-mpart:
2530 (if (eq (char-after) ?\() ;; body-fld-param
2531 (push (imap-parse-string-list) body)
2532 (push (and (imap-parse-nil) nil) body))
2534 (append (imap-parse-body-ext) body))) ;; body-ext-...
2535 (assert (eq (char-after) ?\)) t "In imap-parse-body")
2539 (push (imap-parse-string) body) ;; media-type
2541 (push (imap-parse-string) body) ;; media-subtype
2543 ;; next line for Sun SIMS bug
2544 (and (eq (char-after) ? ) (imap-forward))
2545 (if (eq (char-after) ?\() ;; body-fld-param
2546 (push (imap-parse-string-list) body)
2547 (push (and (imap-parse-nil) nil) body))
2549 (push (imap-parse-nstring) body) ;; body-fld-id
2551 (push (imap-parse-nstring) body) ;; body-fld-desc
2553 ;; next `or' for Sun SIMS bug, it regard body-fld-enc as a
2554 ;; nstring and return NIL instead of defaulting back to 7BIT
2555 ;; as the standard says.
2556 (push (or (imap-parse-nstring) "7BIT") body) ;; body-fld-enc
2558 (push (imap-parse-number) body) ;; body-fld-octets
2560 ;; ok, we're done parsing the required parts, what comes now is one
2563 ;; envelope (then we're parsing body-type-msg)
2564 ;; body-fld-lines (then we're parsing body-type-text)
2565 ;; body-ext-1part (then we're parsing body-type-basic)
2567 ;; the problem is that the two first are in turn optionally followed
2568 ;; by the third. So we parse the first two here (if there are any)...
2570 (when (eq (char-after) ?\ )
2573 (cond ((eq (char-after) ?\() ;; body-type-msg:
2574 (push (imap-parse-envelope) body) ;; envelope
2576 (push (imap-parse-body) body) ;; body
2577 ;; buggy stalker communigate pro 3.0 doesn't print
2578 ;; number of lines in message/rfc822 attachment
2579 (if (eq (char-after) ?\))
2582 (push (imap-parse-number) body))) ;; body-fld-lines
2583 ((setq lines (imap-parse-number)) ;; body-type-text:
2584 (push lines body)) ;; body-fld-lines
2586 (backward-char))))) ;; no match...
2588 ;; ...and then parse the third one here...
2590 (when (eq (char-after) ?\ ) ;; body-ext-1part:
2592 (push (imap-parse-nstring) body) ;; body-fld-md5
2593 (setq body (append (imap-parse-body-ext) body))) ;; body-ext-1part..
2595 (assert (eq (char-after) ?\)) t "In imap-parse-body 2")
2599 (when imap-debug ; (untrace-all)
2601 (buffer-disable-undo (get-buffer-create imap-debug-buffer))
2602 (mapcar (lambda (f) (trace-function-background f imap-debug-buffer))
2614 imap-interactive-login
2630 imap-send-command-wait
2635 imap-current-mailbox
2636 imap-current-mailbox-p-1
2637 imap-current-mailbox-p
2638 imap-mailbox-select-1
2640 imap-mailbox-examine-1
2641 imap-mailbox-examine
2642 imap-mailbox-unselect
2643 imap-mailbox-expunge
2645 imap-mailbox-create-1
2651 imap-mailbox-subscribe
2652 imap-mailbox-unsubscribe
2654 imap-mailbox-acl-get
2655 imap-mailbox-acl-set
2656 imap-mailbox-acl-delete
2657 imap-current-message
2658 imap-list-to-message-set
2665 imap-message-flag-permanent-p
2666 imap-message-flags-set
2667 imap-message-flags-del
2668 imap-message-flags-add
2669 imap-message-copyuid-1
2670 imap-message-copyuid
2672 imap-message-appenduid-1
2673 imap-message-appenduid
2685 imap-parse-resp-text
2686 imap-parse-resp-text-code
2687 imap-parse-data-list
2691 imap-parse-flag-list
2693 imap-parse-body-extension
2699 ;;; imap.el ends here