1 ;;; imap.el --- imap library
2 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003
3 ;; Free Software Foundation, Inc.
5 ;; Author: Simon Josefsson <jas@pdc.kth.se>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
27 ;; imap.el is a elisp library providing an interface for talking to
30 ;; imap.el is roughly divided in two parts, one that parses IMAP
31 ;; responses from the server and storing data into buffer-local
32 ;; variables, and one for utility functions which send commands to
33 ;; server, waits for an answer, and return information. The latter
34 ;; part is layered on top of the previous.
36 ;; The imap.el API consist of the following functions, other functions
37 ;; in this file should not be called directly and the result of doing
38 ;; so are at best undefined.
42 ;; imap-open, imap-opened, imap-authenticate, imap-close,
43 ;; imap-capability, imap-namespace, imap-error-text
47 ;; imap-mailbox-get, imap-mailbox-map, imap-current-mailbox,
48 ;; imap-current-mailbox-p, imap-search, imap-mailbox-select,
49 ;; imap-mailbox-examine, imap-mailbox-unselect, imap-mailbox-expunge
50 ;; imap-mailbox-close, imap-mailbox-create, imap-mailbox-delete
51 ;; imap-mailbox-rename, imap-mailbox-lsub, imap-mailbox-list
52 ;; imap-mailbox-subscribe, imap-mailbox-unsubscribe, imap-mailbox-status
53 ;; imap-mailbox-acl-get, imap-mailbox-acl-set, imap-mailbox-acl-delete
57 ;; imap-fetch-asynch, imap-fetch,
58 ;; imap-current-message, imap-list-to-message-set,
59 ;; imap-message-get, imap-message-map
60 ;; imap-message-envelope-date, imap-message-envelope-subject,
61 ;; imap-message-envelope-from, imap-message-envelope-sender,
62 ;; imap-message-envelope-reply-to, imap-message-envelope-to,
63 ;; imap-message-envelope-cc, imap-message-envelope-bcc
64 ;; imap-message-envelope-in-reply-to, imap-message-envelope-message-id
65 ;; imap-message-body, imap-message-flag-permanent-p
66 ;; imap-message-flags-set, imap-message-flags-del
67 ;; imap-message-flags-add, imap-message-copyuid
68 ;; imap-message-copy, imap-message-appenduid
69 ;; imap-message-append, imap-envelope-from
72 ;; It is my hope that theese commands should be pretty self
73 ;; explanatory for someone that know IMAP. All functions have
74 ;; additional documentation on how to invoke them.
76 ;; imap.el support RFC1730/2060 (IMAP4/IMAP4rev1), implemented IMAP
77 ;; extensions are RFC2195 (CRAM-MD5), RFC2086 (ACL), RFC2342
78 ;; (NAMESPACE), RFC2359 (UIDPLUS), the IMAP-part of RFC2595 (STARTTLS,
79 ;; LOGINDISABLED) (with use of external library starttls.el and
80 ;; program starttls) and the GSSAPI / kerberos V4 sections of RFC1731
81 ;; (with use of external program `imtest'). It also take advantage
82 ;; the UNSELECT extension in Cyrus IMAPD.
84 ;; Without the work of John McClary Prevost and Jim Radford this library
85 ;; would not have seen the light of day. Many thanks.
87 ;; This is a transcript of short interactive session for demonstration
90 ;; (imap-open "my.mail.server")
91 ;; => " *imap* my.mail.server:0"
93 ;; The rest are invoked with current buffer as the buffer returned by
94 ;; `imap-open'. It is possible to do all without this, but it would
95 ;; look ugly here since `buffer' is always the last argument for all
96 ;; imap.el API functions.
98 ;; (imap-authenticate "myusername" "mypassword")
101 ;; (imap-mailbox-lsub "*")
102 ;; => ("INBOX.sentmail" "INBOX.private" "INBOX.draft" "INBOX.spam")
104 ;; (imap-mailbox-list "INBOX.n%")
105 ;; => ("INBOX.namedroppers" "INBOX.nnimap" "INBOX.ntbugtraq")
107 ;; (imap-mailbox-select "INBOX.nnimap")
110 ;; (imap-mailbox-get 'exists)
113 ;; (imap-mailbox-get 'uidvalidity)
116 ;; (imap-search "FLAGGED SINCE 18-DEC-98")
119 ;; (imap-fetch 235 "RFC822.PEEK" 'RFC822)
120 ;; => "X-Sieve: cmu-sieve 1.3^M\nX-Username: <jas@pdc.kth.se>^M\r...."
124 ;; o Parse UIDs as strings? We need to overcome the 28 bit limit somehow.
125 ;; o Don't use `read' at all (important places already fixed)
126 ;; o Accept list of articles instead of message set string in most
127 ;; imap-message-* functions.
131 ;; - 19991218 added starttls/digest-md5 patch,
132 ;; by Daiki Ueno <ueno@ueda.info.waseda.ac.jp>
133 ;; NB! you need SLIM for starttls.el and digest-md5.el
134 ;; - 19991023 commited to pgnus
139 (eval-when-compile (require 'cl))
140 (eval-when-compile (require 'static))
145 (autoload 'starttls-open-stream "starttls")
146 (autoload 'starttls-negotiate "starttls")
147 (autoload 'rfc2104-hash "rfc2104")
148 (autoload 'md5 "md5")
149 (autoload 'utf7-encode "utf7")
150 (autoload 'utf7-decode "utf7")
151 (autoload 'format-spec "format-spec")
152 (autoload 'format-spec-make "format-spec")
153 ;; Avoid use gnus-point-at-eol so we're independent of Gnus. These
154 ;; days we have point-at-eol anyhow.
155 (if (fboundp 'point-at-eol)
156 (defalias 'imap-point-at-eol 'point-at-eol)
157 (defun imap-point-at-eol ()
161 (autoload 'sasl-digest-md5-digest-response "sasl"))
166 "Low-level IMAP issues."
170 (defcustom imap-kerberos4-program '("imtest -m kerberos_v4 -u %l -p %p %s"
172 "List of strings containing commands for Kerberos 4 authentication.
173 %s is replaced with server hostname, %p with port to connect to, and
174 %l with the value of `imap-default-user'. The program should accept
175 IMAP commands on stdin and return responses to stdout. Each entry in
176 the list is tried until a successful connection is made."
178 :type '(repeat string))
180 (defcustom imap-gssapi-program '("imtest -m gssapi -u %l -p %p %s")
181 "List of strings containing commands for GSSAPI (krb5) authentication.
182 %s is replaced with server hostname, %p with port to connect to, and
183 %l with the value of `imap-default-user'. The program should accept
184 IMAP commands on stdin and return responses to stdout. Each entry in
185 the list is tried until a successful connection is made."
187 :type '(repeat string))
189 (defcustom imap-ssl-program '("openssl s_client -quiet -ssl3 -connect %s:%p"
190 "openssl s_client -quiet -ssl2 -connect %s:%p"
191 "s_client -quiet -ssl3 -connect %s:%p"
192 "s_client -quiet -ssl2 -connect %s:%p")
193 "A string, or list of strings, containing commands for SSL connections.
194 Within a string, %s is replaced with the server address and %p with
195 port number on server. The program should accept IMAP commands on
196 stdin and return responses to stdout. Each entry in the list is tried
197 until a successful connection is made."
199 :type '(choice string
202 (defcustom imap-shell-program '("ssh %s imapd"
204 "ssh %g ssh %s imapd"
205 "rsh %g rsh %s imapd")
206 "A list of strings, containing commands for IMAP connection.
207 Within a string, %s is replaced with the server address, %p with port
208 number on server, %g with `imap-shell-host', and %l with
209 `imap-default-user'. The program should read IMAP commands from stdin
210 and write IMAP response to stdout. Each entry in the list is tried
211 until a successful connection is made."
213 :type '(repeat string))
215 (defcustom imap-process-connection-type nil
216 "*Value for `process-connection-type' to use for Kerberos4 and GSSAPI."
220 (defcustom imap-use-utf7 t
221 "If non-nil, do utf7 encoding/decoding of mailbox names.
222 Since the UTF7 decoding currently only decodes into ISO-8859-1
223 characters, you may disable this decoding if you need to access UTF7
224 encoded mailboxes which doesn't translate into ISO-8859-1."
228 (defcustom imap-log nil
229 "If non-nil, a imap session trace is placed in *imap-log* buffer."
233 (defcustom imap-debug nil
234 "If non-nil, random debug spews are placed in *imap-debug* buffer."
238 (defcustom imap-shell-host "gateway"
239 "Hostname of rlogin proxy."
243 (defcustom imap-default-user (user-login-name)
244 "Default username to use."
248 ;; Various variables.
250 (defvar imap-fetch-data-hook nil
251 "Hooks called after receiving each FETCH response.")
253 (defvar imap-streams '(gssapi kerberos4 starttls ssl network shell)
254 "Priority of streams to consider when opening connection to server.")
256 (defvar imap-stream-alist
257 '((gssapi imap-gssapi-stream-p imap-gssapi-open)
258 (kerberos4 imap-kerberos4-stream-p imap-kerberos4-open)
259 (ssl imap-ssl-p imap-ssl-open)
260 (network imap-network-p imap-network-open)
261 (shell imap-shell-p imap-shell-open)
262 (starttls imap-starttls-p imap-starttls-open))
263 "Definition of network streams.
267 NAME names the stream, CHECK is a function returning non-nil if the
268 server support the stream and OPEN is a function for opening the
271 (defvar imap-authenticators '(gssapi
277 "Priority of authenticators to consider when authenticating to server.")
279 (defvar imap-authenticator-alist
280 '((gssapi imap-gssapi-auth-p imap-gssapi-auth)
281 (kerberos4 imap-kerberos4-auth-p imap-kerberos4-auth)
282 (cram-md5 imap-cram-md5-p imap-cram-md5-auth)
283 (login imap-login-p imap-login-auth)
284 (anonymous imap-anonymous-p imap-anonymous-auth)
285 (digest-md5 imap-digest-md5-p imap-digest-md5-auth))
286 "Definition of authenticators.
288 \(NAME CHECK AUTHENTICATE)
290 NAME names the authenticator. CHECK is a function returning non-nil if
291 the server support the authenticator and AUTHENTICATE is a function
292 for doing the actual authentication.")
294 (defvar imap-error nil
295 "Error codes from the last command.")
297 ;; Internal constants. Change theese and die.
299 (defconst imap-default-port 143)
300 (defconst imap-default-ssl-port 993)
301 (defconst imap-default-stream 'network)
302 (defconst imap-local-variables '(imap-server
311 imap-current-target-mailbox
320 imap-calculate-literal-size-first
322 (defconst imap-log-buffer "*imap-log*")
323 (defconst imap-debug-buffer "*imap-debug*")
325 ;; Internal variables.
327 (defvar imap-stream nil)
328 (defvar imap-auth nil)
329 (defvar imap-server nil)
330 (defvar imap-port nil)
331 (defvar imap-username nil)
332 (defvar imap-password nil)
333 (defvar imap-calculate-literal-size-first nil)
334 (defvar imap-state 'closed
336 Valid states are `closed', `initial', `nonauth', `auth', `selected'
339 (defvar imap-server-eol "\r\n"
340 "The EOL string sent from the server.")
342 (defvar imap-client-eol "\r\n"
343 "The EOL string we send to the server.")
345 (defvar imap-current-mailbox nil
346 "Current mailbox name.")
348 (defvar imap-current-target-mailbox nil
349 "Current target mailbox for COPY and APPEND commands.")
351 (defvar imap-mailbox-data nil
352 "Obarray with mailbox data.")
354 (defvar imap-mailbox-prime 997
355 "Length of imap-mailbox-data.")
357 (defvar imap-current-message nil
358 "Current message number.")
360 (defvar imap-message-data nil
361 "Obarray with message data.")
363 (defvar imap-message-prime 997
364 "Length of imap-message-data.")
366 (defvar imap-capability nil
367 "Capability for server.")
369 (defvar imap-namespace nil
370 "Namespace for current server.")
372 (defvar imap-reached-tag 0
373 "Lower limit on command tags that have been parsed.")
375 (defvar imap-failed-tags nil
376 "Alist of tags that failed.
377 Each element is a list with four elements; tag (a integer), response
378 state (a symbol, `OK', `NO' or `BAD'), response code (a string), and
379 human readable response text (a string).")
382 "Command tag number.")
384 (defvar imap-process nil
387 (defvar imap-continuation nil
388 "Non-nil indicates that the server emitted a continuation request.
389 The actual value is really the text on the continuation line.")
391 (defvar imap-callbacks nil
392 "List of response tags and callbacks, on the form `(number . function)'.
393 The function should take two arguments, the first the IMAP tag and the
394 second the status (OK, NO, BAD etc) of the command.")
397 ;; Utility functions:
399 (defun imap-remassoc (key alist)
400 "Delete by side effect any elements of LIST whose car is `equal' to KEY.
401 The modified LIST is returned. If the first member
402 of LIST has a car that is `equal' to KEY, there is no way to remove it
403 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
404 sure of changing the value of `foo'."
406 (if (equal key (caar alist))
408 (setcdr alist (imap-remassoc key (cdr alist)))
411 (defsubst imap-utf7-encode (string)
415 (utf7-encode string t)
417 "imap: Could not UTF7 encode `%s', using it unencoded..."
422 (defsubst imap-utf7-decode (string)
426 (utf7-decode string t)
428 "imap: Could not UTF7 decode `%s', using it undecoded..."
433 (defsubst imap-ok-p (status)
436 (setq imap-error status)
439 (defun imap-error-text (&optional buffer)
440 (with-current-buffer (or buffer (current-buffer))
441 (nth 3 (car imap-failed-tags))))
444 ;; Server functions; stream stuff:
446 (defun imap-kerberos4-stream-p (buffer)
447 (imap-capability 'AUTH=KERBEROS_V4 buffer))
449 (defun imap-kerberos4-open (name buffer server port)
450 (let ((cmds imap-kerberos4-program)
452 (while (and (not done) (setq cmd (pop cmds)))
453 (message "Opening Kerberos 4 IMAP connection with `%s'..." cmd)
455 (let* ((port (or port imap-default-port))
456 (process-connection-type imap-process-connection-type)
457 (process (as-binary-process
459 name buffer shell-file-name shell-command-switch
464 ?p (number-to-string port)
465 ?l imap-default-user)))))
468 (with-current-buffer buffer
469 (setq imap-client-eol "\n"
470 imap-calculate-literal-size-first t)
471 (while (and (memq (process-status process) '(open run))
472 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
473 (goto-char (point-min))
474 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
475 (or (while (looking-at "^C:")
478 ;; cyrus 1.6 imtest print "S: " before server greeting
479 (or (not (looking-at "S: "))
482 (not (and (imap-parse-greeting)
483 ;; success in imtest < 1.6:
484 (or (re-search-forward
485 "^__\\(.*\\)__\n" nil t)
486 ;; success in imtest 1.6:
488 "^\\(Authenticat.*\\)" nil t))
489 (setq response (match-string 1)))))
490 (accept-process-output process 1)
493 (with-current-buffer (get-buffer-create imap-log-buffer)
494 (buffer-disable-undo)
495 (goto-char (point-max))
496 (insert-buffer-substring buffer)))
498 (message "Opening Kerberos 4 IMAP connection with `%s'...%s" cmd
499 (if response (concat "done, " response) "failed"))
500 (if (and response (let ((case-fold-search nil))
501 (not (string-match "failed" response))))
503 (if (memq (process-status process) '(open run))
504 (imap-send-command "LOGOUT"))
505 (delete-process process)
509 (defun imap-gssapi-stream-p (buffer)
510 (imap-capability 'AUTH=GSSAPI buffer))
512 (defun imap-gssapi-open (name buffer server port)
513 (let ((cmds imap-gssapi-program)
515 (while (and (not done) (setq cmd (pop cmds)))
516 (message "Opening GSSAPI IMAP connection with `%s'..." cmd)
517 (let* ((port (or port imap-default-port))
518 (process-connection-type imap-process-connection-type)
519 (process (as-binary-process
521 name buffer shell-file-name shell-command-switch
526 ?p (number-to-string port)
527 ?l imap-default-user)))))
530 (with-current-buffer buffer
531 (setq imap-client-eol "\n"
532 imap-calculate-literal-size-first t)
533 (while (and (memq (process-status process) '(open run))
534 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
535 (goto-char (point-min))
536 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
537 (or (while (looking-at "^C:")
540 ;; cyrus 1.6 imtest print "S: " before server greeting
541 (or (not (looking-at "S: "))
544 (not (and (imap-parse-greeting)
545 ;; success in imtest 1.6:
547 "^\\(Authenticat.*\\)" nil t)
548 (setq response (match-string 1)))))
549 (accept-process-output process 1)
552 (with-current-buffer (get-buffer-create imap-log-buffer)
553 (buffer-disable-undo)
554 (goto-char (point-max))
555 (insert-buffer-substring buffer)))
557 (message "GSSAPI IMAP connection: %s" (or response "failed"))
558 (if (and response (let ((case-fold-search nil))
559 (not (string-match "failed" response))))
561 (if (memq (process-status process) '(open run))
562 (imap-send-command "LOGOUT"))
563 (delete-process process)
567 (defun imap-ssl-p (buffer)
570 (defun imap-ssl-open (name buffer server port)
571 "Open a SSL connection to server."
572 (let ((cmds (if (listp imap-ssl-program) imap-ssl-program
573 (list imap-ssl-program)))
575 (while (and (not done) (setq cmd (pop cmds)))
576 (message "imap: Opening SSL connection with `%s'..." cmd)
577 (let ((port (or port imap-default-ssl-port))
578 (process-connection-type nil)
581 (setq process (as-binary-process
583 name buffer shell-file-name
588 ?p (number-to-string port))))))
589 (process-kill-without-query process))
590 (with-current-buffer buffer
591 (goto-char (point-min))
592 (while (and (memq (process-status process) '(open run))
593 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
594 (goto-char (point-max))
596 (not (imap-parse-greeting)))
597 (accept-process-output process 1)
600 (with-current-buffer (get-buffer-create imap-log-buffer)
601 (buffer-disable-undo)
602 (goto-char (point-max))
603 (insert-buffer-substring buffer)))
605 (when (memq (process-status process) '(open run))
606 (setq done process))))))
609 (message "imap: Opening SSL connection with `%s'...done" cmd)
611 (message "imap: Opening SSL connection with `%s'...failed" cmd)
614 (defun imap-network-p (buffer)
617 (defun imap-network-open (name buffer server port)
618 (let* ((port (or port imap-default-port))
619 (process (open-network-stream-as-binary name buffer server port)))
621 (while (and (memq (process-status process) '(open run))
622 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
623 (goto-char (point-min))
624 (not (imap-parse-greeting)))
625 (accept-process-output process 1)
628 (with-current-buffer (get-buffer-create imap-log-buffer)
629 (buffer-disable-undo)
630 (goto-char (point-max))
631 (insert-buffer-substring buffer)))
632 (when (memq (process-status process) '(open run))
635 (defun imap-shell-p (buffer)
638 (defun imap-shell-open (name buffer server port)
639 (let ((cmds (if (listp imap-shell-program) imap-shell-program
640 (list imap-shell-program)))
642 (while (and (not done) (setq cmd (pop cmds)))
643 (message "imap: Opening IMAP connection with `%s'..." cmd)
644 (setq imap-client-eol "\n")
645 (let* ((port (or port imap-default-port))
646 (process (as-binary-process
648 name buffer shell-file-name shell-command-switch
654 ?p (number-to-string port)
655 ?l imap-default-user))))))
657 (while (and (memq (process-status process) '(open run))
658 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
659 (goto-char (point-max))
661 (not (imap-parse-greeting)))
662 (accept-process-output process 1)
665 (with-current-buffer (get-buffer-create imap-log-buffer)
666 (buffer-disable-undo)
667 (goto-char (point-max))
668 (insert-buffer-substring buffer)))
670 (when (memq (process-status process) '(open run))
671 (setq done process)))))
674 (message "imap: Opening IMAP connection with `%s'...done" cmd)
676 (message "imap: Opening IMAP connection with `%s'...failed" cmd)
679 (defun imap-starttls-p (buffer)
680 (imap-capability 'STARTTLS buffer))
682 (defun imap-starttls-open (name buffer server port)
683 (let* ((port (or port imap-default-port))
684 (process (as-binary-process
685 (starttls-open-stream name buffer server port)))
687 (message "imap: Connecting with STARTTLS...")
689 (while (and (memq (process-status process) '(open run))
690 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
691 (goto-char (point-min))
692 (not (imap-parse-greeting)))
693 (accept-process-output process 1)
696 (with-current-buffer (get-buffer-create imap-log-buffer)
697 (buffer-disable-undo)
698 (goto-char (point-max))
699 (insert-buffer-substring buffer)))
700 (let ((imap-process process))
703 (set-process-filter imap-process 'imap-arrival-filter)
704 (when (and (eq imap-stream 'starttls)
705 (imap-ok-p (imap-send-command-wait "STARTTLS")))
706 (starttls-negotiate imap-process)))
707 (set-process-filter imap-process nil)))
708 (when (memq (process-status process) '(open run))
709 (setq done process)))
712 (message "imap: Connecting with STARTTLS...done")
714 (message "imap: Connecting with STARTTLS...failed")
717 ;; Server functions; authenticator stuff:
719 (defun imap-interactive-login (buffer loginfunc)
720 "Login to server in BUFFER.
721 LOGINFUNC is passed a username and a password, it should return t if
722 it where successful authenticating itself to the server, nil otherwise.
723 Returns t if login was successful, nil otherwise."
724 (with-current-buffer buffer
725 (make-local-variable 'imap-username)
726 (make-local-variable 'imap-password)
727 (let (user passwd ret)
728 ;; (condition-case ()
729 (while (or (not user) (not passwd))
730 (setq user (or imap-username
731 (read-from-minibuffer
732 (concat "IMAP username for " imap-server
733 " (using stream `" (symbol-name imap-stream)
735 (or user imap-default-user))))
736 (setq passwd (or imap-password
738 (concat "IMAP password for " user "@"
739 imap-server " (using authenticator `"
740 (symbol-name imap-auth) "'): "))))
741 (when (and user passwd)
742 (if (funcall loginfunc user passwd)
746 (if (and (not imap-password)
747 (y-or-n-p "Store password for this session? "))
748 (setq imap-password passwd)))
749 (message "Login failed...")
752 ;; (quit (with-current-buffer buffer
755 ;; (error (with-current-buffer buffer
760 (defun imap-gssapi-auth-p (buffer)
761 (and (imap-capability 'AUTH=GSSAPI buffer)
762 (eq imap-stream 'gssapi)))
764 (defun imap-gssapi-auth (buffer)
765 (message "imap: Authenticating using GSSAPI...%s"
766 (if (eq imap-stream 'gssapi) "done" "failed"))
767 (eq imap-stream 'gssapi))
769 (defun imap-kerberos4-auth-p (buffer)
770 (and (imap-capability 'AUTH=KERBEROS_V4 buffer)
771 (eq imap-stream 'kerberos4)))
773 (defun imap-kerberos4-auth (buffer)
774 (message "imap: Authenticating using Kerberos 4...%s"
775 (if (eq imap-stream 'kerberos4) "done" "failed"))
776 (eq imap-stream 'kerberos4))
778 (defun imap-cram-md5-p (buffer)
779 (imap-capability 'AUTH=CRAM-MD5 buffer))
781 (defun imap-cram-md5-auth (buffer)
782 "Login to server using the AUTH CRAM-MD5 method."
783 (message "imap: Authenticating using CRAM-MD5...")
784 (let ((done (imap-interactive-login
786 (lambda (user passwd)
788 (imap-send-command-wait
790 "AUTHENTICATE CRAM-MD5"
792 (let* ((decoded (base64-decode-string challenge))
794 (if (and (featurep 'xemacs)
795 (>= (function-max-args 'md5) 4))
796 (lambda (object &optional start end)
797 (md5 object start end 'binary))
799 (hash (rfc2104-hash hash-function 64 16
801 (response (concat user " " hash))
802 (encoded (base64-encode-string response)))
805 (message "imap: Authenticating using CRAM-MD5...done")
806 (message "imap: Authenticating using CRAM-MD5...failed"))))
808 (defun imap-login-p (buffer)
809 (and (not (imap-capability 'LOGINDISABLED buffer))
810 (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
812 (defun imap-login-auth (buffer)
813 "Login to server using the LOGIN command."
814 (message "imap: Plaintext authentication...")
815 (imap-interactive-login buffer
816 (lambda (user passwd)
817 (imap-ok-p (imap-send-command-wait
818 (concat "LOGIN \"" user "\" \""
821 (defun imap-anonymous-p (buffer)
824 (defun imap-anonymous-auth (buffer)
825 (message "imap: Logging in anonymously...")
826 (with-current-buffer buffer
827 (imap-ok-p (imap-send-command-wait
828 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
829 (system-name)) "\"")))))
831 (defun imap-digest-md5-p (buffer)
832 (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
834 (require 'digest-md5)
837 (defun imap-digest-md5-auth (buffer)
838 "Login to server using the AUTH DIGEST-MD5 method."
839 (message "imap: Authenticating using DIGEST-MD5...")
840 (imap-interactive-login
842 (lambda (user passwd)
846 "AUTHENTICATE DIGEST-MD5"
848 (base64-encode-string
849 (sasl-digest-md5-digest-response
850 (base64-decode-string challenge)
851 user passwd "imap" imap-server)
853 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
855 (setq imap-continuation nil)
856 (imap-send-command-1 "")
857 (imap-ok-p (imap-wait-for-tag tag)))))))
861 (defun imap-open-1 (buffer)
862 (with-current-buffer buffer
864 (setq imap-current-mailbox nil
865 imap-current-message nil
867 imap-process (condition-case ()
868 (funcall (nth 2 (assq imap-stream
870 "imap" buffer imap-server imap-port)
873 (set-process-filter imap-process 'imap-arrival-filter)
874 (set-process-sentinel imap-process 'imap-sentinel)
875 (while (and (eq imap-state 'initial)
876 (memq (process-status imap-process) '(open run)))
877 (message "Waiting for response from %s..." imap-server)
878 (accept-process-output imap-process 1))
879 (message "Waiting for response from %s...done" imap-server)
880 (and (memq (process-status imap-process) '(open run))
883 (defun imap-open (server &optional port stream auth buffer)
884 "Open a IMAP connection to host SERVER at PORT returning a buffer.
885 If PORT is unspecified, a default value is used (143 except
886 for SSL which use 993).
887 STREAM indicates the stream to use, see `imap-streams' for available
888 streams. If nil, it choices the best stream the server is capable of.
889 AUTH indicates authenticator to use, see `imap-authenticators' for
890 available authenticators. If nil, it choices the best stream the
891 server is capable of.
892 BUFFER can be a buffer or a name of a buffer, which is created if
893 necessary. If nil, the buffer name is generated."
894 (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
895 (with-current-buffer (get-buffer-create buffer)
896 (if (imap-opened buffer)
898 (mapcar 'make-local-variable imap-local-variables)
899 (set-buffer-multibyte nil)
900 (buffer-disable-undo)
901 (setq imap-server (or server imap-server))
902 (setq imap-port (or port imap-port))
903 (setq imap-auth (or auth imap-auth))
904 (setq imap-stream (or stream imap-stream))
905 (message "imap: Connecting to %s..." imap-server)
906 (if (null (let ((imap-stream (or imap-stream imap-default-stream)))
907 (imap-open-1 buffer)))
909 (message "imap: Connecting to %s...failed" imap-server)
911 (when (null imap-stream)
912 ;; Need to choose stream.
913 (let ((streams imap-streams))
914 (while (setq stream (pop streams))
915 ;; OK to use this stream?
916 (when (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
918 (if (not (eq imap-default-stream stream))
919 (with-current-buffer (get-buffer-create
920 (generate-new-buffer-name " *temp*"))
921 (mapcar 'make-local-variable imap-local-variables)
922 (set-buffer-multibyte nil)
923 (buffer-disable-undo)
924 (setq imap-server (or server imap-server))
925 (setq imap-port (or port imap-port))
926 (setq imap-auth (or auth imap-auth))
927 (message "imap: Reconnecting with stream `%s'..." stream)
928 (if (null (let ((imap-stream stream))
929 (imap-open-1 (current-buffer))))
931 (kill-buffer (current-buffer))
933 "imap: Reconnecting with stream `%s'...failed"
935 ;; We're done, kill the first connection
938 (rename-buffer buffer)
939 (message "imap: Reconnecting with stream `%s'...done"
941 (setq imap-stream stream)
942 (setq imap-capability nil)
945 (message "imap: Connecting to %s...done" imap-server)
946 (setq imap-stream stream)
947 (setq imap-capability nil)
948 (setq streams nil))))))
949 (when (imap-opened buffer)
950 (setq imap-mailbox-data (make-vector imap-mailbox-prime 0)))
954 (defun imap-opened (&optional buffer)
955 "Return non-nil if connection to imap server in BUFFER is open.
956 If BUFFER is nil then the current buffer is used."
957 (and (setq buffer (get-buffer (or buffer (current-buffer))))
958 (buffer-live-p buffer)
959 (with-current-buffer buffer
961 (memq (process-status imap-process) '(open run))))))
963 (defun imap-authenticate (&optional user passwd buffer)
964 "Authenticate to server in BUFFER, using current buffer if nil.
965 It uses the authenticator specified when opening the server. If the
966 authenticator requires username/passwords, they are queried from the
967 user and optionally stored in the buffer. If USER and/or PASSWD is
968 specified, the user will not be questioned and the username and/or
969 password is remembered in the buffer."
970 (with-current-buffer (or buffer (current-buffer))
971 (if (not (eq imap-state 'nonauth))
972 (or (eq imap-state 'auth)
973 (eq imap-state 'select)
974 (eq imap-state 'examine))
975 (make-local-variable 'imap-username)
976 (make-local-variable 'imap-password)
977 (if user (setq imap-username user))
978 (if passwd (setq imap-password passwd))
980 (and (funcall (nth 2 (assq imap-auth
981 imap-authenticator-alist)) buffer)
982 (setq imap-state 'auth))
983 ;; Choose authenticator.
984 (let ((auths imap-authenticators)
986 (while (setq auth (pop auths))
987 ;; OK to use authenticator?
988 (when (funcall (nth 1 (assq auth imap-authenticator-alist)) buffer)
989 (message "imap: Authenticating to `%s' using `%s'..."
991 (setq imap-auth auth)
992 (if (funcall (nth 2 (assq auth imap-authenticator-alist)) buffer)
994 (message "imap: Authenticating to `%s' using `%s'...done"
997 (message "imap: Authenticating to `%s' using `%s'...failed"
998 imap-server auth)))))
1001 (defun imap-close (&optional buffer)
1002 "Close connection to server in BUFFER.
1003 If BUFFER is nil, the current buffer is used."
1004 (with-current-buffer (or buffer (current-buffer))
1007 (imap-send-command-wait "LOGOUT")
1009 (when (and imap-process
1010 (memq (process-status imap-process) '(open run)))
1011 (delete-process imap-process))
1012 (setq imap-current-mailbox nil
1013 imap-current-message nil
1018 (defun imap-capability (&optional identifier buffer)
1019 "Return a list of identifiers which server in BUFFER support.
1020 If IDENTIFIER, return non-nil if it's among the servers capabilities.
1021 If BUFFER is nil, the current buffer is assumed."
1022 (with-current-buffer (or buffer (current-buffer))
1023 (unless imap-capability
1024 (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
1025 (setq imap-capability '(IMAP2))))
1027 (memq (intern (upcase (symbol-name identifier))) imap-capability)
1030 (defun imap-namespace (&optional buffer)
1031 "Return a namespace hierarchy at server in BUFFER.
1032 If BUFFER is nil, the current buffer is assumed."
1033 (with-current-buffer (or buffer (current-buffer))
1034 (unless imap-namespace
1035 (when (imap-capability 'NAMESPACE)
1036 (imap-send-command-wait "NAMESPACE")))
1039 (defun imap-send-command-wait (command &optional buffer)
1040 (imap-wait-for-tag (imap-send-command command buffer) buffer))
1043 ;; Mailbox functions:
1045 (defun imap-mailbox-put (propname value &optional mailbox buffer)
1046 (with-current-buffer (or buffer (current-buffer))
1047 (if imap-mailbox-data
1048 (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
1050 (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
1051 propname value mailbox (current-buffer)))
1054 (defsubst imap-mailbox-get-1 (propname &optional mailbox)
1055 (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
1058 (defun imap-mailbox-get (propname &optional mailbox buffer)
1059 (let ((mailbox (imap-utf7-encode mailbox)))
1060 (with-current-buffer (or buffer (current-buffer))
1061 (imap-mailbox-get-1 propname (or mailbox imap-current-mailbox)))))
1063 (defun imap-mailbox-map-1 (func &optional mailbox-decoder buffer)
1064 (with-current-buffer (or buffer (current-buffer))
1068 (push (funcall func (if mailbox-decoder
1069 (funcall mailbox-decoder (symbol-name s))
1070 (symbol-name s))) result))
1074 (defun imap-mailbox-map (func &optional buffer)
1075 "Map a function across each mailbox in `imap-mailbox-data', returning a list.
1076 Function should take a mailbox name (a string) as
1078 (imap-mailbox-map-1 func 'imap-utf7-decode buffer))
1080 (defun imap-current-mailbox (&optional buffer)
1081 (with-current-buffer (or buffer (current-buffer))
1082 (imap-utf7-decode imap-current-mailbox)))
1084 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
1085 (and (string= mailbox imap-current-mailbox)
1087 (eq imap-state 'examine))
1089 (eq imap-state 'selected)))))
1091 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
1092 (with-current-buffer (or buffer (current-buffer))
1093 (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
1095 (defun imap-mailbox-select-1 (mailbox &optional examine)
1096 "Select MAILBOX on server in BUFFER.
1097 If EXAMINE is non-nil, do a read-only select."
1098 (if (imap-current-mailbox-p-1 mailbox examine)
1099 imap-current-mailbox
1100 (setq imap-current-mailbox mailbox)
1101 (if (imap-ok-p (imap-send-command-wait
1102 (concat (if examine "EXAMINE" "SELECT") " \""
1105 (setq imap-message-data (make-vector imap-message-prime 0)
1106 imap-state (if examine 'examine 'selected))
1107 imap-current-mailbox)
1108 ;; Failed SELECT/EXAMINE unselects current mailbox
1109 (setq imap-current-mailbox nil))))
1111 (defun imap-mailbox-select (mailbox &optional examine buffer)
1112 (with-current-buffer (or buffer (current-buffer))
1114 (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
1116 (defun imap-mailbox-examine-1 (mailbox &optional buffer)
1117 (with-current-buffer (or buffer (current-buffer))
1118 (imap-mailbox-select-1 mailbox 'examine)))
1120 (defun imap-mailbox-examine (mailbox &optional buffer)
1121 "Examine MAILBOX on server in BUFFER."
1122 (imap-mailbox-select mailbox 'examine buffer))
1124 (defun imap-mailbox-unselect (&optional buffer)
1125 "Close current folder in BUFFER, without expunging articles."
1126 (with-current-buffer (or buffer (current-buffer))
1127 (when (or (eq imap-state 'auth)
1128 (and (imap-capability 'UNSELECT)
1129 (imap-ok-p (imap-send-command-wait "UNSELECT")))
1131 (imap-send-command-wait (concat "EXAMINE \""
1132 imap-current-mailbox
1134 (imap-ok-p (imap-send-command-wait "CLOSE"))))
1135 (setq imap-current-mailbox nil
1136 imap-message-data nil
1140 (defun imap-mailbox-expunge (&optional asynch buffer)
1141 "Expunge articles in current folder in BUFFER.
1142 If ASYNCH, do not wait for succesful completion of the command.
1143 If BUFFER is nil the current buffer is assumed."
1144 (with-current-buffer (or buffer (current-buffer))
1145 (when (and imap-current-mailbox (not (eq imap-state 'examine)))
1147 (imap-send-command "EXPUNGE")
1148 (imap-ok-p (imap-send-command-wait "EXPUNGE"))))))
1150 (defun imap-mailbox-close (&optional asynch buffer)
1151 "Expunge articles and close current folder in BUFFER.
1152 If ASYNCH, do not wait for succesful completion of the command.
1153 If BUFFER is nil the current buffer is assumed."
1154 (with-current-buffer (or buffer (current-buffer))
1155 (when imap-current-mailbox
1157 (imap-add-callback (imap-send-command "CLOSE")
1158 `(lambda (tag status)
1159 (message "IMAP mailbox `%s' closed... %s"
1160 imap-current-mailbox status)
1161 (when (eq ,imap-current-mailbox
1162 imap-current-mailbox)
1163 ;; Don't wipe out data if another mailbox
1165 (setq imap-current-mailbox nil
1166 imap-message-data nil
1167 imap-state 'auth))))
1168 (when (imap-ok-p (imap-send-command-wait "CLOSE"))
1169 (setq imap-current-mailbox nil
1170 imap-message-data nil
1174 (defun imap-mailbox-create-1 (mailbox)
1175 (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
1177 (defun imap-mailbox-create (mailbox &optional buffer)
1178 "Create MAILBOX on server in BUFFER.
1179 If BUFFER is nil the current buffer is assumed."
1180 (with-current-buffer (or buffer (current-buffer))
1181 (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
1183 (defun imap-mailbox-delete (mailbox &optional buffer)
1184 "Delete MAILBOX on server in BUFFER.
1185 If BUFFER is nil the current buffer is assumed."
1186 (let ((mailbox (imap-utf7-encode mailbox)))
1187 (with-current-buffer (or buffer (current-buffer))
1189 (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1191 (defun imap-mailbox-rename (oldname newname &optional buffer)
1192 "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1193 If BUFFER is nil the current buffer is assumed."
1194 (let ((oldname (imap-utf7-encode oldname))
1195 (newname (imap-utf7-encode newname)))
1196 (with-current-buffer (or buffer (current-buffer))
1198 (imap-send-command-wait (list "RENAME \"" oldname "\" "
1199 "\"" newname "\""))))))
1201 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1202 "Return a list of subscribed mailboxes on server in BUFFER.
1203 If ROOT is non-nil, only list matching mailboxes. If ADD-DELIMITER is
1204 non-nil, a hierarchy delimiter is added to root. REFERENCE is a
1205 implementation-specific string that has to be passed to lsub command."
1206 (with-current-buffer (or buffer (current-buffer))
1207 ;; Make sure we know the hierarchy separator for root's hierarchy
1208 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1209 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1210 (imap-utf7-encode root) "\"")))
1211 ;; clear list data (NB not delimiter and other stuff)
1212 (imap-mailbox-map-1 (lambda (mailbox)
1213 (imap-mailbox-put 'lsub nil mailbox)))
1215 (imap-send-command-wait
1216 (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1217 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1220 (imap-mailbox-map-1 (lambda (mailbox)
1221 (when (imap-mailbox-get-1 'lsub mailbox)
1222 (push (imap-utf7-decode mailbox) out))))
1225 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1226 "Return a list of mailboxes matching ROOT on server in BUFFER.
1227 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1228 root. REFERENCE is a implementation-specific string that has to be
1229 passed to list command."
1230 (with-current-buffer (or buffer (current-buffer))
1231 ;; Make sure we know the hierarchy separator for root's hierarchy
1232 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1233 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1234 (imap-utf7-encode root) "\"")))
1235 ;; clear list data (NB not delimiter and other stuff)
1236 (imap-mailbox-map-1 (lambda (mailbox)
1237 (imap-mailbox-put 'list nil mailbox)))
1239 (imap-send-command-wait
1240 (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1241 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1244 (imap-mailbox-map-1 (lambda (mailbox)
1245 (when (imap-mailbox-get-1 'list mailbox)
1246 (push (imap-utf7-decode mailbox) out))))
1249 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1250 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1251 Returns non-nil if successful."
1252 (with-current-buffer (or buffer (current-buffer))
1253 (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1254 (imap-utf7-encode mailbox)
1257 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1258 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1259 Returns non-nil if successful."
1260 (with-current-buffer (or buffer (current-buffer))
1261 (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1262 (imap-utf7-encode mailbox)
1265 (defun imap-mailbox-status (mailbox items &optional buffer)
1266 "Get status items ITEM in MAILBOX from server in BUFFER.
1267 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1268 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1269 or 'unseen. If ITEMS is a list of symbols, a list of values is
1270 returned, if ITEMS is a symbol only its value is returned."
1271 (with-current-buffer (or buffer (current-buffer))
1273 (imap-send-command-wait (list "STATUS \""
1274 (imap-utf7-encode mailbox)
1281 (mapcar (lambda (item)
1282 (imap-mailbox-get item mailbox))
1284 (imap-mailbox-get items mailbox)))))
1286 (defun imap-mailbox-status-asynch (mailbox items &optional buffer)
1287 "Send status item request ITEM on MAILBOX to server in BUFFER.
1288 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1289 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1290 or 'unseen. The IMAP command tag is returned."
1291 (with-current-buffer (or buffer (current-buffer))
1292 (imap-send-command (list "STATUS \""
1293 (imap-utf7-encode mailbox)
1300 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1301 "Get ACL on mailbox from server in BUFFER."
1302 (let ((mailbox (imap-utf7-encode mailbox)))
1303 (with-current-buffer (or buffer (current-buffer))
1305 (imap-send-command-wait (list "GETACL \""
1306 (or mailbox imap-current-mailbox)
1308 (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1310 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1311 "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
1312 (let ((mailbox (imap-utf7-encode mailbox)))
1313 (with-current-buffer (or buffer (current-buffer))
1315 (imap-send-command-wait (list "SETACL \""
1316 (or mailbox imap-current-mailbox)
1322 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1323 "Removes any <identifier,rights> pair for IDENTIFIER in MAILBOX from server in BUFFER."
1324 (let ((mailbox (imap-utf7-encode mailbox)))
1325 (with-current-buffer (or buffer (current-buffer))
1327 (imap-send-command-wait (list "DELETEACL \""
1328 (or mailbox imap-current-mailbox)
1333 ;; Message functions:
1335 (defun imap-current-message (&optional buffer)
1336 (with-current-buffer (or buffer (current-buffer))
1337 imap-current-message))
1339 (defun imap-list-to-message-set (list)
1340 (mapconcat (lambda (item)
1341 (number-to-string item))
1347 (defun imap-range-to-message-set (range)
1352 (car item) (cdr item))
1353 (format "%d" item)))
1354 (if (and (listp range) (not (listp (cdr range))))
1355 (list range) ;; make (1 . 2) into ((1 . 2))
1359 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1360 (with-current-buffer (or buffer (current-buffer))
1361 (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1363 (imap-list-to-message-set uids)
1367 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1368 "Fetch properties PROPS from message set UIDS from server in BUFFER.
1369 UIDS can be a string, number or a list of numbers. If RECEIVE
1370 is non-nil return theese properties."
1371 (with-current-buffer (or buffer (current-buffer))
1372 (when (imap-ok-p (imap-send-command-wait
1373 (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1375 (imap-list-to-message-set uids)
1378 (if (or (null receive) (stringp uids))
1381 (mapcar (lambda (uid)
1383 (mapcar (lambda (prop)
1384 (imap-message-get uid prop))
1386 (imap-message-get uid receive)))
1388 (imap-message-get uids receive))))))
1390 (defun imap-message-put (uid propname value &optional buffer)
1391 (with-current-buffer (or buffer (current-buffer))
1392 (if imap-message-data
1393 (put (intern (number-to-string uid) imap-message-data)
1395 (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1396 uid propname value (current-buffer)))
1399 (defun imap-message-get (uid propname &optional buffer)
1400 (with-current-buffer (or buffer (current-buffer))
1401 (get (intern-soft (number-to-string uid) imap-message-data)
1404 (defun imap-message-map (func propname &optional buffer)
1405 "Map a function across each mailbox in `imap-message-data', returning a list."
1406 (with-current-buffer (or buffer (current-buffer))
1410 (push (funcall func (get s 'UID) (get s propname)) result))
1414 (defmacro imap-message-envelope-date (uid &optional buffer)
1415 `(with-current-buffer (or ,buffer (current-buffer))
1416 (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1418 (defmacro imap-message-envelope-subject (uid &optional buffer)
1419 `(with-current-buffer (or ,buffer (current-buffer))
1420 (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1422 (defmacro imap-message-envelope-from (uid &optional buffer)
1423 `(with-current-buffer (or ,buffer (current-buffer))
1424 (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1426 (defmacro imap-message-envelope-sender (uid &optional buffer)
1427 `(with-current-buffer (or ,buffer (current-buffer))
1428 (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1430 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1431 `(with-current-buffer (or ,buffer (current-buffer))
1432 (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1434 (defmacro imap-message-envelope-to (uid &optional buffer)
1435 `(with-current-buffer (or ,buffer (current-buffer))
1436 (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1438 (defmacro imap-message-envelope-cc (uid &optional buffer)
1439 `(with-current-buffer (or ,buffer (current-buffer))
1440 (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1442 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1443 `(with-current-buffer (or ,buffer (current-buffer))
1444 (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1446 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1447 `(with-current-buffer (or ,buffer (current-buffer))
1448 (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1450 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1451 `(with-current-buffer (or ,buffer (current-buffer))
1452 (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1454 (defmacro imap-message-body (uid &optional buffer)
1455 `(with-current-buffer (or ,buffer (current-buffer))
1456 (imap-message-get ,uid 'BODY)))
1458 (defun imap-search (predicate &optional buffer)
1459 (with-current-buffer (or buffer (current-buffer))
1460 (imap-mailbox-put 'search 'dummy)
1461 (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1462 (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1464 (message "Missing SEARCH response to a SEARCH command (server not RFC compliant)...")
1466 (imap-mailbox-get-1 'search imap-current-mailbox)))))
1468 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1469 "Return t iff FLAG can be permanently (between IMAP sessions) saved on articles, in MAILBOX on server in BUFFER."
1470 (with-current-buffer (or buffer (current-buffer))
1471 (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1472 (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1474 (defun imap-message-flags-set (articles flags &optional silent buffer)
1475 (when (and articles flags)
1476 (with-current-buffer (or buffer (current-buffer))
1477 (imap-ok-p (imap-send-command-wait
1478 (concat "UID STORE " articles
1479 " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1481 (defun imap-message-flags-del (articles flags &optional silent buffer)
1482 (when (and articles flags)
1483 (with-current-buffer (or buffer (current-buffer))
1484 (imap-ok-p (imap-send-command-wait
1485 (concat "UID STORE " articles
1486 " -FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1488 (defun imap-message-flags-add (articles flags &optional silent buffer)
1489 (when (and articles flags)
1490 (with-current-buffer (or buffer (current-buffer))
1491 (imap-ok-p (imap-send-command-wait
1492 (concat "UID STORE " articles
1493 " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1495 (defun imap-message-copyuid-1 (mailbox)
1496 (if (imap-capability 'UIDPLUS)
1497 (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1498 (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1499 (let ((old-mailbox imap-current-mailbox)
1501 (imap-message-data (make-vector 2 0)))
1502 (when (imap-mailbox-examine-1 mailbox)
1504 (and (imap-fetch "*" "UID")
1505 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1506 (apply 'max (imap-message-map
1507 (lambda (uid prop) uid) 'UID))))
1509 (imap-mailbox-select old-mailbox (eq state 'examine))
1510 (imap-mailbox-unselect)))))))
1512 (defun imap-message-copyuid (mailbox &optional buffer)
1513 (with-current-buffer (or buffer (current-buffer))
1514 (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1516 (defun imap-message-copy (articles mailbox
1517 &optional dont-create no-copyuid buffer)
1518 "Copy ARTICLES (a string message set) to MAILBOX on server in
1519 BUFFER, creating mailbox if it doesn't exist. If dont-create is
1520 non-nil, it will not create a mailbox. On success, return a list with
1521 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1522 first element, rest of list contain the saved articles' UIDs."
1524 (with-current-buffer (or buffer (current-buffer))
1525 (let ((mailbox (imap-utf7-encode mailbox)))
1526 (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1527 (imap-current-target-mailbox mailbox))
1528 (if (imap-ok-p (imap-send-command-wait cmd))
1530 (when (and (not dont-create)
1531 ;; removed because of buggy Oracle server
1532 ;; that doesn't send TRYCREATE tags (which
1533 ;; is a MUST according to specifications):
1534 ;;(imap-mailbox-get-1 'trycreate mailbox)
1535 (imap-mailbox-create-1 mailbox))
1536 (imap-ok-p (imap-send-command-wait cmd)))))
1538 (imap-message-copyuid-1 mailbox)))))))
1540 (defun imap-message-appenduid-1 (mailbox)
1541 (if (imap-capability 'UIDPLUS)
1542 (imap-mailbox-get-1 'appenduid mailbox)
1543 (let ((old-mailbox imap-current-mailbox)
1545 (imap-message-data (make-vector 2 0)))
1546 (when (imap-mailbox-examine-1 mailbox)
1548 (and (imap-fetch "*" "UID")
1549 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1550 (apply 'max (imap-message-map
1551 (lambda (uid prop) uid) 'UID))))
1553 (imap-mailbox-select old-mailbox (eq state 'examine))
1554 (imap-mailbox-unselect)))))))
1556 (defun imap-message-appenduid (mailbox &optional buffer)
1557 (with-current-buffer (or buffer (current-buffer))
1558 (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1560 (defun imap-message-append (mailbox article &optional flags date-time buffer)
1561 "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1562 FLAGS and DATE-TIME is currently not used. Return a cons holding
1563 uidvalidity of MAILBOX and UID the newly created article got, or nil
1565 (let ((mailbox (imap-utf7-encode mailbox)))
1566 (with-current-buffer (or buffer (current-buffer))
1567 (and (let ((imap-current-target-mailbox mailbox))
1569 (imap-send-command-wait
1570 (list "APPEND \"" mailbox "\" " article))))
1571 (imap-message-appenduid-1 mailbox)))))
1573 (defun imap-body-lines (body)
1574 "Return number of lines in article by looking at the mime bodystructure BODY."
1576 (if (stringp (car body))
1577 (cond ((and (string= (upcase (car body)) "TEXT")
1578 (numberp (nth 7 body)))
1580 ((and (string= (upcase (car body)) "MESSAGE")
1581 (numberp (nth 9 body)))
1584 (apply '+ (mapcar 'imap-body-lines body)))
1587 (defun imap-envelope-from (from)
1588 "Return a from string line."
1590 (concat (aref from 0)
1591 (if (aref from 0) " <")
1595 (if (aref from 0) ">"))))
1598 ;; Internal functions.
1600 (defun imap-add-callback (tag func)
1601 (setq imap-callbacks (append (list (cons tag func)) imap-callbacks)))
1603 (defun imap-send-command-1 (cmdstr)
1604 (setq cmdstr (concat cmdstr imap-client-eol))
1606 (with-current-buffer (get-buffer-create imap-log-buffer)
1607 (buffer-disable-undo)
1608 (goto-char (point-max))
1610 (process-send-string imap-process cmdstr))
1612 (defun imap-send-command (command &optional buffer)
1613 (with-current-buffer (or buffer (current-buffer))
1614 (if (not (listp command)) (setq command (list command)))
1615 (let ((tag (setq imap-tag (1+ imap-tag)))
1617 (setq cmdstr (concat (number-to-string imap-tag) " "))
1618 (while (setq cmd (pop command))
1619 (cond ((stringp cmd)
1620 (setq cmdstr (concat cmdstr cmd)))
1622 (let ((eol imap-client-eol)
1623 (calcfirst imap-calculate-literal-size-first)
1625 (with-current-buffer cmd
1627 (setq size (buffer-size)))
1628 (when (not (equal eol "\r\n"))
1629 ;; XXX modifies buffer!
1630 (goto-char (point-min))
1631 (while (search-forward "\r\n" nil t)
1632 (replace-match eol)))
1634 (setq size (buffer-size))))
1636 (concat cmdstr (format "{%d}" size))))
1639 (imap-send-command-1 cmdstr)
1641 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1642 (setq command nil);; abort command if no cont-req
1643 (let ((process imap-process)
1644 (stream imap-stream)
1645 (eol imap-client-eol))
1646 (with-current-buffer cmd
1648 (with-current-buffer (get-buffer-create
1650 (buffer-disable-undo)
1651 (goto-char (point-max))
1652 (insert-buffer-substring cmd)))
1653 (process-send-region process (point-min)
1655 (process-send-string process imap-client-eol))))
1656 (setq imap-continuation nil)))
1658 (imap-send-command-1 cmdstr)
1661 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1662 (setq command nil);; abort command if no cont-req
1663 (setq command (cons (funcall cmd imap-continuation)
1665 (setq imap-continuation nil)))
1667 (error "Unknown command type"))))
1669 (imap-send-command-1 cmdstr))
1672 (defun imap-wait-for-tag (tag &optional buffer)
1673 (with-current-buffer (or buffer (current-buffer))
1674 (let (imap-have-messaged)
1675 (while (and (null imap-continuation)
1676 (memq (process-status imap-process) '(open run))
1677 (< imap-reached-tag tag))
1678 (let ((len (/ (point-max) 1024))
1681 (setq imap-have-messaged t)
1682 (message "imap read: %dk" len))
1683 (accept-process-output imap-process 1)))
1684 (when imap-have-messaged
1686 (and (memq (process-status imap-process) '(open run))
1687 (or (assq tag imap-failed-tags)
1688 (if imap-continuation
1692 (defun imap-sentinel (process string)
1693 (delete-process process))
1695 (defun imap-find-next-line ()
1696 "Return point at end of current line, taking into account literals.
1697 Return nil if no complete line has arrived."
1698 (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
1701 (if (match-string 1)
1702 (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1704 (goto-char (+ (point) (string-to-number (match-string 1))))
1705 (imap-find-next-line))
1708 (defun imap-arrival-filter (proc string)
1709 "IMAP process filter."
1710 (with-current-buffer (process-buffer proc)
1711 (goto-char (point-max))
1714 (with-current-buffer (get-buffer-create imap-log-buffer)
1715 (buffer-disable-undo)
1716 (goto-char (point-max))
1719 (goto-char (point-min))
1720 (while (setq end (imap-find-next-line))
1722 (narrow-to-region (point-min) end)
1723 (delete-backward-char (length imap-server-eol))
1724 (goto-char (point-min))
1726 (cond ((eq imap-state 'initial)
1727 (imap-parse-greeting))
1728 ((or (eq imap-state 'auth)
1729 (eq imap-state 'nonauth)
1730 (eq imap-state 'selected)
1731 (eq imap-state 'examine))
1732 (imap-parse-response))
1734 (message "Unknown state %s in arrival filter"
1736 (delete-region (point-min) (point-max))))))))
1741 (defsubst imap-forward ()
1742 (or (eobp) (forward-char)))
1745 ;; ; Unsigned 32-bit integer
1746 ;; ; (0 <= n < 4,294,967,296)
1748 (defsubst imap-parse-number ()
1749 (when (looking-at "[0-9]+")
1751 (string-to-number (match-string 0))
1752 (goto-char (match-end 0)))))
1754 ;; literal = "{" number "}" CRLF *CHAR8
1755 ;; ; Number represents the number of CHAR8s
1757 (defsubst imap-parse-literal ()
1758 (when (looking-at "{\\([0-9]+\\)}\r\n")
1759 (let ((pos (match-end 0))
1760 (len (string-to-number (match-string 1))))
1761 (if (< (point-max) (+ pos len))
1763 (goto-char (+ pos len))
1764 (buffer-substring pos (+ pos len))))))
1766 ;; string = quoted / literal
1768 ;; quoted = DQUOTE *QUOTED-CHAR DQUOTE
1770 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
1771 ;; "\" quoted-specials
1773 ;; quoted-specials = DQUOTE / "\"
1775 ;; TEXT-CHAR = <any CHAR except CR and LF>
1777 (defsubst imap-parse-string ()
1778 (cond ((eq (char-after) ?\")
1780 (let ((p (point)) (name ""))
1781 (skip-chars-forward "^\"\\\\")
1782 (setq name (buffer-substring p (point)))
1783 (while (eq (char-after) ?\\)
1784 (setq p (1+ (point)))
1786 (skip-chars-forward "^\"\\\\")
1787 (setq name (concat name (buffer-substring p (point)))))
1790 ((eq (char-after) ?{)
1791 (imap-parse-literal))))
1795 (defsubst imap-parse-nil ()
1796 (if (looking-at "NIL")
1797 (goto-char (match-end 0))))
1799 ;; nstring = string / nil
1801 (defsubst imap-parse-nstring ()
1802 (or (imap-parse-string)
1803 (and (imap-parse-nil)
1806 ;; astring = atom / string
1808 ;; atom = 1*ATOM-CHAR
1810 ;; ATOM-CHAR = <any CHAR except atom-specials>
1812 ;; atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards /
1815 ;; list-wildcards = "%" / "*"
1817 ;; quoted-specials = DQUOTE / "\"
1819 (defsubst imap-parse-astring ()
1820 (or (imap-parse-string)
1821 (buffer-substring (point)
1822 (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
1823 (goto-char (1- (match-end 0)))
1827 ;; address = "(" addr-name SP addr-adl SP addr-mailbox SP
1830 ;; addr-adl = nstring
1831 ;; ; Holds route from [RFC-822] route-addr if
1834 ;; addr-host = nstring
1835 ;; ; nil indicates [RFC-822] group syntax.
1836 ;; ; Otherwise, holds [RFC-822] domain name
1838 ;; addr-mailbox = nstring
1839 ;; ; nil indicates end of [RFC-822] group; if
1840 ;; ; non-nil and addr-host is nil, holds
1841 ;; ; [RFC-822] group name.
1842 ;; ; Otherwise, holds [RFC-822] local-part
1843 ;; ; after removing [RFC-822] quoting
1845 ;; addr-name = nstring
1846 ;; ; If non-nil, holds phrase from [RFC-822]
1847 ;; ; mailbox after removing [RFC-822] quoting
1850 (defsubst imap-parse-address ()
1852 (when (eq (char-after) ?\()
1854 (setq address (vector (prog1 (imap-parse-nstring)
1856 (prog1 (imap-parse-nstring)
1858 (prog1 (imap-parse-nstring)
1860 (imap-parse-nstring)))
1861 (when (eq (char-after) ?\))
1865 ;; address-list = "(" 1*address ")" / nil
1869 (defsubst imap-parse-address-list ()
1870 (if (eq (char-after) ?\()
1871 (let (address addresses)
1873 (while (and (not (eq (char-after) ?\)))
1874 ;; next line for MS Exchange bug
1875 (progn (and (eq (char-after) ? ) (imap-forward)) t)
1876 (setq address (imap-parse-address)))
1877 (setq addresses (cons address addresses)))
1878 (when (eq (char-after) ?\))
1880 (nreverse addresses)))
1881 (assert (imap-parse-nil) t "In imap-parse-address-list")))
1883 ;; mailbox = "INBOX" / astring
1884 ;; ; INBOX is case-insensitive. All case variants of
1885 ;; ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
1886 ;; ; not as an astring. An astring which consists of
1887 ;; ; the case-insensitive sequence "I" "N" "B" "O" "X"
1888 ;; ; is considered to be INBOX and not an astring.
1889 ;; ; Refer to section 5.1 for further
1890 ;; ; semantic details of mailbox names.
1892 (defsubst imap-parse-mailbox ()
1893 (let ((mailbox (imap-parse-astring)))
1894 (if (string-equal "INBOX" (upcase mailbox))
1898 ;; greeting = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
1900 ;; resp-cond-auth = ("OK" / "PREAUTH") SP resp-text
1901 ;; ; Authentication condition
1903 ;; resp-cond-bye = "BYE" SP resp-text
1905 (defun imap-parse-greeting ()
1906 "Parse a IMAP greeting."
1907 (cond ((looking-at "\\* OK ")
1908 (setq imap-state 'nonauth))
1909 ((looking-at "\\* PREAUTH ")
1910 (setq imap-state 'auth))
1911 ((looking-at "\\* BYE ")
1912 (setq imap-state 'closed))))
1914 ;; response = *(continue-req / response-data) response-done
1916 ;; continue-req = "+" SP (resp-text / base64) CRLF
1918 ;; response-data = "*" SP (resp-cond-state / resp-cond-bye /
1919 ;; mailbox-data / message-data / capability-data) CRLF
1921 ;; response-done = response-tagged / response-fatal
1923 ;; response-fatal = "*" SP resp-cond-bye CRLF
1924 ;; ; Server closes connection immediately
1926 ;; response-tagged = tag SP resp-cond-state CRLF
1928 ;; resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
1929 ;; ; Status condition
1931 ;; resp-cond-bye = "BYE" SP resp-text
1933 ;; mailbox-data = "FLAGS" SP flag-list /
1934 ;; "LIST" SP mailbox-list /
1935 ;; "LSUB" SP mailbox-list /
1936 ;; "SEARCH" *(SP nz-number) /
1937 ;; "STATUS" SP mailbox SP "("
1938 ;; [status-att SP number *(SP status-att SP number)] ")" /
1939 ;; number SP "EXISTS" /
1940 ;; number SP "RECENT"
1942 ;; message-data = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
1944 ;; capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
1946 ;; ; IMAP4rev1 servers which offer RFC 1730
1947 ;; ; compatibility MUST list "IMAP4" as the first
1950 (defun imap-parse-response ()
1951 "Parse a IMAP command response."
1953 (case (setq token (read (current-buffer)))
1954 (+ (setq imap-continuation
1955 (or (buffer-substring (min (point-max) (1+ (point)))
1958 (* (case (prog1 (setq token (read (current-buffer)))
1960 (OK (imap-parse-resp-text))
1961 (NO (imap-parse-resp-text))
1962 (BAD (imap-parse-resp-text))
1963 (BYE (imap-parse-resp-text))
1964 (FLAGS (imap-mailbox-put 'flags (imap-parse-flag-list)))
1965 (LIST (imap-parse-data-list 'list))
1966 (LSUB (imap-parse-data-list 'lsub))
1967 (SEARCH (imap-mailbox-put
1969 (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
1970 (STATUS (imap-parse-status))
1971 (CAPABILITY (setq imap-capability
1972 (read (concat "(" (upcase (buffer-substring
1973 (point) (point-max)))
1975 (ACL (imap-parse-acl))
1976 (t (case (prog1 (read (current-buffer))
1978 (EXISTS (imap-mailbox-put 'exists token))
1979 (RECENT (imap-mailbox-put 'recent token))
1981 (FETCH (imap-parse-fetch token))
1982 (t (message "Garbage: %s" (buffer-string)))))))
1984 (if (not (integerp token))
1985 (message "Garbage: %s" (buffer-string))
1986 (case (prog1 (setq status (read (current-buffer)))
1989 (setq imap-reached-tag (max imap-reached-tag token))
1990 (imap-parse-resp-text)))
1992 (setq imap-reached-tag (max imap-reached-tag token))
1994 (imap-parse-resp-text))
1996 (when (eq (char-after) ?\[)
1997 (setq code (buffer-substring (point)
1998 (search-forward "]")))
2000 (setq text (buffer-substring (point) (point-max)))
2001 (push (list token status code text)
2002 imap-failed-tags))))
2004 (setq imap-reached-tag (max imap-reached-tag token))
2006 (imap-parse-resp-text))
2008 (when (eq (char-after) ?\[)
2009 (setq code (buffer-substring (point)
2010 (search-forward "]")))
2012 (setq text (buffer-substring (point) (point-max)))
2013 (push (list token status code text) imap-failed-tags)
2014 (error "Internal error, tag %s status %s code %s text %s"
2015 token status code text))))
2016 (t (message "Garbage: %s" (buffer-string))))
2017 (when (assq token imap-callbacks)
2018 (funcall (cdr (assq token imap-callbacks)) token status)
2019 (setq imap-callbacks
2020 (imap-remassoc token imap-callbacks)))))))))
2022 ;; resp-text = ["[" resp-text-code "]" SP] text
2024 ;; text = 1*TEXT-CHAR
2026 ;; TEXT-CHAR = <any CHAR except CR and LF>
2028 (defun imap-parse-resp-text ()
2029 (imap-parse-resp-text-code))
2031 ;; resp-text-code = "ALERT" /
2032 ;; "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
2033 ;; "NEWNAME" SP string SP string /
2035 ;; "PERMANENTFLAGS" SP "("
2036 ;; [flag-perm *(SP flag-perm)] ")" /
2040 ;; "UIDNEXT" SP nz-number /
2041 ;; "UIDVALIDITY" SP nz-number /
2042 ;; "UNSEEN" SP nz-number /
2043 ;; resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
2045 ;; resp_code_apnd = "APPENDUID" SPACE nz_number SPACE uniqueid
2047 ;; resp_code_copy = "COPYUID" SPACE nz_number SPACE set SPACE set
2049 ;; set = sequence-num / (sequence-num ":" sequence-num) /
2051 ;; ; Identifies a set of messages. For message
2052 ;; ; sequence numbers, these are consecutive
2053 ;; ; numbers from 1 to the number of messages in
2055 ;; ; Comma delimits individual numbers, colon
2056 ;; ; delimits between two numbers inclusive.
2057 ;; ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
2058 ;; ; 14,15 for a mailbox with 15 messages.
2060 ;; sequence-num = nz-number / "*"
2061 ;; ; * is the largest number in use. For message
2062 ;; ; sequence numbers, it is the number of messages
2063 ;; ; in the mailbox. For unique identifiers, it is
2064 ;; ; the unique identifier of the last message in
2067 ;; flag-perm = flag / "\*"
2069 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2070 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2071 ;; ; Does not include "\Recent"
2073 ;; flag-extension = "\" atom
2074 ;; ; Future expansion. Client implementations
2075 ;; ; MUST accept flag-extension flags. Server
2076 ;; ; implementations MUST NOT generate
2077 ;; ; flag-extension flags except as defined by
2078 ;; ; future standard or standards-track
2079 ;; ; revisions of this specification.
2081 ;; flag-keyword = atom
2083 ;; resp-text-atom = 1*<any ATOM-CHAR except "]">
2085 (defun imap-parse-resp-text-code ()
2086 ;; xxx next line for stalker communigate pro 3.3.1 bug
2087 (when (looking-at " \\[")
2089 (when (eq (char-after) ?\[)
2091 (cond ((search-forward "PERMANENTFLAGS " nil t)
2092 (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2093 ((search-forward "UIDNEXT \\([0-9]+\\)" nil t)
2094 (imap-mailbox-put 'uidnext (match-string 1)))
2095 ((search-forward "UNSEEN " nil t)
2096 (imap-mailbox-put 'first-unseen (read (current-buffer))))
2097 ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2098 (imap-mailbox-put 'uidvalidity (match-string 1)))
2099 ((search-forward "READ-ONLY" nil t)
2100 (imap-mailbox-put 'read-only t))
2101 ((search-forward "NEWNAME " nil t)
2102 (let (oldname newname)
2103 (setq oldname (imap-parse-string))
2105 (setq newname (imap-parse-string))
2106 (imap-mailbox-put 'newname newname oldname)))
2107 ((search-forward "TRYCREATE" nil t)
2108 (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2109 ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2110 (imap-mailbox-put 'appenduid
2111 (list (match-string 1)
2112 (string-to-number (match-string 2)))
2113 imap-current-target-mailbox))
2114 ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2115 (imap-mailbox-put 'copyuid (list (match-string 1)
2118 imap-current-target-mailbox))
2119 ((search-forward "ALERT] " nil t)
2120 (message "Imap server %s information: %s" imap-server
2121 (buffer-substring (point) (point-max)))))))
2123 ;; mailbox-list = "(" [mbx-list-flags] ")" SP
2124 ;; (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2126 ;; mbx-list-flags = *(mbx-list-oflag SP) mbx-list-sflag
2127 ;; *(SP mbx-list-oflag) /
2128 ;; mbx-list-oflag *(SP mbx-list-oflag)
2130 ;; mbx-list-oflag = "\Noinferiors" / flag-extension
2131 ;; ; Other flags; multiple possible per LIST response
2133 ;; mbx-list-sflag = "\Noselect" / "\Marked" / "\Unmarked"
2134 ;; ; Selectability flags; only one per LIST response
2136 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2137 ;; "\" quoted-specials
2139 ;; quoted-specials = DQUOTE / "\"
2141 (defun imap-parse-data-list (type)
2142 (let (flags delimiter mailbox)
2143 (setq flags (imap-parse-flag-list))
2144 (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2145 (setq delimiter (match-string 1))
2146 (goto-char (1+ (match-end 0)))
2147 (when (setq mailbox (imap-parse-mailbox))
2148 (imap-mailbox-put type t mailbox)
2149 (imap-mailbox-put 'list-flags flags mailbox)
2150 (imap-mailbox-put 'delimiter delimiter mailbox)))))
2152 ;; msg_att ::= "(" 1#("ENVELOPE" SPACE envelope /
2153 ;; "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2154 ;; "INTERNALDATE" SPACE date_time /
2155 ;; "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2156 ;; "RFC822.SIZE" SPACE number /
2157 ;; "BODY" ["STRUCTURE"] SPACE body /
2158 ;; "BODY" section ["<" number ">"] SPACE nstring /
2159 ;; "UID" SPACE uniqueid) ")"
2161 ;; date_time ::= <"> date_day_fixed "-" date_month "-" date_year
2162 ;; SPACE time SPACE zone <">
2164 ;; section ::= "[" [section_text / (nz_number *["." nz_number]
2165 ;; ["." (section_text / "MIME")])] "]"
2167 ;; section_text ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2168 ;; SPACE header_list / "TEXT"
2170 ;; header_fld_name ::= astring
2172 ;; header_list ::= "(" 1#header_fld_name ")"
2174 (defsubst imap-parse-header-list ()
2175 (when (eq (char-after) ?\()
2177 (while (not (eq (char-after) ?\)))
2179 (push (imap-parse-astring) strlist))
2181 (nreverse strlist))))
2183 (defsubst imap-parse-fetch-body-section ()
2185 (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2186 (if (eq (char-before) ? )
2188 (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2189 (search-forward "]" nil t))
2192 (defun imap-parse-fetch (response)
2193 (when (eq (char-after) ?\()
2194 (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2195 rfc822size body bodydetail bodystructure flags-empty)
2196 (while (not (eq (char-after) ?\)))
2198 (let ((token (read (current-buffer))))
2200 (cond ((eq token 'UID)
2201 (setq uid (condition-case ()
2202 (read (current-buffer))
2205 (setq flags (imap-parse-flag-list))
2207 (setq flags-empty 't)))
2208 ((eq token 'ENVELOPE)
2209 (setq envelope (imap-parse-envelope)))
2210 ((eq token 'INTERNALDATE)
2211 (setq internaldate (imap-parse-string)))
2213 (setq rfc822 (imap-parse-nstring)))
2214 ((eq token 'RFC822.HEADER)
2215 (setq rfc822header (imap-parse-nstring)))
2216 ((eq token 'RFC822.TEXT)
2217 (setq rfc822text (imap-parse-nstring)))
2218 ((eq token 'RFC822.SIZE)
2219 (setq rfc822size (read (current-buffer))))
2221 (if (eq (char-before) ?\[)
2223 (upcase (imap-parse-fetch-body-section))
2224 (and (eq (char-after) ?<)
2225 (buffer-substring (1+ (point))
2226 (search-forward ">" nil t)))
2227 (progn (imap-forward)
2228 (imap-parse-nstring)))
2230 (setq body (imap-parse-body))))
2231 ((eq token 'BODYSTRUCTURE)
2232 (setq bodystructure (imap-parse-body))))))
2234 (setq imap-current-message uid)
2235 (imap-message-put uid 'UID uid)
2236 (and (or flags flags-empty) (imap-message-put uid 'FLAGS flags))
2237 (and envelope (imap-message-put uid 'ENVELOPE envelope))
2238 (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2239 (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2240 (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2241 (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2242 (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2243 (and body (imap-message-put uid 'BODY body))
2244 (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2245 (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2246 (run-hooks 'imap-fetch-data-hook)))))
2248 ;; mailbox-data = ...
2249 ;; "STATUS" SP mailbox SP "("
2250 ;; [status-att SP number
2251 ;; *(SP status-att SP number)] ")"
2254 ;; status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2257 (defun imap-parse-status ()
2258 (let ((mailbox (imap-parse-mailbox)))
2259 (if (eq (char-after) ? )
2261 (when (and mailbox (eq (char-after) ?\())
2262 (while (and (not (eq (char-after) ?\)))
2263 (or (forward-char) t)
2264 (looking-at "\\([A-Za-z]+\\) "))
2265 (let ((token (match-string 1)))
2266 (goto-char (match-end 0))
2267 (cond ((string= token "MESSAGES")
2268 (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2269 ((string= token "RECENT")
2270 (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2271 ((string= token "UIDNEXT")
2272 (and (looking-at "[0-9]+")
2273 (imap-mailbox-put 'uidnext (match-string 0) mailbox)
2274 (goto-char (match-end 0))))
2275 ((string= token "UIDVALIDITY")
2276 (and (looking-at "[0-9]+")
2277 (imap-mailbox-put 'uidvalidity (match-string 0) mailbox)
2278 (goto-char (match-end 0))))
2279 ((string= token "UNSEEN")
2280 (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2282 (message "Unknown status data %s in mailbox %s ignored"
2284 (read (current-buffer)))))))))
2286 ;; acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2289 ;; identifier ::= astring
2291 ;; rights ::= astring
2293 (defun imap-parse-acl ()
2294 (let ((mailbox (imap-parse-mailbox))
2295 identifier rights acl)
2296 (while (eq (char-after) ?\ )
2298 (setq identifier (imap-parse-astring))
2300 (setq rights (imap-parse-astring))
2301 (setq acl (append acl (list (cons identifier rights)))))
2302 (imap-mailbox-put 'acl acl mailbox)))
2304 ;; flag-list = "(" [flag *(SP flag)] ")"
2306 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2307 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2308 ;; ; Does not include "\Recent"
2310 ;; flag-keyword = atom
2312 ;; flag-extension = "\" atom
2313 ;; ; Future expansion. Client implementations
2314 ;; ; MUST accept flag-extension flags. Server
2315 ;; ; implementations MUST NOT generate
2316 ;; ; flag-extension flags except as defined by
2317 ;; ; future standard or standards-track
2318 ;; ; revisions of this specification.
2320 (defun imap-parse-flag-list ()
2321 (let (flag-list start)
2322 (assert (eq (char-after) ?\() t "In imap-parse-flag-list")
2323 (while (and (not (eq (char-after) ?\)))
2326 ;; next line for Courier IMAP bug.
2327 (skip-chars-forward " ")
2329 (> (skip-chars-forward "^ )" (imap-point-at-eol)) 0))
2330 (push (buffer-substring start (point)) flag-list))
2331 (assert (eq (char-after) ?\)) t "In imap-parse-flag-list")
2333 (nreverse flag-list)))
2335 ;; envelope = "(" env-date SP env-subject SP env-from SP env-sender SP
2336 ;; env-reply-to SP env-to SP env-cc SP env-bcc SP
2337 ;; env-in-reply-to SP env-message-id ")"
2339 ;; env-bcc = "(" 1*address ")" / nil
2341 ;; env-cc = "(" 1*address ")" / nil
2343 ;; env-date = nstring
2345 ;; env-from = "(" 1*address ")" / nil
2347 ;; env-in-reply-to = nstring
2349 ;; env-message-id = nstring
2351 ;; env-reply-to = "(" 1*address ")" / nil
2353 ;; env-sender = "(" 1*address ")" / nil
2355 ;; env-subject = nstring
2357 ;; env-to = "(" 1*address ")" / nil
2359 (defun imap-parse-envelope ()
2360 (when (eq (char-after) ?\()
2362 (vector (prog1 (imap-parse-nstring);; date
2364 (prog1 (imap-parse-nstring);; subject
2366 (prog1 (imap-parse-address-list);; from
2368 (prog1 (imap-parse-address-list);; sender
2370 (prog1 (imap-parse-address-list);; reply-to
2372 (prog1 (imap-parse-address-list);; to
2374 (prog1 (imap-parse-address-list);; cc
2376 (prog1 (imap-parse-address-list);; bcc
2378 (prog1 (imap-parse-nstring);; in-reply-to
2380 (prog1 (imap-parse-nstring);; message-id
2383 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2385 (defsubst imap-parse-string-list ()
2386 (cond ((eq (char-after) ?\();; body-fld-param
2389 (while (setq str (imap-parse-string))
2391 ;; buggy stalker communigate pro 3.0 doesn't print SPC
2392 ;; between body-fld-param's sometimes
2393 (or (eq (char-after) ?\")
2395 (nreverse strlist)))
2399 ;; body-extension = nstring / number /
2400 ;; "(" body-extension *(SP body-extension) ")"
2401 ;; ; Future expansion. Client implementations
2402 ;; ; MUST accept body-extension fields. Server
2403 ;; ; implementations MUST NOT generate
2404 ;; ; body-extension fields except as defined by
2405 ;; ; future standard or standards-track
2406 ;; ; revisions of this specification.
2408 (defun imap-parse-body-extension ()
2409 (if (eq (char-after) ?\()
2412 (push (imap-parse-body-extension) b-e)
2413 (while (eq (char-after) ?\ )
2415 (push (imap-parse-body-extension) b-e))
2416 (assert (eq (char-after) ?\)) t "In imap-parse-body-extension")
2419 (or (imap-parse-number)
2420 (imap-parse-nstring))))
2422 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2423 ;; *(SP body-extension)]]
2424 ;; ; MUST NOT be returned on non-extensible
2427 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2428 ;; *(SP body-extension)]]
2429 ;; ; MUST NOT be returned on non-extensible
2432 (defsubst imap-parse-body-ext ()
2434 (when (eq (char-after) ?\ );; body-fld-dsp
2437 (if (eq (char-after) ?\()
2440 (push (imap-parse-string) dsp)
2442 (push (imap-parse-string-list) dsp)
2444 (assert (imap-parse-nil) t "In imap-parse-body-ext"))
2445 (push (nreverse dsp) ext))
2446 (when (eq (char-after) ?\ );; body-fld-lang
2448 (if (eq (char-after) ?\()
2449 (push (imap-parse-string-list) ext)
2450 (push (imap-parse-nstring) ext))
2451 (while (eq (char-after) ?\ );; body-extension
2453 (setq ext (append (imap-parse-body-extension) ext)))))
2456 ;; body = "(" body-type-1part / body-type-mpart ")"
2458 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2459 ;; *(SP body-extension)]]
2460 ;; ; MUST NOT be returned on non-extensible
2463 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2464 ;; *(SP body-extension)]]
2465 ;; ; MUST NOT be returned on non-extensible
2468 ;; body-fields = body-fld-param SP body-fld-id SP body-fld-desc SP
2469 ;; body-fld-enc SP body-fld-octets
2471 ;; body-fld-desc = nstring
2473 ;; body-fld-dsp = "(" string SP body-fld-param ")" / nil
2475 ;; body-fld-enc = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2476 ;; "QUOTED-PRINTABLE") DQUOTE) / string
2478 ;; body-fld-id = nstring
2480 ;; body-fld-lang = nstring / "(" string *(SP string) ")"
2482 ;; body-fld-lines = number
2484 ;; body-fld-md5 = nstring
2486 ;; body-fld-octets = number
2488 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2490 ;; body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2491 ;; [SP body-ext-1part]
2493 ;; body-type-basic = media-basic SP body-fields
2494 ;; ; MESSAGE subtype MUST NOT be "RFC822"
2496 ;; body-type-msg = media-message SP body-fields SP envelope
2497 ;; SP body SP body-fld-lines
2499 ;; body-type-text = media-text SP body-fields SP body-fld-lines
2501 ;; body-type-mpart = 1*body SP media-subtype
2502 ;; [SP body-ext-mpart]
2504 ;; media-basic = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2505 ;; "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2506 ;; ; Defined in [MIME-IMT]
2508 ;; media-message = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2509 ;; ; Defined in [MIME-IMT]
2511 ;; media-subtype = string
2512 ;; ; Defined in [MIME-IMT]
2514 ;; media-text = DQUOTE "TEXT" DQUOTE SP media-subtype
2515 ;; ; Defined in [MIME-IMT]
2517 (defun imap-parse-body ()
2519 (when (eq (char-after) ?\()
2521 (if (eq (char-after) ?\()
2523 (while (and (eq (char-after) ?\()
2524 (setq subbody (imap-parse-body)))
2525 ;; buggy stalker communigate pro 3.0 insert a SPC between
2526 ;; parts in multiparts
2527 (when (and (eq (char-after) ?\ )
2528 (eq (char-after (1+ (point))) ?\())
2530 (push subbody body))
2532 (push (imap-parse-string) body);; media-subtype
2533 (when (eq (char-after) ?\ );; body-ext-mpart:
2535 (if (eq (char-after) ?\();; body-fld-param
2536 (push (imap-parse-string-list) body)
2537 (push (and (imap-parse-nil) nil) body))
2539 (append (imap-parse-body-ext) body)));; body-ext-...
2540 (assert (eq (char-after) ?\)) t "In imap-parse-body")
2544 (push (imap-parse-string) body);; media-type
2546 (push (imap-parse-string) body);; media-subtype
2548 ;; next line for Sun SIMS bug
2549 (and (eq (char-after) ? ) (imap-forward))
2550 (if (eq (char-after) ?\();; body-fld-param
2551 (push (imap-parse-string-list) body)
2552 (push (and (imap-parse-nil) nil) body))
2554 (push (imap-parse-nstring) body);; body-fld-id
2556 (push (imap-parse-nstring) body);; body-fld-desc
2558 ;; next `or' for Sun SIMS bug, it regard body-fld-enc as a
2559 ;; nstring and return nil instead of defaulting back to 7BIT
2560 ;; as the standard says.
2561 (push (or (imap-parse-nstring) "7BIT") body);; body-fld-enc
2563 (push (imap-parse-number) body);; body-fld-octets
2565 ;; ok, we're done parsing the required parts, what comes now is one
2568 ;; envelope (then we're parsing body-type-msg)
2569 ;; body-fld-lines (then we're parsing body-type-text)
2570 ;; body-ext-1part (then we're parsing body-type-basic)
2572 ;; the problem is that the two first are in turn optionally followed
2573 ;; by the third. So we parse the first two here (if there are any)...
2575 (when (eq (char-after) ?\ )
2578 (cond ((eq (char-after) ?\();; body-type-msg:
2579 (push (imap-parse-envelope) body);; envelope
2581 (push (imap-parse-body) body);; body
2582 ;; buggy stalker communigate pro 3.0 doesn't print
2583 ;; number of lines in message/rfc822 attachment
2584 (if (eq (char-after) ?\))
2587 (push (imap-parse-number) body))) ;; body-fld-lines
2588 ((setq lines (imap-parse-number)) ;; body-type-text:
2589 (push lines body)) ;; body-fld-lines
2591 (backward-char))))) ;; no match...
2593 ;; ...and then parse the third one here...
2595 (when (eq (char-after) ?\ );; body-ext-1part:
2597 (push (imap-parse-nstring) body);; body-fld-md5
2598 (setq body (append (imap-parse-body-ext) body)));; body-ext-1part..
2600 (assert (eq (char-after) ?\)) t "In imap-parse-body 2")
2604 (when imap-debug ; (untrace-all)
2606 (buffer-disable-undo (get-buffer-create imap-debug-buffer))
2607 (mapcar (lambda (f) (trace-function-background f imap-debug-buffer))
2618 imap-interactive-login
2634 imap-send-command-wait
2639 imap-current-mailbox
2640 imap-current-mailbox-p-1
2641 imap-current-mailbox-p
2642 imap-mailbox-select-1
2644 imap-mailbox-examine-1
2645 imap-mailbox-examine
2646 imap-mailbox-unselect
2647 imap-mailbox-expunge
2649 imap-mailbox-create-1
2655 imap-mailbox-subscribe
2656 imap-mailbox-unsubscribe
2658 imap-mailbox-acl-get
2659 imap-mailbox-acl-set
2660 imap-mailbox-acl-delete
2661 imap-current-message
2662 imap-list-to-message-set
2669 imap-message-flag-permanent-p
2670 imap-message-flags-set
2671 imap-message-flags-del
2672 imap-message-flags-add
2673 imap-message-copyuid-1
2674 imap-message-copyuid
2676 imap-message-appenduid-1
2677 imap-message-appenduid
2689 imap-parse-resp-text
2690 imap-parse-resp-text-code
2691 imap-parse-data-list
2695 imap-parse-flag-list
2697 imap-parse-body-extension
2703 ;;; imap.el ends here