1 ;;; imap.el --- imap library
2 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002
3 ;; Free Software Foundation, Inc.
5 ;; Author: Simon Josefsson <jas@pdc.kth.se>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
27 ;; imap.el is a elisp library providing an interface for talking to
30 ;; imap.el is roughly divided in two parts, one that parses IMAP
31 ;; responses from the server and storing data into buffer-local
32 ;; variables, and one for utility functions which send commands to
33 ;; server, waits for an answer, and return information. The latter
34 ;; part is layered on top of the previous.
36 ;; The imap.el API consist of the following functions, other functions
37 ;; in this file should not be called directly and the result of doing
38 ;; so are at best undefined.
42 ;; imap-open, imap-opened, imap-authenticate, imap-close,
43 ;; imap-capability, imap-namespace, imap-error-text
47 ;; imap-mailbox-get, imap-mailbox-map, imap-current-mailbox,
48 ;; imap-current-mailbox-p, imap-search, imap-mailbox-select,
49 ;; imap-mailbox-examine, imap-mailbox-unselect, imap-mailbox-expunge
50 ;; imap-mailbox-close, imap-mailbox-create, imap-mailbox-delete
51 ;; imap-mailbox-rename, imap-mailbox-lsub, imap-mailbox-list
52 ;; imap-mailbox-subscribe, imap-mailbox-unsubscribe, imap-mailbox-status
53 ;; imap-mailbox-acl-get, imap-mailbox-acl-set, imap-mailbox-acl-delete
57 ;; imap-fetch-asynch, imap-fetch,
58 ;; imap-current-message, imap-list-to-message-set,
59 ;; imap-message-get, imap-message-map
60 ;; imap-message-envelope-date, imap-message-envelope-subject,
61 ;; imap-message-envelope-from, imap-message-envelope-sender,
62 ;; imap-message-envelope-reply-to, imap-message-envelope-to,
63 ;; imap-message-envelope-cc, imap-message-envelope-bcc
64 ;; imap-message-envelope-in-reply-to, imap-message-envelope-message-id
65 ;; imap-message-body, imap-message-flag-permanent-p
66 ;; imap-message-flags-set, imap-message-flags-del
67 ;; imap-message-flags-add, imap-message-copyuid
68 ;; imap-message-copy, imap-message-appenduid
69 ;; imap-message-append, imap-envelope-from
72 ;; It is my hope that theese commands should be pretty self
73 ;; explanatory for someone that know IMAP. All functions have
74 ;; additional documentation on how to invoke them.
76 ;; imap.el support RFC1730/2060 (IMAP4/IMAP4rev1), implemented IMAP
77 ;; extensions are RFC2195 (CRAM-MD5), RFC2086 (ACL), RFC2342
78 ;; (NAMESPACE), RFC2359 (UIDPLUS), the IMAP-part of RFC2595 (STARTTLS,
79 ;; LOGINDISABLED) (with use of external library starttls.el and
80 ;; program starttls) and the GSSAPI / kerberos V4 sections of RFC1731
81 ;; (with use of external program `imtest'). It also take advantage
82 ;; the UNSELECT extension in Cyrus IMAPD.
84 ;; Without the work of John McClary Prevost and Jim Radford this library
85 ;; would not have seen the light of day. Many thanks.
87 ;; This is a transcript of short interactive session for demonstration
90 ;; (imap-open "my.mail.server")
91 ;; => " *imap* my.mail.server:0"
93 ;; The rest are invoked with current buffer as the buffer returned by
94 ;; `imap-open'. It is possible to do all without this, but it would
95 ;; look ugly here since `buffer' is always the last argument for all
96 ;; imap.el API functions.
98 ;; (imap-authenticate "myusername" "mypassword")
101 ;; (imap-mailbox-lsub "*")
102 ;; => ("INBOX.sentmail" "INBOX.private" "INBOX.draft" "INBOX.spam")
104 ;; (imap-mailbox-list "INBOX.n%")
105 ;; => ("INBOX.namedroppers" "INBOX.nnimap" "INBOX.ntbugtraq")
107 ;; (imap-mailbox-select "INBOX.nnimap")
110 ;; (imap-mailbox-get 'exists)
113 ;; (imap-mailbox-get 'uidvalidity)
116 ;; (imap-search "FLAGGED SINCE 18-DEC-98")
119 ;; (imap-fetch 235 "RFC822.PEEK" 'RFC822)
120 ;; => "X-Sieve: cmu-sieve 1.3^M\nX-Username: <jas@pdc.kth.se>^M\r...."
124 ;; o Parse UIDs as strings? We need to overcome the 28 bit limit somehow.
125 ;; o Don't use `read' at all (important places already fixed)
126 ;; o Accept list of articles instead of message set string in most
127 ;; imap-message-* functions.
131 ;; - 19991218 added starttls/digest-md5 patch,
132 ;; by Daiki Ueno <ueno@ueda.info.waseda.ac.jp>
133 ;; NB! you need SLIM for starttls.el and digest-md5.el
134 ;; - 19991023 commited to pgnus
139 (eval-when-compile (require 'cl))
141 (autoload 'open-ssl-stream "ssl")
142 (autoload 'base64-decode-string "base64")
143 (autoload 'base64-encode-string "base64")
144 (autoload 'starttls-open-stream "starttls")
145 (autoload 'starttls-negotiate "starttls")
146 (autoload 'digest-md5-parse-digest-challenge "digest-md5")
147 (autoload 'digest-md5-digest-response "digest-md5")
148 (autoload 'digest-md5-digest-uri "digest-md5")
149 (autoload 'digest-md5-challenge "digest-md5")
150 (autoload 'rfc2104-hash "rfc2104")
151 (autoload 'md5 "md5")
152 (autoload 'utf7-encode "utf7")
153 (autoload 'utf7-decode "utf7")
154 (autoload 'format-spec "format-spec")
155 (autoload 'format-spec-make "format-spec")
156 ;; Avoid use gnus-point-at-eol so we're independent of Gnus. These
157 ;; days we have point-at-eol anyhow.
158 (if (fboundp 'point-at-eol)
159 (defalias 'imap-point-at-eol 'point-at-eol)
160 (defun imap-point-at-eol ()
168 "Low-level IMAP issues."
172 (defcustom imap-kerberos4-program '("imtest -m kerberos_v4 -u %l -p %p %s"
174 "List of strings containing commands for Kerberos 4 authentication.
175 %s is replaced with server hostname, %p with port to connect to, and
176 %l with the value of `imap-default-user'. The program should accept
177 IMAP commands on stdin and return responses to stdout. Each entry in
178 the list is tried until a successful connection is made."
180 :type '(repeat string))
182 (defcustom imap-gssapi-program '("imtest -m gssapi -u %l -p %p %s")
183 "List of strings containing commands for GSSAPI (krb5) authentication.
184 %s is replaced with server hostname, %p with port to connect to, and
185 %l with the value of `imap-default-user'. The program should accept
186 IMAP commands on stdin and return responses to stdout. Each entry in
187 the list is tried until a successful connection is made."
189 :type '(repeat string))
191 (defcustom imap-ssl-program '("openssl s_client -quiet -ssl3 -connect %s:%p"
192 "openssl s_client -quiet -ssl2 -connect %s:%p"
193 "s_client -quiet -ssl3 -connect %s:%p"
194 "s_client -quiet -ssl2 -connect %s:%p")
195 "A string, or list of strings, containing commands for SSL connections.
196 Within a string, %s is replaced with the server address and %p with
197 port number on server. The program should accept IMAP commands on
198 stdin and return responses to stdout. Each entry in the list is tried
199 until a successful connection is made."
201 :type '(choice string
204 (defcustom imap-shell-program '("ssh %s imapd"
206 "ssh %g ssh %s imapd"
207 "rsh %g rsh %s imapd")
208 "A list of strings, containing commands for IMAP connection.
209 Within a string, %s is replaced with the server address, %p with port
210 number on server, %g with `imap-shell-host', and %l with
211 `imap-default-user'. The program should read IMAP commands from stdin
212 and write IMAP response to stdout. Each entry in the list is tried
213 until a successful connection is made."
215 :type '(repeat string))
217 (defcustom imap-process-connection-type nil
218 "*Value for `process-connection-type' to use for Kerberos4 and GSSAPI."
222 (defcustom imap-use-utf7 t
223 "If non-nil, do utf7 encoding/decoding of mailbox names.
224 Since the UTF7 decoding currently only decodes into ISO-8859-1
225 characters, you may disable this decoding if you need to access UTF7
226 encoded mailboxes which doesn't translate into ISO-8859-1."
230 (defcustom imap-log nil
231 "If non-nil, a imap session trace is placed in *imap-log* buffer."
235 (defcustom imap-debug nil
236 "If non-nil, random debug spews are placed in *imap-debug* buffer."
240 (defcustom imap-shell-host "gateway"
241 "Hostname of rlogin proxy."
245 (defcustom imap-default-user (user-login-name)
246 "Default username to use."
250 ;; Various variables.
252 (defvar imap-fetch-data-hook nil
253 "Hooks called after receiving each FETCH response.")
255 (defvar imap-streams '(gssapi kerberos4 starttls ssl network shell)
256 "Priority of streams to consider when opening connection to server.")
258 (defvar imap-stream-alist
259 '((gssapi imap-gssapi-stream-p imap-gssapi-open)
260 (kerberos4 imap-kerberos4-stream-p imap-kerberos4-open)
261 (ssl imap-ssl-p imap-ssl-open)
262 (network imap-network-p imap-network-open)
263 (shell imap-shell-p imap-shell-open)
264 (starttls imap-starttls-p imap-starttls-open))
265 "Definition of network streams.
269 NAME names the stream, CHECK is a function returning non-nil if the
270 server support the stream and OPEN is a function for opening the
273 (defvar imap-authenticators '(gssapi
279 "Priority of authenticators to consider when authenticating to server.")
281 (defvar imap-authenticator-alist
282 '((gssapi imap-gssapi-auth-p imap-gssapi-auth)
283 (kerberos4 imap-kerberos4-auth-p imap-kerberos4-auth)
284 (cram-md5 imap-cram-md5-p imap-cram-md5-auth)
285 (login imap-login-p imap-login-auth)
286 (anonymous imap-anonymous-p imap-anonymous-auth)
287 (digest-md5 imap-digest-md5-p imap-digest-md5-auth))
288 "Definition of authenticators.
290 \(NAME CHECK AUTHENTICATE)
292 NAME names the authenticator. CHECK is a function returning non-nil if
293 the server support the authenticator and AUTHENTICATE is a function
294 for doing the actual authentication.")
296 (defvar imap-error nil
297 "Error codes from the last command.")
299 ;; Internal constants. Change theese and die.
301 (defconst imap-default-port 143)
302 (defconst imap-default-ssl-port 993)
303 (defconst imap-default-stream 'network)
304 (defconst imap-coding-system-for-read 'binary)
305 (defconst imap-coding-system-for-write 'binary)
306 (defconst imap-local-variables '(imap-server
315 imap-current-target-mailbox
324 imap-calculate-literal-size-first
326 (defconst imap-log-buffer "*imap-log*")
327 (defconst imap-debug-buffer "*imap-debug*")
329 ;; Internal variables.
331 (defvar imap-stream nil)
332 (defvar imap-auth nil)
333 (defvar imap-server nil)
334 (defvar imap-port nil)
335 (defvar imap-username nil)
336 (defvar imap-password nil)
337 (defvar imap-calculate-literal-size-first nil)
338 (defvar imap-state 'closed
340 Valid states are `closed', `initial', `nonauth', `auth', `selected'
343 (defvar imap-server-eol "\r\n"
344 "The EOL string sent from the server.")
346 (defvar imap-client-eol "\r\n"
347 "The EOL string we send to the server.")
349 (defvar imap-current-mailbox nil
350 "Current mailbox name.")
352 (defvar imap-current-target-mailbox nil
353 "Current target mailbox for COPY and APPEND commands.")
355 (defvar imap-mailbox-data nil
356 "Obarray with mailbox data.")
358 (defvar imap-mailbox-prime 997
359 "Length of imap-mailbox-data.")
361 (defvar imap-current-message nil
362 "Current message number.")
364 (defvar imap-message-data nil
365 "Obarray with message data.")
367 (defvar imap-message-prime 997
368 "Length of imap-message-data.")
370 (defvar imap-capability nil
371 "Capability for server.")
373 (defvar imap-namespace nil
374 "Namespace for current server.")
376 (defvar imap-reached-tag 0
377 "Lower limit on command tags that have been parsed.")
379 (defvar imap-failed-tags nil
380 "Alist of tags that failed.
381 Each element is a list with four elements; tag (a integer), response
382 state (a symbol, `OK', `NO' or `BAD'), response code (a string), and
383 human readable response text (a string).")
386 "Command tag number.")
388 (defvar imap-process nil
391 (defvar imap-continuation nil
392 "Non-nil indicates that the server emitted a continuation request.
393 The actually value is really the text on the continuation line.")
395 (defvar imap-callbacks nil
396 "List of response tags and callbacks, on the form `(number . function)'.
397 The function should take two arguments, the first the IMAP tag and the
398 second the status (OK, NO, BAD etc) of the command.")
401 ;; Utility functions:
403 (defun imap-remassoc (key alist)
404 "Delete by side effect any elements of LIST whose car is `equal' to KEY.
405 The modified LIST is returned. If the first member
406 of LIST has a car that is `equal' to KEY, there is no way to remove it
407 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
408 sure of changing the value of `foo'."
410 (if (equal key (caar alist))
412 (setcdr alist (imap-remassoc key (cdr alist)))
415 (defsubst imap-disable-multibyte ()
416 "Enable multibyte in the current buffer."
417 (when (fboundp 'set-buffer-multibyte)
418 (set-buffer-multibyte nil)))
420 (defun imap-read-passwd (prompt &rest args)
421 "Read a password using PROMPT.
422 If ARGS, PROMPT is used as an argument to `format'."
423 (let ((prompt (if args
424 (apply 'format prompt args)
426 (funcall (if (or (fboundp 'read-passwd)
428 (fboundp 'read-passwd))
429 (and (load "passwd" t)
430 (fboundp 'read-passwd)))
432 (autoload 'ange-ftp-read-passwd "ange-ftp")
433 'ange-ftp-read-passwd)
436 (defsubst imap-utf7-encode (string)
440 (utf7-encode string t)
442 "imap: Could not UTF7 encode `%s', using it unencoded..."
447 (defsubst imap-utf7-decode (string)
451 (utf7-decode string t)
453 "imap: Could not UTF7 decode `%s', using it undecoded..."
458 (defsubst imap-ok-p (status)
461 (setq imap-error status)
464 (defun imap-error-text (&optional buffer)
465 (with-current-buffer (or buffer (current-buffer))
466 (nth 3 (car imap-failed-tags))))
469 ;; Server functions; stream stuff:
471 (defun imap-kerberos4-stream-p (buffer)
472 (imap-capability 'AUTH=KERBEROS_V4 buffer))
474 (defun imap-kerberos4-open (name buffer server port)
475 (let ((cmds imap-kerberos4-program)
477 (while (and (not done) (setq cmd (pop cmds)))
478 (message "Opening Kerberos 4 IMAP connection with `%s'..." cmd)
480 (let* ((port (or port imap-default-port))
481 (coding-system-for-read imap-coding-system-for-read)
482 (coding-system-for-write imap-coding-system-for-write)
483 (process-connection-type imap-process-connection-type)
484 (process (start-process
485 name buffer shell-file-name shell-command-switch
490 ?p (number-to-string port)
491 ?l imap-default-user))))
494 (with-current-buffer buffer
495 (setq imap-client-eol "\n"
496 imap-calculate-literal-size-first t)
497 (while (and (memq (process-status process) '(open run))
498 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
499 (goto-char (point-min))
500 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
501 (or (while (looking-at "^C:")
504 ;; cyrus 1.6 imtest print "S: " before server greeting
505 (or (not (looking-at "S: "))
508 (not (and (imap-parse-greeting)
509 ;; success in imtest < 1.6:
510 (or (re-search-forward
511 "^__\\(.*\\)__\n" nil t)
512 ;; success in imtest 1.6:
514 "^\\(Authenticat.*\\)" nil t))
515 (setq response (match-string 1)))))
516 (accept-process-output process 1)
519 (with-current-buffer (get-buffer-create imap-log-buffer)
520 (imap-disable-multibyte)
521 (buffer-disable-undo)
522 (goto-char (point-max))
523 (insert-buffer-substring buffer)))
525 (message "Opening Kerberos 4 IMAP connection with `%s'...%s" cmd
526 (if response (concat "done, " response) "failed"))
527 (if (and response (let ((case-fold-search nil))
528 (not (string-match "failed" response))))
530 (if (memq (process-status process) '(open run))
531 (imap-send-command-wait "LOGOUT"))
532 (delete-process process)
536 (defun imap-gssapi-stream-p (buffer)
537 (imap-capability 'AUTH=GSSAPI buffer))
539 (defun imap-gssapi-open (name buffer server port)
540 (let ((cmds imap-gssapi-program)
542 (while (and (not done) (setq cmd (pop cmds)))
543 (message "Opening GSSAPI IMAP connection with `%s'..." cmd)
544 (let* ((port (or port imap-default-port))
545 (coding-system-for-read imap-coding-system-for-read)
546 (coding-system-for-write imap-coding-system-for-write)
547 (process-connection-type imap-process-connection-type)
548 (process (start-process
549 name buffer shell-file-name shell-command-switch
554 ?p (number-to-string port)
555 ?l imap-default-user))))
558 (with-current-buffer buffer
559 (setq imap-client-eol "\n"
560 imap-calculate-literal-size-first t)
561 (while (and (memq (process-status process) '(open run))
562 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
563 (goto-char (point-min))
564 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
565 (or (while (looking-at "^C:")
568 ;; cyrus 1.6 imtest print "S: " before server greeting
569 (or (not (looking-at "S: "))
572 (not (and (imap-parse-greeting)
573 ;; success in imtest 1.6:
575 "^\\(Authenticat.*\\)" nil t)
576 (setq response (match-string 1)))))
577 (accept-process-output process 1)
580 (with-current-buffer (get-buffer-create imap-log-buffer)
581 (imap-disable-multibyte)
582 (buffer-disable-undo)
583 (goto-char (point-max))
584 (insert-buffer-substring buffer)))
586 (message "GSSAPI IMAP connection: %s" (or response "failed"))
587 (if (and response (let ((case-fold-search nil))
588 (not (string-match "failed" response))))
590 (if (memq (process-status process) '(open run))
591 (imap-send-command-wait "LOGOUT"))
592 (delete-process process)
596 (defun imap-ssl-p (buffer)
599 (defun imap-ssl-open (name buffer server port)
600 "Open a SSL connection to server."
601 (let ((cmds (if (listp imap-ssl-program) imap-ssl-program
602 (list imap-ssl-program)))
607 (while (and (not done) (setq cmd (pop cmds)))
608 (message "imap: Opening SSL connection with `%s'..." cmd)
609 (let* ((port (or port imap-default-ssl-port))
610 (coding-system-for-read imap-coding-system-for-read)
611 (coding-system-for-write imap-coding-system-for-write)
612 (ssl-program-name shell-file-name)
613 (ssl-program-arguments
614 (list shell-command-switch
615 (format-spec cmd (format-spec-make
617 ?p (number-to-string port)))))
619 (when (setq process (condition-case ()
620 (open-ssl-stream name buffer server port)
622 (with-current-buffer buffer
623 (goto-char (point-min))
624 (while (and (memq (process-status process) '(open run))
625 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
626 (goto-char (point-max))
628 (not (imap-parse-greeting)))
629 (accept-process-output process 1)
632 (with-current-buffer (get-buffer-create imap-log-buffer)
633 (imap-disable-multibyte)
634 (buffer-disable-undo)
635 (goto-char (point-max))
636 (insert-buffer-substring buffer)))
638 (when (memq (process-status process) '(open run))
639 (setq done process))))))
642 (message "imap: Opening SSL connection with `%s'...done" cmd)
644 (message "imap: Opening SSL connection with `%s'...failed" cmd)
647 (defun imap-network-p (buffer)
650 (defun imap-network-open (name buffer server port)
651 (let* ((port (or port imap-default-port))
652 (coding-system-for-read imap-coding-system-for-read)
653 (coding-system-for-write imap-coding-system-for-write)
654 (process (open-network-stream name buffer server port)))
656 (while (and (memq (process-status process) '(open run))
657 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
658 (goto-char (point-min))
659 (not (imap-parse-greeting)))
660 (accept-process-output process 1)
663 (with-current-buffer (get-buffer-create imap-log-buffer)
664 (imap-disable-multibyte)
665 (buffer-disable-undo)
666 (goto-char (point-max))
667 (insert-buffer-substring buffer)))
668 (when (memq (process-status process) '(open run))
671 (defun imap-shell-p (buffer)
674 (defun imap-shell-open (name buffer server port)
675 (let ((cmds imap-shell-program)
677 (while (and (not done) (setq cmd (pop cmds)))
678 (message "imap: Opening IMAP connection with `%s'..." cmd)
679 (setq imap-client-eol "\n")
680 (let* ((port (or port imap-default-port))
681 (coding-system-for-read imap-coding-system-for-read)
682 (coding-system-for-write imap-coding-system-for-write)
683 (process (start-process
684 name buffer shell-file-name shell-command-switch
690 ?p (number-to-string port)
691 ?l imap-default-user)))))
693 (while (and (memq (process-status process) '(open run))
694 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
695 (goto-char (point-min))
696 (not (imap-parse-greeting)))
697 (accept-process-output process 1)
700 (with-current-buffer (get-buffer-create imap-log-buffer)
701 (imap-disable-multibyte)
702 (buffer-disable-undo)
703 (goto-char (point-max))
704 (insert-buffer-substring buffer)))
706 (when (memq (process-status process) '(open run))
707 (setq done process)))))
710 (message "imap: Opening IMAP connection with `%s'...done" cmd)
712 (message "imap: Opening IMAP connection with `%s'...failed" cmd)
715 (defun imap-starttls-p (buffer)
716 (imap-capability 'STARTTLS buffer))
718 (defun imap-starttls-open (name buffer server port)
719 (let* ((port (or port imap-default-port))
720 (coding-system-for-read imap-coding-system-for-read)
721 (coding-system-for-write imap-coding-system-for-write)
722 (process (starttls-open-stream name buffer server port))
724 (message "imap: Connecting with STARTTLS...")
726 (while (and (memq (process-status process) '(open run))
727 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
728 (goto-char (point-min))
729 (not (imap-parse-greeting)))
730 (accept-process-output process 1)
733 (with-current-buffer (get-buffer-create imap-log-buffer)
734 (buffer-disable-undo)
735 (goto-char (point-max))
736 (insert-buffer-substring buffer)))
737 (let ((imap-process process))
740 (set-process-filter imap-process 'imap-arrival-filter)
741 (when (and (eq imap-stream 'starttls)
742 (imap-ok-p (imap-send-command-wait "STARTTLS")))
743 (starttls-negotiate imap-process)))
744 (set-process-filter imap-process nil)))
745 (when (memq (process-status process) '(open run))
746 (setq done process)))
749 (message "imap: Connecting with STARTTLS...done")
751 (message "imap: Connecting with STARTTLS...failed")
754 ;; Server functions; authenticator stuff:
756 (defun imap-interactive-login (buffer loginfunc)
757 "Login to server in BUFFER.
758 LOGINFUNC is passed a username and a password, it should return t if
759 it where sucessful authenticating itself to the server, nil otherwise.
760 Returns t if login was successful, nil otherwise."
761 (with-current-buffer buffer
762 (make-local-variable 'imap-username)
763 (make-local-variable 'imap-password)
764 (let (user passwd ret)
765 ;; (condition-case ()
766 (while (or (not user) (not passwd))
767 (setq user (or imap-username
768 (read-from-minibuffer
769 (concat "IMAP username for " imap-server ": ")
770 (or user imap-default-user))))
771 (setq passwd (or imap-password
773 (concat "IMAP password for " user "@"
775 (when (and user passwd)
776 (if (funcall loginfunc user passwd)
780 (if (and (not imap-password)
781 (y-or-n-p "Store password for this session? "))
782 (setq imap-password passwd)))
783 (message "Login failed...")
786 ;; (quit (with-current-buffer buffer
789 ;; (error (with-current-buffer buffer
794 (defun imap-gssapi-auth-p (buffer)
795 (and (imap-capability 'AUTH=GSSAPI buffer)
796 (eq imap-state 'gssapi)))
798 (defun imap-gssapi-auth (buffer)
799 (message "imap: Authenticating using GSSAPI...%s"
800 (if (eq imap-stream 'gssapi) "done" "failed"))
801 (eq imap-stream 'gssapi))
803 (defun imap-kerberos4-auth-p (buffer)
804 (and (imap-capability 'AUTH=KERBEROS_V4 buffer)
805 (eq imap-state 'kerberos4)))
807 (defun imap-kerberos4-auth (buffer)
808 (message "imap: Authenticating using Kerberos 4...%s"
809 (if (eq imap-stream 'kerberos4) "done" "failed"))
810 (eq imap-stream 'kerberos4))
812 (defun imap-cram-md5-p (buffer)
813 (imap-capability 'AUTH=CRAM-MD5 buffer))
815 (defun imap-cram-md5-auth (buffer)
816 "Login to server using the AUTH CRAM-MD5 method."
817 (message "imap: Authenticating using CRAM-MD5...")
818 (let ((done (imap-interactive-login
820 (lambda (user passwd)
822 (imap-send-command-wait
824 "AUTHENTICATE CRAM-MD5"
826 (let* ((decoded (base64-decode-string challenge))
827 (hash (rfc2104-hash 'md5 64 16 passwd decoded))
828 (response (concat user " " hash))
829 (encoded (base64-encode-string response)))
832 (message "imap: Authenticating using CRAM-MD5...done")
833 (message "imap: Authenticating using CRAM-MD5...failed"))))
835 (defun imap-login-p (buffer)
836 (and (not (imap-capability 'LOGINDISABLED buffer))
837 (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
839 (defun imap-login-auth (buffer)
840 "Login to server using the LOGIN command."
841 (message "imap: Plaintext authentication...")
842 (imap-interactive-login buffer
843 (lambda (user passwd)
844 (imap-ok-p (imap-send-command-wait
845 (concat "LOGIN \"" user "\" \""
848 (defun imap-anonymous-p (buffer)
851 (defun imap-anonymous-auth (buffer)
852 (message "imap: Loging in anonymously...")
853 (with-current-buffer buffer
854 (imap-ok-p (imap-send-command-wait
855 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
856 (system-name)) "\"")))))
858 (defun imap-digest-md5-p (buffer)
859 (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
861 (require 'digest-md5)
864 (defun imap-digest-md5-auth (buffer)
865 "Login to server using the AUTH DIGEST-MD5 method."
866 (message "imap: Authenticating using DIGEST-MD5...")
867 (imap-interactive-login
869 (lambda (user passwd)
873 "AUTHENTICATE DIGEST-MD5"
875 (digest-md5-parse-digest-challenge
876 (base64-decode-string challenge))
878 (digest-md5-digest-uri
879 "imap" (digest-md5-challenge 'realm)))
881 (digest-md5-digest-response
882 user passwd digest-uri)))
883 (base64-encode-string response 'no-line-break))))
885 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
887 (setq imap-continuation nil)
888 (imap-send-command-1 "")
889 (imap-ok-p (imap-wait-for-tag tag)))))))
893 (defun imap-open-1 (buffer)
894 (with-current-buffer buffer
896 (setq imap-current-mailbox nil
897 imap-current-message nil
899 imap-process (condition-case ()
900 (funcall (nth 2 (assq imap-stream
902 "imap" buffer imap-server imap-port)
905 (set-process-filter imap-process 'imap-arrival-filter)
906 (set-process-sentinel imap-process 'imap-sentinel)
907 (while (and (eq imap-state 'initial)
908 (memq (process-status imap-process) '(open run)))
909 (message "Waiting for response from %s..." imap-server)
910 (accept-process-output imap-process 1))
911 (message "Waiting for response from %s...done" imap-server)
912 (and (memq (process-status imap-process) '(open run))
915 (defun imap-open (server &optional port stream auth buffer)
916 "Open a IMAP connection to host SERVER at PORT returning a buffer.
917 If PORT is unspecified, a default value is used (143 except
918 for SSL which use 993).
919 STREAM indicates the stream to use, see `imap-streams' for available
920 streams. If nil, it choices the best stream the server is capable of.
921 AUTH indicates authenticator to use, see `imap-authenticators' for
922 available authenticators. If nil, it choices the best stream the
923 server is capable of.
924 BUFFER can be a buffer or a name of a buffer, which is created if
925 necessery. If nil, the buffer name is generated."
926 (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
927 (with-current-buffer (get-buffer-create buffer)
928 (if (imap-opened buffer)
930 (mapcar 'make-local-variable imap-local-variables)
931 (imap-disable-multibyte)
932 (buffer-disable-undo)
933 (setq imap-server (or server imap-server))
934 (setq imap-port (or port imap-port))
935 (setq imap-auth (or auth imap-auth))
936 (setq imap-stream (or stream imap-stream))
937 (message "imap: Connecting to %s..." imap-server)
938 (if (null (let ((imap-stream (or imap-stream imap-default-stream)))
939 (imap-open-1 buffer)))
941 (message "imap: Connecting to %s...failed" imap-server)
943 (when (null imap-stream)
944 ;; Need to choose stream.
945 (let ((streams imap-streams))
946 (while (setq stream (pop streams))
947 ;; OK to use this stream?
948 (when (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
950 (if (not (eq imap-default-stream stream))
952 (mapcar 'make-local-variable imap-local-variables)
953 (imap-disable-multibyte)
954 (buffer-disable-undo)
955 (message "imap: Reconnecting with stream `%s'..." stream)
956 (if (null (let ((imap-stream stream))
957 (imap-open-1 (current-buffer))))
958 (message "imap: Reconnecting with stream `%s'...failed"
960 ;; We're done, kill the first connection
963 (rename-buffer buffer)
964 (message "imap: Reconnecting with stream `%s'...done"
966 (setq imap-stream stream)
967 (setq imap-capability nil)
970 (message "imap: Connecting to %s...done" imap-server)
971 (setq imap-stream stream)
972 (setq imap-capability nil)
973 (setq streams nil))))))
974 (when (imap-opened buffer)
975 (setq imap-mailbox-data (make-vector imap-mailbox-prime 0)))
979 (defun imap-opened (&optional buffer)
980 "Return non-nil if connection to imap server in BUFFER is open.
981 If BUFFER is nil then the current buffer is used."
982 (and (setq buffer (get-buffer (or buffer (current-buffer))))
983 (buffer-live-p buffer)
984 (with-current-buffer buffer
986 (memq (process-status imap-process) '(open run))))))
988 (defun imap-authenticate (&optional user passwd buffer)
989 "Authenticate to server in BUFFER, using current buffer if nil.
990 It uses the authenticator specified when opening the server. If the
991 authenticator requires username/passwords, they are queried from the
992 user and optionally stored in the buffer. If USER and/or PASSWD is
993 specified, the user will not be questioned and the username and/or
994 password is remembered in the buffer."
995 (with-current-buffer (or buffer (current-buffer))
996 (if (not (eq imap-state 'nonauth))
997 (or (eq imap-state 'auth)
998 (eq imap-state 'select)
999 (eq imap-state 'examine))
1000 (make-local-variable 'imap-username)
1001 (make-local-variable 'imap-password)
1002 (if user (setq imap-username user))
1003 (if passwd (setq imap-password passwd))
1005 (and (funcall (nth 2 (assq imap-auth
1006 imap-authenticator-alist)) buffer)
1007 (setq imap-state 'auth))
1008 ;; Choose authenticator.
1010 (auths imap-authenticators))
1011 (while (setq auth (pop auths))
1012 ;; OK to use authenticator?
1013 (when (funcall (nth 1 (assq auth imap-authenticator-alist)) buffer)
1014 (message "imap: Authenticating to `%s' using `%s'..."
1016 (if (funcall (nth 2 (assq auth imap-authenticator-alist)) buffer)
1018 (message "imap: Authenticating to `%s' using `%s'...done"
1020 (setq imap-auth auth
1022 (message "imap: Authenticating to `%s' using `%s'...failed"
1023 imap-server auth)))))
1026 (defun imap-close (&optional buffer)
1027 "Close connection to server in BUFFER.
1028 If BUFFER is nil, the current buffer is used."
1029 (with-current-buffer (or buffer (current-buffer))
1032 (imap-send-command-wait "LOGOUT")
1034 (when (and imap-process
1035 (memq (process-status imap-process) '(open run)))
1036 (delete-process imap-process))
1037 (setq imap-current-mailbox nil
1038 imap-current-message nil
1043 (defun imap-capability (&optional identifier buffer)
1044 "Return a list of identifiers which server in BUFFER support.
1045 If IDENTIFIER, return non-nil if it's among the servers capabilities.
1046 If BUFFER is nil, the current buffer is assumed."
1047 (with-current-buffer (or buffer (current-buffer))
1048 (unless imap-capability
1049 (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
1050 (setq imap-capability '(IMAP2))))
1052 (memq (intern (upcase (symbol-name identifier))) imap-capability)
1055 (defun imap-namespace (&optional buffer)
1056 "Return a namespace hierarchy at server in BUFFER.
1057 If BUFFER is nil, the current buffer is assumed."
1058 (with-current-buffer (or buffer (current-buffer))
1059 (unless imap-namespace
1060 (when (imap-capability 'NAMESPACE)
1061 (imap-send-command-wait "NAMESPACE")))
1064 (defun imap-send-command-wait (command &optional buffer)
1065 (imap-wait-for-tag (imap-send-command command buffer) buffer))
1068 ;; Mailbox functions:
1070 (defun imap-mailbox-put (propname value &optional mailbox buffer)
1071 (with-current-buffer (or buffer (current-buffer))
1072 (if imap-mailbox-data
1073 (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
1075 (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
1076 propname value mailbox (current-buffer)))
1079 (defsubst imap-mailbox-get-1 (propname &optional mailbox)
1080 (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
1083 (defun imap-mailbox-get (propname &optional mailbox buffer)
1084 (let ((mailbox (imap-utf7-encode mailbox)))
1085 (with-current-buffer (or buffer (current-buffer))
1086 (imap-mailbox-get-1 propname (or mailbox imap-current-mailbox)))))
1088 (defun imap-mailbox-map-1 (func &optional mailbox-decoder buffer)
1089 (with-current-buffer (or buffer (current-buffer))
1093 (push (funcall func (if mailbox-decoder
1094 (funcall mailbox-decoder (symbol-name s))
1095 (symbol-name s))) result))
1099 (defun imap-mailbox-map (func &optional buffer)
1100 "Map a function across each mailbox in `imap-mailbox-data', returning a list.
1101 Function should take a mailbox name (a string) as
1103 (imap-mailbox-map-1 func 'imap-utf7-decode buffer))
1105 (defun imap-current-mailbox (&optional buffer)
1106 (with-current-buffer (or buffer (current-buffer))
1107 (imap-utf7-decode imap-current-mailbox)))
1109 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
1110 (and (string= mailbox imap-current-mailbox)
1112 (eq imap-state 'examine))
1114 (eq imap-state 'selected)))))
1116 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
1117 (with-current-buffer (or buffer (current-buffer))
1118 (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
1120 (defun imap-mailbox-select-1 (mailbox &optional examine)
1121 "Select MAILBOX on server in BUFFER.
1122 If EXAMINE is non-nil, do a read-only select."
1123 (if (imap-current-mailbox-p-1 mailbox examine)
1124 imap-current-mailbox
1125 (setq imap-current-mailbox mailbox)
1126 (if (imap-ok-p (imap-send-command-wait
1127 (concat (if examine "EXAMINE" "SELECT") " \""
1130 (setq imap-message-data (make-vector imap-message-prime 0)
1131 imap-state (if examine 'examine 'selected))
1132 imap-current-mailbox)
1133 ;; Failed SELECT/EXAMINE unselects current mailbox
1134 (setq imap-current-mailbox nil))))
1136 (defun imap-mailbox-select (mailbox &optional examine buffer)
1137 (with-current-buffer (or buffer (current-buffer))
1139 (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
1141 (defun imap-mailbox-examine-1 (mailbox &optional buffer)
1142 (with-current-buffer (or buffer (current-buffer))
1143 (imap-mailbox-select-1 mailbox 'examine)))
1145 (defun imap-mailbox-examine (mailbox &optional buffer)
1146 "Examine MAILBOX on server in BUFFER."
1147 (imap-mailbox-select mailbox 'examine buffer))
1149 (defun imap-mailbox-unselect (&optional buffer)
1150 "Close current folder in BUFFER, without expunging articles."
1151 (with-current-buffer (or buffer (current-buffer))
1152 (when (or (eq imap-state 'auth)
1153 (and (imap-capability 'UNSELECT)
1154 (imap-ok-p (imap-send-command-wait "UNSELECT")))
1156 (imap-send-command-wait (concat "EXAMINE \""
1157 imap-current-mailbox
1159 (imap-ok-p (imap-send-command-wait "CLOSE"))))
1160 (setq imap-current-mailbox nil
1161 imap-message-data nil
1165 (defun imap-mailbox-expunge (&optional asynch buffer)
1166 "Expunge articles in current folder in BUFFER.
1167 If ASYNCH, do not wait for succesful completion of the command.
1168 If BUFFER is nil the current buffer is assumed."
1169 (with-current-buffer (or buffer (current-buffer))
1170 (when (and imap-current-mailbox (not (eq imap-state 'examine)))
1172 (imap-send-command "EXPUNGE")
1173 (imap-ok-p (imap-send-command-wait "EXPUNGE"))))))
1175 (defun imap-mailbox-close (&optional asynch buffer)
1176 "Expunge articles and close current folder in BUFFER.
1177 If ASYNCH, do not wait for succesful completion of the command.
1178 If BUFFER is nil the current buffer is assumed."
1179 (with-current-buffer (or buffer (current-buffer))
1180 (when imap-current-mailbox
1182 (imap-add-callback (imap-send-command "CLOSE")
1183 `(lambda (tag status)
1184 (message "IMAP mailbox `%s' closed... %s"
1185 imap-current-mailbox status)
1186 (when (eq ,imap-current-mailbox
1187 imap-current-mailbox)
1188 ;; Don't wipe out data if another mailbox
1190 (setq imap-current-mailbox nil
1191 imap-message-data nil
1192 imap-state 'auth))))
1193 (when (imap-ok-p (imap-send-command-wait "CLOSE"))
1194 (setq imap-current-mailbox nil
1195 imap-message-data nil
1199 (defun imap-mailbox-create-1 (mailbox)
1200 (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
1202 (defun imap-mailbox-create (mailbox &optional buffer)
1203 "Create MAILBOX on server in BUFFER.
1204 If BUFFER is nil the current buffer is assumed."
1205 (with-current-buffer (or buffer (current-buffer))
1206 (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
1208 (defun imap-mailbox-delete (mailbox &optional buffer)
1209 "Delete MAILBOX on server in BUFFER.
1210 If BUFFER is nil the current buffer is assumed."
1211 (let ((mailbox (imap-utf7-encode mailbox)))
1212 (with-current-buffer (or buffer (current-buffer))
1214 (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1216 (defun imap-mailbox-rename (oldname newname &optional buffer)
1217 "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1218 If BUFFER is nil the current buffer is assumed."
1219 (let ((oldname (imap-utf7-encode oldname))
1220 (newname (imap-utf7-encode newname)))
1221 (with-current-buffer (or buffer (current-buffer))
1223 (imap-send-command-wait (list "RENAME \"" oldname "\" "
1224 "\"" newname "\""))))))
1226 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1227 "Return a list of subscribed mailboxes on server in BUFFER.
1228 If ROOT is non-nil, only list matching mailboxes. If ADD-DELIMITER is
1229 non-nil, a hierarchy delimiter is added to root. REFERENCE is a
1230 implementation-specific string that has to be passed to lsub command."
1231 (with-current-buffer (or buffer (current-buffer))
1232 ;; Make sure we know the hierarchy separator for root's hierarchy
1233 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1234 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1235 (imap-utf7-encode root) "\"")))
1236 ;; clear list data (NB not delimiter and other stuff)
1237 (imap-mailbox-map-1 (lambda (mailbox)
1238 (imap-mailbox-put 'lsub nil mailbox)))
1240 (imap-send-command-wait
1241 (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1242 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1245 (imap-mailbox-map-1 (lambda (mailbox)
1246 (when (imap-mailbox-get-1 'lsub mailbox)
1247 (push (imap-utf7-decode mailbox) out))))
1250 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1251 "Return a list of mailboxes matching ROOT on server in BUFFER.
1252 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1253 root. REFERENCE is a implementation-specific string that has to be
1254 passed to list command."
1255 (with-current-buffer (or buffer (current-buffer))
1256 ;; Make sure we know the hierarchy separator for root's hierarchy
1257 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1258 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1259 (imap-utf7-encode root) "\"")))
1260 ;; clear list data (NB not delimiter and other stuff)
1261 (imap-mailbox-map-1 (lambda (mailbox)
1262 (imap-mailbox-put 'list nil mailbox)))
1264 (imap-send-command-wait
1265 (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1266 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1269 (imap-mailbox-map-1 (lambda (mailbox)
1270 (when (imap-mailbox-get-1 'list mailbox)
1271 (push (imap-utf7-decode mailbox) out))))
1274 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1275 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1276 Returns non-nil if successful."
1277 (with-current-buffer (or buffer (current-buffer))
1278 (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1279 (imap-utf7-encode mailbox)
1282 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1283 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1284 Returns non-nil if successful."
1285 (with-current-buffer (or buffer (current-buffer))
1286 (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1287 (imap-utf7-encode mailbox)
1290 (defun imap-mailbox-status (mailbox items &optional buffer)
1291 "Get status items ITEM in MAILBOX from server in BUFFER.
1292 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1293 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1294 or 'unseen. If ITEMS is a list of symbols, a list of values is
1295 returned, if ITEMS is a symbol only it's value is returned."
1296 (with-current-buffer (or buffer (current-buffer))
1298 (imap-send-command-wait (list "STATUS \""
1299 (imap-utf7-encode mailbox)
1306 (mapcar (lambda (item)
1307 (imap-mailbox-get item mailbox))
1309 (imap-mailbox-get items mailbox)))))
1311 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1312 "Get ACL on mailbox from server in BUFFER."
1313 (let ((mailbox (imap-utf7-encode mailbox)))
1314 (with-current-buffer (or buffer (current-buffer))
1316 (imap-send-command-wait (list "GETACL \""
1317 (or mailbox imap-current-mailbox)
1319 (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1321 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1322 "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
1323 (let ((mailbox (imap-utf7-encode mailbox)))
1324 (with-current-buffer (or buffer (current-buffer))
1326 (imap-send-command-wait (list "SETACL \""
1327 (or mailbox imap-current-mailbox)
1333 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1334 "Removes any <identifier,rights> pair for IDENTIFIER in MAILBOX from server in BUFFER."
1335 (let ((mailbox (imap-utf7-encode mailbox)))
1336 (with-current-buffer (or buffer (current-buffer))
1338 (imap-send-command-wait (list "DELETEACL \""
1339 (or mailbox imap-current-mailbox)
1344 ;; Message functions:
1346 (defun imap-current-message (&optional buffer)
1347 (with-current-buffer (or buffer (current-buffer))
1348 imap-current-message))
1350 (defun imap-list-to-message-set (list)
1351 (mapconcat (lambda (item)
1352 (number-to-string item))
1358 (defun imap-range-to-message-set (range)
1363 (car item) (cdr item))
1364 (format "%d" item)))
1365 (if (and (listp range) (not (listp (cdr range))))
1366 (list range) ;; make (1 . 2) into ((1 . 2))
1370 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1371 (with-current-buffer (or buffer (current-buffer))
1372 (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1374 (imap-list-to-message-set uids)
1378 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1379 "Fetch properties PROPS from message set UIDS from server in BUFFER.
1380 UIDS can be a string, number or a list of numbers. If RECEIVE
1381 is non-nil return theese properties."
1382 (with-current-buffer (or buffer (current-buffer))
1383 (when (imap-ok-p (imap-send-command-wait
1384 (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1386 (imap-list-to-message-set uids)
1389 (if (or (null receive) (stringp uids))
1392 (mapcar (lambda (uid)
1394 (mapcar (lambda (prop)
1395 (imap-message-get uid prop))
1397 (imap-message-get uid receive)))
1399 (imap-message-get uids receive))))))
1401 (defun imap-message-put (uid propname value &optional buffer)
1402 (with-current-buffer (or buffer (current-buffer))
1403 (if imap-message-data
1404 (put (intern (number-to-string uid) imap-message-data)
1406 (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1407 uid propname value (current-buffer)))
1410 (defun imap-message-get (uid propname &optional buffer)
1411 (with-current-buffer (or buffer (current-buffer))
1412 (get (intern-soft (number-to-string uid) imap-message-data)
1415 (defun imap-message-map (func propname &optional buffer)
1416 "Map a function across each mailbox in `imap-message-data', returning a list."
1417 (with-current-buffer (or buffer (current-buffer))
1421 (push (funcall func (get s 'UID) (get s propname)) result))
1425 (defmacro imap-message-envelope-date (uid &optional buffer)
1426 `(with-current-buffer (or ,buffer (current-buffer))
1427 (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1429 (defmacro imap-message-envelope-subject (uid &optional buffer)
1430 `(with-current-buffer (or ,buffer (current-buffer))
1431 (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1433 (defmacro imap-message-envelope-from (uid &optional buffer)
1434 `(with-current-buffer (or ,buffer (current-buffer))
1435 (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1437 (defmacro imap-message-envelope-sender (uid &optional buffer)
1438 `(with-current-buffer (or ,buffer (current-buffer))
1439 (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1441 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1442 `(with-current-buffer (or ,buffer (current-buffer))
1443 (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1445 (defmacro imap-message-envelope-to (uid &optional buffer)
1446 `(with-current-buffer (or ,buffer (current-buffer))
1447 (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1449 (defmacro imap-message-envelope-cc (uid &optional buffer)
1450 `(with-current-buffer (or ,buffer (current-buffer))
1451 (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1453 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1454 `(with-current-buffer (or ,buffer (current-buffer))
1455 (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1457 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1458 `(with-current-buffer (or ,buffer (current-buffer))
1459 (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1461 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1462 `(with-current-buffer (or ,buffer (current-buffer))
1463 (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1465 (defmacro imap-message-body (uid &optional buffer)
1466 `(with-current-buffer (or ,buffer (current-buffer))
1467 (imap-message-get ,uid 'BODY)))
1469 (defun imap-search (predicate &optional buffer)
1470 (with-current-buffer (or buffer (current-buffer))
1471 (imap-mailbox-put 'search 'dummy)
1472 (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1473 (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1475 (message "Missing SEARCH response to a SEARCH command (server not RFC compliant)...")
1477 (imap-mailbox-get-1 'search imap-current-mailbox)))))
1479 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1480 "Return t iff FLAG can be permanently (between IMAP sessions) saved on articles, in MAILBOX on server in BUFFER."
1481 (with-current-buffer (or buffer (current-buffer))
1482 (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1483 (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1485 (defun imap-message-flags-set (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-del (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-flags-add (articles flags &optional silent buffer)
1500 (when (and articles flags)
1501 (with-current-buffer (or buffer (current-buffer))
1502 (imap-ok-p (imap-send-command-wait
1503 (concat "UID STORE " articles
1504 " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1506 (defun imap-message-copyuid-1 (mailbox)
1507 (if (imap-capability 'UIDPLUS)
1508 (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1509 (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1510 (let ((old-mailbox imap-current-mailbox)
1512 (imap-message-data (make-vector 2 0)))
1513 (when (imap-mailbox-examine-1 mailbox)
1515 (and (imap-fetch "*" "UID")
1516 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1517 (apply 'max (imap-message-map
1518 (lambda (uid prop) uid) 'UID))))
1520 (imap-mailbox-select old-mailbox (eq state 'examine))
1521 (imap-mailbox-unselect)))))))
1523 (defun imap-message-copyuid (mailbox &optional buffer)
1524 (with-current-buffer (or buffer (current-buffer))
1525 (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1527 (defun imap-message-copy (articles mailbox
1528 &optional dont-create no-copyuid buffer)
1529 "Copy ARTICLES (a string message set) to MAILBOX on server in
1530 BUFFER, creating mailbox if it doesn't exist. If dont-create is
1531 non-nil, it will not create a mailbox. On success, return a list with
1532 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1533 first element, rest of list contain the saved articles' UIDs."
1535 (with-current-buffer (or buffer (current-buffer))
1536 (let ((mailbox (imap-utf7-encode mailbox)))
1537 (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1538 (imap-current-target-mailbox mailbox))
1539 (if (imap-ok-p (imap-send-command-wait cmd))
1541 (when (and (not dont-create)
1542 ;; removed because of buggy Oracle server
1543 ;; that doesn't send TRYCREATE tags (which
1544 ;; is a MUST according to specifications):
1545 ;;(imap-mailbox-get-1 'trycreate mailbox)
1546 (imap-mailbox-create-1 mailbox))
1547 (imap-ok-p (imap-send-command-wait cmd)))))
1549 (imap-message-copyuid-1 mailbox)))))))
1551 (defun imap-message-appenduid-1 (mailbox)
1552 (if (imap-capability 'UIDPLUS)
1553 (imap-mailbox-get-1 'appenduid mailbox)
1554 (let ((old-mailbox imap-current-mailbox)
1556 (imap-message-data (make-vector 2 0)))
1557 (when (imap-mailbox-examine-1 mailbox)
1559 (and (imap-fetch "*" "UID")
1560 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1561 (apply 'max (imap-message-map
1562 (lambda (uid prop) uid) 'UID))))
1564 (imap-mailbox-select old-mailbox (eq state 'examine))
1565 (imap-mailbox-unselect)))))))
1567 (defun imap-message-appenduid (mailbox &optional buffer)
1568 (with-current-buffer (or buffer (current-buffer))
1569 (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1571 (defun imap-message-append (mailbox article &optional flags date-time buffer)
1572 "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1573 FLAGS and DATE-TIME is currently not used. Return a cons holding
1574 uidvalidity of MAILBOX and UID the newly created article got, or nil
1576 (let ((mailbox (imap-utf7-encode mailbox)))
1577 (with-current-buffer (or buffer (current-buffer))
1578 (and (let ((imap-current-target-mailbox mailbox))
1580 (imap-send-command-wait
1581 (list "APPEND \"" mailbox "\" " article))))
1582 (imap-message-appenduid-1 mailbox)))))
1584 (defun imap-body-lines (body)
1585 "Return number of lines in article by looking at the mime bodystructure BODY."
1587 (if (stringp (car body))
1588 (cond ((and (string= (upcase (car body)) "TEXT")
1589 (numberp (nth 7 body)))
1591 ((and (string= (upcase (car body)) "MESSAGE")
1592 (numberp (nth 9 body)))
1595 (apply '+ (mapcar 'imap-body-lines body)))
1598 (defun imap-envelope-from (from)
1599 "Return a from string line."
1601 (concat (aref from 0)
1602 (if (aref from 0) " <")
1606 (if (aref from 0) ">"))))
1609 ;; Internal functions.
1611 (defun imap-add-callback (tag func)
1612 (setq imap-callbacks (append (list (cons tag func)) imap-callbacks)))
1614 (defun imap-send-command-1 (cmdstr)
1615 (setq cmdstr (concat cmdstr imap-client-eol))
1617 (with-current-buffer (get-buffer-create imap-log-buffer)
1618 (imap-disable-multibyte)
1619 (buffer-disable-undo)
1620 (goto-char (point-max))
1622 (process-send-string imap-process cmdstr))
1624 (defun imap-send-command (command &optional buffer)
1625 (with-current-buffer (or buffer (current-buffer))
1626 (if (not (listp command)) (setq command (list command)))
1627 (let ((tag (setq imap-tag (1+ imap-tag)))
1629 (setq cmdstr (concat (number-to-string imap-tag) " "))
1630 (while (setq cmd (pop command))
1631 (cond ((stringp cmd)
1632 (setq cmdstr (concat cmdstr cmd)))
1634 (let ((eol imap-client-eol)
1635 (calcfirst imap-calculate-literal-size-first)
1637 (with-current-buffer cmd
1639 (setq size (buffer-size)))
1640 (when (not (equal eol "\r\n"))
1641 ;; XXX modifies buffer!
1642 (goto-char (point-min))
1643 (while (search-forward "\r\n" nil t)
1644 (replace-match eol)))
1646 (setq size (buffer-size))))
1648 (concat cmdstr (format "{%d}" size))))
1651 (imap-send-command-1 cmdstr)
1653 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1654 (setq command nil) ;; abort command if no cont-req
1655 (let ((process imap-process)
1656 (stream imap-stream)
1657 (eol imap-client-eol))
1658 (with-current-buffer cmd
1660 (with-current-buffer (get-buffer-create
1662 (imap-disable-multibyte)
1663 (buffer-disable-undo)
1664 (goto-char (point-max))
1665 (insert-buffer-substring cmd)))
1666 (process-send-region process (point-min)
1668 (process-send-string process imap-client-eol))))
1669 (setq imap-continuation nil)))
1671 (imap-send-command-1 cmdstr)
1674 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1675 (setq command nil) ;; abort command if no cont-req
1676 (setq command (cons (funcall cmd imap-continuation)
1678 (setq imap-continuation nil)))
1680 (error "Unknown command type"))))
1682 (imap-send-command-1 cmdstr))
1685 (defun imap-wait-for-tag (tag &optional buffer)
1686 (with-current-buffer (or buffer (current-buffer))
1687 (let (imap-have-messaged)
1688 (while (and (null imap-continuation)
1689 (memq (process-status imap-process) '(open run))
1690 (< imap-reached-tag tag))
1691 (let ((len (/ (point-max) 1024))
1694 (setq imap-have-messaged t)
1695 (message "imap read: %dk" len))
1696 (accept-process-output imap-process 1)))
1697 (when imap-have-messaged
1699 (and (memq (process-status imap-process) '(open run))
1700 (or (assq tag imap-failed-tags)
1701 (if imap-continuation
1705 (defun imap-sentinel (process string)
1706 (delete-process process))
1708 (defun imap-find-next-line ()
1709 "Return point at end of current line, taking into account literals.
1710 Return nil if no complete line has arrived."
1711 (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
1714 (if (match-string 1)
1715 (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1717 (goto-char (+ (point) (string-to-number (match-string 1))))
1718 (imap-find-next-line))
1721 (defun imap-arrival-filter (proc string)
1722 "IMAP process filter."
1723 (with-current-buffer (process-buffer proc)
1724 (goto-char (point-max))
1727 (with-current-buffer (get-buffer-create imap-log-buffer)
1728 (imap-disable-multibyte)
1729 (buffer-disable-undo)
1730 (goto-char (point-max))
1733 (goto-char (point-min))
1734 (while (setq end (imap-find-next-line))
1736 (narrow-to-region (point-min) end)
1737 (delete-backward-char (length imap-server-eol))
1738 (goto-char (point-min))
1740 (cond ((eq imap-state 'initial)
1741 (imap-parse-greeting))
1742 ((or (eq imap-state 'auth)
1743 (eq imap-state 'nonauth)
1744 (eq imap-state 'selected)
1745 (eq imap-state 'examine))
1746 (imap-parse-response))
1748 (message "Unknown state %s in arrival filter"
1750 (delete-region (point-min) (point-max))))))))
1755 (defsubst imap-forward ()
1756 (or (eobp) (forward-char)))
1759 ;; ; Unsigned 32-bit integer
1760 ;; ; (0 <= n < 4,294,967,296)
1762 (defsubst imap-parse-number ()
1763 (when (looking-at "[0-9]+")
1765 (string-to-number (match-string 0))
1766 (goto-char (match-end 0)))))
1768 ;; literal = "{" number "}" CRLF *CHAR8
1769 ;; ; Number represents the number of CHAR8s
1771 (defsubst imap-parse-literal ()
1772 (when (looking-at "{\\([0-9]+\\)}\r\n")
1773 (let ((pos (match-end 0))
1774 (len (string-to-number (match-string 1))))
1775 (if (< (point-max) (+ pos len))
1777 (goto-char (+ pos len))
1778 (buffer-substring pos (+ pos len))))))
1780 ;; string = quoted / literal
1782 ;; quoted = DQUOTE *QUOTED-CHAR DQUOTE
1784 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
1785 ;; "\" quoted-specials
1787 ;; quoted-specials = DQUOTE / "\"
1789 ;; TEXT-CHAR = <any CHAR except CR and LF>
1791 (defsubst imap-parse-string ()
1792 (cond ((eq (char-after) ?\")
1794 (let ((p (point)) (name ""))
1795 (skip-chars-forward "^\"\\\\")
1796 (setq name (buffer-substring p (point)))
1797 (while (eq (char-after) ?\\)
1798 (setq p (1+ (point)))
1800 (skip-chars-forward "^\"\\\\")
1801 (setq name (concat name (buffer-substring p (point)))))
1804 ((eq (char-after) ?{)
1805 (imap-parse-literal))))
1809 (defsubst imap-parse-nil ()
1810 (if (looking-at "NIL")
1811 (goto-char (match-end 0))))
1813 ;; nstring = string / nil
1815 (defsubst imap-parse-nstring ()
1816 (or (imap-parse-string)
1817 (and (imap-parse-nil)
1820 ;; astring = atom / string
1822 ;; atom = 1*ATOM-CHAR
1824 ;; ATOM-CHAR = <any CHAR except atom-specials>
1826 ;; atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards /
1829 ;; list-wildcards = "%" / "*"
1831 ;; quoted-specials = DQUOTE / "\"
1833 (defsubst imap-parse-astring ()
1834 (or (imap-parse-string)
1835 (buffer-substring (point)
1836 (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
1837 (goto-char (1- (match-end 0)))
1841 ;; address = "(" addr-name SP addr-adl SP addr-mailbox SP
1844 ;; addr-adl = nstring
1845 ;; ; Holds route from [RFC-822] route-addr if
1848 ;; addr-host = nstring
1849 ;; ; nil indicates [RFC-822] group syntax.
1850 ;; ; Otherwise, holds [RFC-822] domain name
1852 ;; addr-mailbox = nstring
1853 ;; ; nil indicates end of [RFC-822] group; if
1854 ;; ; non-nil and addr-host is nil, holds
1855 ;; ; [RFC-822] group name.
1856 ;; ; Otherwise, holds [RFC-822] local-part
1857 ;; ; after removing [RFC-822] quoting
1859 ;; addr-name = nstring
1860 ;; ; If non-nil, holds phrase from [RFC-822]
1861 ;; ; mailbox after removing [RFC-822] quoting
1864 (defsubst imap-parse-address ()
1866 (when (eq (char-after) ?\()
1868 (setq address (vector (prog1 (imap-parse-nstring)
1870 (prog1 (imap-parse-nstring)
1872 (prog1 (imap-parse-nstring)
1874 (imap-parse-nstring)))
1875 (when (eq (char-after) ?\))
1879 ;; address-list = "(" 1*address ")" / nil
1883 (defsubst imap-parse-address-list ()
1884 (if (eq (char-after) ?\()
1885 (let (address addresses)
1887 (while (and (not (eq (char-after) ?\)))
1888 ;; next line for MS Exchange bug
1889 (progn (and (eq (char-after) ? ) (imap-forward)) t)
1890 (setq address (imap-parse-address)))
1891 (setq addresses (cons address addresses)))
1892 (when (eq (char-after) ?\))
1894 (nreverse addresses)))
1895 (assert (imap-parse-nil) t "In imap-parse-address-list")))
1897 ;; mailbox = "INBOX" / astring
1898 ;; ; INBOX is case-insensitive. All case variants of
1899 ;; ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
1900 ;; ; not as an astring. An astring which consists of
1901 ;; ; the case-insensitive sequence "I" "N" "B" "O" "X"
1902 ;; ; is considered to be INBOX and not an astring.
1903 ;; ; Refer to section 5.1 for further
1904 ;; ; semantic details of mailbox names.
1906 (defsubst imap-parse-mailbox ()
1907 (let ((mailbox (imap-parse-astring)))
1908 (if (string-equal "INBOX" (upcase mailbox))
1912 ;; greeting = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
1914 ;; resp-cond-auth = ("OK" / "PREAUTH") SP resp-text
1915 ;; ; Authentication condition
1917 ;; resp-cond-bye = "BYE" SP resp-text
1919 (defun imap-parse-greeting ()
1920 "Parse a IMAP greeting."
1921 (cond ((looking-at "\\* OK ")
1922 (setq imap-state 'nonauth))
1923 ((looking-at "\\* PREAUTH ")
1924 (setq imap-state 'auth))
1925 ((looking-at "\\* BYE ")
1926 (setq imap-state 'closed))))
1928 ;; response = *(continue-req / response-data) response-done
1930 ;; continue-req = "+" SP (resp-text / base64) CRLF
1932 ;; response-data = "*" SP (resp-cond-state / resp-cond-bye /
1933 ;; mailbox-data / message-data / capability-data) CRLF
1935 ;; response-done = response-tagged / response-fatal
1937 ;; response-fatal = "*" SP resp-cond-bye CRLF
1938 ;; ; Server closes connection immediately
1940 ;; response-tagged = tag SP resp-cond-state CRLF
1942 ;; resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
1943 ;; ; Status condition
1945 ;; resp-cond-bye = "BYE" SP resp-text
1947 ;; mailbox-data = "FLAGS" SP flag-list /
1948 ;; "LIST" SP mailbox-list /
1949 ;; "LSUB" SP mailbox-list /
1950 ;; "SEARCH" *(SP nz-number) /
1951 ;; "STATUS" SP mailbox SP "("
1952 ;; [status-att SP number *(SP status-att SP number)] ")" /
1953 ;; number SP "EXISTS" /
1954 ;; number SP "RECENT"
1956 ;; message-data = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
1958 ;; capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
1960 ;; ; IMAP4rev1 servers which offer RFC 1730
1961 ;; ; compatibility MUST list "IMAP4" as the first
1964 (defun imap-parse-response ()
1965 "Parse a IMAP command response."
1967 (case (setq token (read (current-buffer)))
1968 (+ (setq imap-continuation
1969 (or (buffer-substring (min (point-max) (1+ (point)))
1972 (* (case (prog1 (setq token (read (current-buffer)))
1974 (OK (imap-parse-resp-text))
1975 (NO (imap-parse-resp-text))
1976 (BAD (imap-parse-resp-text))
1977 (BYE (imap-parse-resp-text))
1978 (FLAGS (imap-mailbox-put 'flags (imap-parse-flag-list)))
1979 (LIST (imap-parse-data-list 'list))
1980 (LSUB (imap-parse-data-list 'lsub))
1981 (SEARCH (imap-mailbox-put
1983 (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
1984 (STATUS (imap-parse-status))
1985 (CAPABILITY (setq imap-capability
1986 (read (concat "(" (upcase (buffer-substring
1987 (point) (point-max)))
1989 (ACL (imap-parse-acl))
1990 (t (case (prog1 (read (current-buffer))
1992 (EXISTS (imap-mailbox-put 'exists token))
1993 (RECENT (imap-mailbox-put 'recent token))
1995 (FETCH (imap-parse-fetch token))
1996 (t (message "Garbage: %s" (buffer-string)))))))
1998 (if (not (integerp token))
1999 (message "Garbage: %s" (buffer-string))
2000 (case (prog1 (setq status (read (current-buffer)))
2003 (setq imap-reached-tag (max imap-reached-tag token))
2004 (imap-parse-resp-text)))
2006 (setq imap-reached-tag (max imap-reached-tag token))
2008 (imap-parse-resp-text))
2010 (when (eq (char-after) ?\[)
2011 (setq code (buffer-substring (point)
2012 (search-forward "]")))
2014 (setq text (buffer-substring (point) (point-max)))
2015 (push (list token status code text)
2016 imap-failed-tags))))
2018 (setq imap-reached-tag (max imap-reached-tag token))
2020 (imap-parse-resp-text))
2022 (when (eq (char-after) ?\[)
2023 (setq code (buffer-substring (point)
2024 (search-forward "]")))
2026 (setq text (buffer-substring (point) (point-max)))
2027 (push (list token status code text) imap-failed-tags)
2028 (error "Internal error, tag %s status %s code %s text %s"
2029 token status code text))))
2030 (t (message "Garbage: %s" (buffer-string))))
2031 (when (assq token imap-callbacks)
2032 (funcall (cdr (assq token imap-callbacks)) token status)
2033 (setq imap-callbacks
2034 (imap-remassoc token imap-callbacks)))))))))
2036 ;; resp-text = ["[" resp-text-code "]" SP] text
2038 ;; text = 1*TEXT-CHAR
2040 ;; TEXT-CHAR = <any CHAR except CR and LF>
2042 (defun imap-parse-resp-text ()
2043 (imap-parse-resp-text-code))
2045 ;; resp-text-code = "ALERT" /
2046 ;; "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
2047 ;; "NEWNAME" SP string SP string /
2049 ;; "PERMANENTFLAGS" SP "("
2050 ;; [flag-perm *(SP flag-perm)] ")" /
2054 ;; "UIDNEXT" SP nz-number /
2055 ;; "UIDVALIDITY" SP nz-number /
2056 ;; "UNSEEN" SP nz-number /
2057 ;; resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
2059 ;; resp_code_apnd = "APPENDUID" SPACE nz_number SPACE uniqueid
2061 ;; resp_code_copy = "COPYUID" SPACE nz_number SPACE set SPACE set
2063 ;; set = sequence-num / (sequence-num ":" sequence-num) /
2065 ;; ; Identifies a set of messages. For message
2066 ;; ; sequence numbers, these are consecutive
2067 ;; ; numbers from 1 to the number of messages in
2069 ;; ; Comma delimits individual numbers, colon
2070 ;; ; delimits between two numbers inclusive.
2071 ;; ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
2072 ;; ; 14,15 for a mailbox with 15 messages.
2074 ;; sequence-num = nz-number / "*"
2075 ;; ; * is the largest number in use. For message
2076 ;; ; sequence numbers, it is the number of messages
2077 ;; ; in the mailbox. For unique identifiers, it is
2078 ;; ; the unique identifier of the last message in
2081 ;; flag-perm = flag / "\*"
2083 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2084 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2085 ;; ; Does not include "\Recent"
2087 ;; flag-extension = "\" atom
2088 ;; ; Future expansion. Client implementations
2089 ;; ; MUST accept flag-extension flags. Server
2090 ;; ; implementations MUST NOT generate
2091 ;; ; flag-extension flags except as defined by
2092 ;; ; future standard or standards-track
2093 ;; ; revisions of this specification.
2095 ;; flag-keyword = atom
2097 ;; resp-text-atom = 1*<any ATOM-CHAR except "]">
2099 (defun imap-parse-resp-text-code ()
2100 ;; xxx next line for stalker communigate pro 3.3.1 bug
2101 (when (looking-at " \\[")
2103 (when (eq (char-after) ?\[)
2105 (cond ((search-forward "PERMANENTFLAGS " nil t)
2106 (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2107 ((search-forward "UIDNEXT " nil t)
2108 (imap-mailbox-put 'uidnext (read (current-buffer))))
2109 ((search-forward "UNSEEN " nil t)
2110 (imap-mailbox-put 'unseen (read (current-buffer))))
2111 ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2112 (imap-mailbox-put 'uidvalidity (match-string 1)))
2113 ((search-forward "READ-ONLY" nil t)
2114 (imap-mailbox-put 'read-only t))
2115 ((search-forward "NEWNAME " nil t)
2116 (let (oldname newname)
2117 (setq oldname (imap-parse-string))
2119 (setq newname (imap-parse-string))
2120 (imap-mailbox-put 'newname newname oldname)))
2121 ((search-forward "TRYCREATE" nil t)
2122 (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2123 ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2124 (imap-mailbox-put 'appenduid
2125 (list (match-string 1)
2126 (string-to-number (match-string 2)))
2127 imap-current-target-mailbox))
2128 ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2129 (imap-mailbox-put 'copyuid (list (match-string 1)
2132 imap-current-target-mailbox))
2133 ((search-forward "ALERT] " nil t)
2134 (message "Imap server %s information: %s" imap-server
2135 (buffer-substring (point) (point-max)))))))
2137 ;; mailbox-list = "(" [mbx-list-flags] ")" SP
2138 ;; (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2140 ;; mbx-list-flags = *(mbx-list-oflag SP) mbx-list-sflag
2141 ;; *(SP mbx-list-oflag) /
2142 ;; mbx-list-oflag *(SP mbx-list-oflag)
2144 ;; mbx-list-oflag = "\Noinferiors" / flag-extension
2145 ;; ; Other flags; multiple possible per LIST response
2147 ;; mbx-list-sflag = "\Noselect" / "\Marked" / "\Unmarked"
2148 ;; ; Selectability flags; only one per LIST response
2150 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2151 ;; "\" quoted-specials
2153 ;; quoted-specials = DQUOTE / "\"
2155 (defun imap-parse-data-list (type)
2156 (let (flags delimiter mailbox)
2157 (setq flags (imap-parse-flag-list))
2158 (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2159 (setq delimiter (match-string 1))
2160 (goto-char (1+ (match-end 0)))
2161 (when (setq mailbox (imap-parse-mailbox))
2162 (imap-mailbox-put type t mailbox)
2163 (imap-mailbox-put 'list-flags flags mailbox)
2164 (imap-mailbox-put 'delimiter delimiter mailbox)))))
2166 ;; msg_att ::= "(" 1#("ENVELOPE" SPACE envelope /
2167 ;; "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2168 ;; "INTERNALDATE" SPACE date_time /
2169 ;; "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2170 ;; "RFC822.SIZE" SPACE number /
2171 ;; "BODY" ["STRUCTURE"] SPACE body /
2172 ;; "BODY" section ["<" number ">"] SPACE nstring /
2173 ;; "UID" SPACE uniqueid) ")"
2175 ;; date_time ::= <"> date_day_fixed "-" date_month "-" date_year
2176 ;; SPACE time SPACE zone <">
2178 ;; section ::= "[" [section_text / (nz_number *["." nz_number]
2179 ;; ["." (section_text / "MIME")])] "]"
2181 ;; section_text ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2182 ;; SPACE header_list / "TEXT"
2184 ;; header_fld_name ::= astring
2186 ;; header_list ::= "(" 1#header_fld_name ")"
2188 (defsubst imap-parse-header-list ()
2189 (when (eq (char-after) ?\()
2191 (while (not (eq (char-after) ?\)))
2193 (push (imap-parse-astring) strlist))
2195 (nreverse strlist))))
2197 (defsubst imap-parse-fetch-body-section ()
2199 (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2200 (if (eq (char-before) ? )
2202 (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2203 (search-forward "]" nil t))
2206 (defun imap-parse-fetch (response)
2207 (when (eq (char-after) ?\()
2208 (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2209 rfc822size body bodydetail bodystructure flags-empty)
2210 (while (not (eq (char-after) ?\)))
2212 (let ((token (read (current-buffer))))
2214 (cond ((eq token 'UID)
2215 (setq uid (condition-case ()
2216 (read (current-buffer))
2219 (setq flags (imap-parse-flag-list))
2221 (setq flags-empty 't)))
2222 ((eq token 'ENVELOPE)
2223 (setq envelope (imap-parse-envelope)))
2224 ((eq token 'INTERNALDATE)
2225 (setq internaldate (imap-parse-string)))
2227 (setq rfc822 (imap-parse-nstring)))
2228 ((eq token 'RFC822.HEADER)
2229 (setq rfc822header (imap-parse-nstring)))
2230 ((eq token 'RFC822.TEXT)
2231 (setq rfc822text (imap-parse-nstring)))
2232 ((eq token 'RFC822.SIZE)
2233 (setq rfc822size (read (current-buffer))))
2235 (if (eq (char-before) ?\[)
2237 (upcase (imap-parse-fetch-body-section))
2238 (and (eq (char-after) ?<)
2239 (buffer-substring (1+ (point))
2240 (search-forward ">" nil t)))
2241 (progn (imap-forward)
2242 (imap-parse-nstring)))
2244 (setq body (imap-parse-body))))
2245 ((eq token 'BODYSTRUCTURE)
2246 (setq bodystructure (imap-parse-body))))))
2248 (setq imap-current-message uid)
2249 (imap-message-put uid 'UID uid)
2250 (and (or flags flags-empty) (imap-message-put uid 'FLAGS flags))
2251 (and envelope (imap-message-put uid 'ENVELOPE envelope))
2252 (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2253 (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2254 (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2255 (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2256 (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2257 (and body (imap-message-put uid 'BODY body))
2258 (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2259 (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2260 (run-hooks 'imap-fetch-data-hook)))))
2262 ;; mailbox-data = ...
2263 ;; "STATUS" SP mailbox SP "("
2264 ;; [status-att SP number
2265 ;; *(SP status-att SP number)] ")"
2268 ;; status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2271 (defun imap-parse-status ()
2272 (let ((mailbox (imap-parse-mailbox)))
2273 (when (and mailbox (search-forward "(" nil t))
2274 (while (not (eq (char-after) ?\)))
2275 (let ((token (read (current-buffer))))
2276 (cond ((eq token 'MESSAGES)
2277 (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2279 (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2280 ((eq token 'UIDNEXT)
2281 (imap-mailbox-put 'uidnext (read (current-buffer)) mailbox))
2282 ((eq token 'UIDVALIDITY)
2283 (and (looking-at " \\([0-9]+\\)")
2284 (imap-mailbox-put 'uidvalidity (match-string 1) mailbox)
2285 (goto-char (match-end 1))))
2287 (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2289 (message "Unknown status data %s in mailbox %s ignored"
2290 token mailbox))))))))
2292 ;; acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2295 ;; identifier ::= astring
2297 ;; rights ::= astring
2299 (defun imap-parse-acl ()
2300 (let ((mailbox (imap-parse-mailbox))
2301 identifier rights acl)
2302 (while (eq (char-after) ?\ )
2304 (setq identifier (imap-parse-astring))
2306 (setq rights (imap-parse-astring))
2307 (setq acl (append acl (list (cons identifier rights)))))
2308 (imap-mailbox-put 'acl acl mailbox)))
2310 ;; flag-list = "(" [flag *(SP flag)] ")"
2312 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2313 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2314 ;; ; Does not include "\Recent"
2316 ;; flag-keyword = atom
2318 ;; flag-extension = "\" atom
2319 ;; ; Future expansion. Client implementations
2320 ;; ; MUST accept flag-extension flags. Server
2321 ;; ; implementations MUST NOT generate
2322 ;; ; flag-extension flags except as defined by
2323 ;; ; future standard or standards-track
2324 ;; ; revisions of this specification.
2326 (defun imap-parse-flag-list ()
2327 (let (flag-list start)
2328 (assert (eq (char-after) ?\() t "In imap-parse-flag-list")
2329 (while (and (not (eq (char-after) ?\)))
2332 ;; next line for Courier IMAP bug.
2333 (skip-chars-forward " ")
2335 (> (skip-chars-forward "^ )" (imap-point-at-eol)) 0))
2336 (push (buffer-substring start (point)) flag-list))
2337 (assert (eq (char-after) ?\)) t "In imap-parse-flag-list")
2339 (nreverse flag-list)))
2341 ;; envelope = "(" env-date SP env-subject SP env-from SP env-sender SP
2342 ;; env-reply-to SP env-to SP env-cc SP env-bcc SP
2343 ;; env-in-reply-to SP env-message-id ")"
2345 ;; env-bcc = "(" 1*address ")" / nil
2347 ;; env-cc = "(" 1*address ")" / nil
2349 ;; env-date = nstring
2351 ;; env-from = "(" 1*address ")" / nil
2353 ;; env-in-reply-to = nstring
2355 ;; env-message-id = nstring
2357 ;; env-reply-to = "(" 1*address ")" / nil
2359 ;; env-sender = "(" 1*address ")" / nil
2361 ;; env-subject = nstring
2363 ;; env-to = "(" 1*address ")" / nil
2365 (defun imap-parse-envelope ()
2366 (when (eq (char-after) ?\()
2368 (vector (prog1 (imap-parse-nstring) ;; date
2370 (prog1 (imap-parse-nstring) ;; subject
2372 (prog1 (imap-parse-address-list) ;; from
2374 (prog1 (imap-parse-address-list) ;; sender
2376 (prog1 (imap-parse-address-list) ;; reply-to
2378 (prog1 (imap-parse-address-list) ;; to
2380 (prog1 (imap-parse-address-list) ;; cc
2382 (prog1 (imap-parse-address-list) ;; bcc
2384 (prog1 (imap-parse-nstring) ;; in-reply-to
2386 (prog1 (imap-parse-nstring) ;; message-id
2389 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2391 (defsubst imap-parse-string-list ()
2392 (cond ((eq (char-after) ?\() ;; body-fld-param
2395 (while (setq str (imap-parse-string))
2397 ;; buggy stalker communigate pro 3.0 doesn't print SPC
2398 ;; between body-fld-param's sometimes
2399 (or (eq (char-after) ?\")
2401 (nreverse strlist)))
2405 ;; body-extension = nstring / number /
2406 ;; "(" body-extension *(SP body-extension) ")"
2407 ;; ; Future expansion. Client implementations
2408 ;; ; MUST accept body-extension fields. Server
2409 ;; ; implementations MUST NOT generate
2410 ;; ; body-extension fields except as defined by
2411 ;; ; future standard or standards-track
2412 ;; ; revisions of this specification.
2414 (defun imap-parse-body-extension ()
2415 (if (eq (char-after) ?\()
2418 (push (imap-parse-body-extension) b-e)
2419 (while (eq (char-after) ?\ )
2421 (push (imap-parse-body-extension) b-e))
2422 (assert (eq (char-after) ?\)) t "In imap-parse-body-extension")
2425 (or (imap-parse-number)
2426 (imap-parse-nstring))))
2428 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2429 ;; *(SP body-extension)]]
2430 ;; ; MUST NOT be returned on non-extensible
2433 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2434 ;; *(SP body-extension)]]
2435 ;; ; MUST NOT be returned on non-extensible
2438 (defsubst imap-parse-body-ext ()
2440 (when (eq (char-after) ?\ ) ;; body-fld-dsp
2443 (if (eq (char-after) ?\()
2446 (push (imap-parse-string) dsp)
2448 (push (imap-parse-string-list) dsp)
2450 (assert (imap-parse-nil) t "In imap-parse-body-ext"))
2451 (push (nreverse dsp) ext))
2452 (when (eq (char-after) ?\ ) ;; body-fld-lang
2454 (if (eq (char-after) ?\()
2455 (push (imap-parse-string-list) ext)
2456 (push (imap-parse-nstring) ext))
2457 (while (eq (char-after) ?\ ) ;; body-extension
2459 (setq ext (append (imap-parse-body-extension) ext)))))
2462 ;; body = "(" body-type-1part / body-type-mpart ")"
2464 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2465 ;; *(SP body-extension)]]
2466 ;; ; MUST NOT be returned on non-extensible
2469 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2470 ;; *(SP body-extension)]]
2471 ;; ; MUST NOT be returned on non-extensible
2474 ;; body-fields = body-fld-param SP body-fld-id SP body-fld-desc SP
2475 ;; body-fld-enc SP body-fld-octets
2477 ;; body-fld-desc = nstring
2479 ;; body-fld-dsp = "(" string SP body-fld-param ")" / nil
2481 ;; body-fld-enc = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2482 ;; "QUOTED-PRINTABLE") DQUOTE) / string
2484 ;; body-fld-id = nstring
2486 ;; body-fld-lang = nstring / "(" string *(SP string) ")"
2488 ;; body-fld-lines = number
2490 ;; body-fld-md5 = nstring
2492 ;; body-fld-octets = number
2494 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2496 ;; body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2497 ;; [SP body-ext-1part]
2499 ;; body-type-basic = media-basic SP body-fields
2500 ;; ; MESSAGE subtype MUST NOT be "RFC822"
2502 ;; body-type-msg = media-message SP body-fields SP envelope
2503 ;; SP body SP body-fld-lines
2505 ;; body-type-text = media-text SP body-fields SP body-fld-lines
2507 ;; body-type-mpart = 1*body SP media-subtype
2508 ;; [SP body-ext-mpart]
2510 ;; media-basic = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2511 ;; "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2512 ;; ; Defined in [MIME-IMT]
2514 ;; media-message = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2515 ;; ; Defined in [MIME-IMT]
2517 ;; media-subtype = string
2518 ;; ; Defined in [MIME-IMT]
2520 ;; media-text = DQUOTE "TEXT" DQUOTE SP media-subtype
2521 ;; ; Defined in [MIME-IMT]
2523 (defun imap-parse-body ()
2525 (when (eq (char-after) ?\()
2527 (if (eq (char-after) ?\()
2529 (while (and (eq (char-after) ?\()
2530 (setq subbody (imap-parse-body)))
2531 ;; buggy stalker communigate pro 3.0 insert a SPC between
2532 ;; parts in multiparts
2533 (when (and (eq (char-after) ?\ )
2534 (eq (char-after (1+ (point))) ?\())
2536 (push subbody body))
2538 (push (imap-parse-string) body) ;; media-subtype
2539 (when (eq (char-after) ?\ ) ;; body-ext-mpart:
2541 (if (eq (char-after) ?\() ;; body-fld-param
2542 (push (imap-parse-string-list) body)
2543 (push (and (imap-parse-nil) nil) body))
2545 (append (imap-parse-body-ext) body))) ;; body-ext-...
2546 (assert (eq (char-after) ?\)) t "In imap-parse-body")
2550 (push (imap-parse-string) body) ;; media-type
2552 (push (imap-parse-string) body) ;; media-subtype
2554 ;; next line for Sun SIMS bug
2555 (and (eq (char-after) ? ) (imap-forward))
2556 (if (eq (char-after) ?\() ;; body-fld-param
2557 (push (imap-parse-string-list) body)
2558 (push (and (imap-parse-nil) nil) body))
2560 (push (imap-parse-nstring) body) ;; body-fld-id
2562 (push (imap-parse-nstring) body) ;; body-fld-desc
2564 ;; next `or' for Sun SIMS bug, it regard body-fld-enc as a
2565 ;; nstring and return nil instead of defaulting back to 7BIT
2566 ;; as the standard says.
2567 (push (or (imap-parse-nstring) "7BIT") body) ;; body-fld-enc
2569 (push (imap-parse-number) body) ;; body-fld-octets
2571 ;; ok, we're done parsing the required parts, what comes now is one
2574 ;; envelope (then we're parsing body-type-msg)
2575 ;; body-fld-lines (then we're parsing body-type-text)
2576 ;; body-ext-1part (then we're parsing body-type-basic)
2578 ;; the problem is that the two first are in turn optionally followed
2579 ;; by the third. So we parse the first two here (if there are any)...
2581 (when (eq (char-after) ?\ )
2584 (cond ((eq (char-after) ?\() ;; body-type-msg:
2585 (push (imap-parse-envelope) body) ;; envelope
2587 (push (imap-parse-body) body) ;; body
2588 ;; buggy stalker communigate pro 3.0 doesn't print
2589 ;; number of lines in message/rfc822 attachment
2590 (if (eq (char-after) ?\))
2593 (push (imap-parse-number) body))) ;; body-fld-lines
2594 ((setq lines (imap-parse-number)) ;; body-type-text:
2595 (push lines body)) ;; body-fld-lines
2597 (backward-char))))) ;; no match...
2599 ;; ...and then parse the third one here...
2601 (when (eq (char-after) ?\ ) ;; body-ext-1part:
2603 (push (imap-parse-nstring) body) ;; body-fld-md5
2604 (setq body (append (imap-parse-body-ext) body))) ;; body-ext-1part..
2606 (assert (eq (char-after) ?\)) t "In imap-parse-body 2")
2610 (when imap-debug ; (untrace-all)
2612 (buffer-disable-undo (get-buffer-create imap-debug-buffer))
2613 (mapcar (lambda (f) (trace-function-background f imap-debug-buffer))
2625 imap-interactive-login
2641 imap-send-command-wait
2646 imap-current-mailbox
2647 imap-current-mailbox-p-1
2648 imap-current-mailbox-p
2649 imap-mailbox-select-1
2651 imap-mailbox-examine-1
2652 imap-mailbox-examine
2653 imap-mailbox-unselect
2654 imap-mailbox-expunge
2656 imap-mailbox-create-1
2662 imap-mailbox-subscribe
2663 imap-mailbox-unsubscribe
2665 imap-mailbox-acl-get
2666 imap-mailbox-acl-set
2667 imap-mailbox-acl-delete
2668 imap-current-message
2669 imap-list-to-message-set
2676 imap-message-flag-permanent-p
2677 imap-message-flags-set
2678 imap-message-flags-del
2679 imap-message-flags-add
2680 imap-message-copyuid-1
2681 imap-message-copyuid
2683 imap-message-appenduid-1
2684 imap-message-appenduid
2696 imap-parse-resp-text
2697 imap-parse-resp-text-code
2698 imap-parse-data-list
2702 imap-parse-flag-list
2704 imap-parse-body-extension
2710 ;;; imap.el ends here