1 ;;; imap.el --- imap library
2 ;; Copyright (C) 1998, 1999, 2000, 2001
3 ;; Free Software Foundation, Inc.
5 ;; Author: Simon Josefsson <jas@pdc.kth.se>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
27 ;; imap.el is a elisp library providing an interface for talking to
30 ;; imap.el is roughly divided in two parts, one that parses IMAP
31 ;; responses from the server and storing data into buffer-local
32 ;; variables, and one for utility functions which send commands to
33 ;; server, waits for an answer, and return information. The latter
34 ;; part is layered on top of the previous.
36 ;; The imap.el API consist of the following functions, other functions
37 ;; in this file should not be called directly and the result of doing
38 ;; so are at best undefined.
42 ;; imap-open, imap-opened, imap-authenticate, imap-close,
43 ;; imap-capability, imap-namespace, imap-error-text
47 ;; imap-mailbox-get, imap-mailbox-map, imap-current-mailbox,
48 ;; imap-current-mailbox-p, imap-search, imap-mailbox-select,
49 ;; imap-mailbox-examine, imap-mailbox-unselect, imap-mailbox-expunge
50 ;; imap-mailbox-close, imap-mailbox-create, imap-mailbox-delete
51 ;; imap-mailbox-rename, imap-mailbox-lsub, imap-mailbox-list
52 ;; imap-mailbox-subscribe, imap-mailbox-unsubscribe, imap-mailbox-status
53 ;; imap-mailbox-acl-get, imap-mailbox-acl-set, imap-mailbox-acl-delete
57 ;; imap-fetch-asynch, imap-fetch,
58 ;; imap-current-message, imap-list-to-message-set,
59 ;; imap-message-get, imap-message-map
60 ;; imap-message-envelope-date, imap-message-envelope-subject,
61 ;; imap-message-envelope-from, imap-message-envelope-sender,
62 ;; imap-message-envelope-reply-to, imap-message-envelope-to,
63 ;; imap-message-envelope-cc, imap-message-envelope-bcc
64 ;; imap-message-envelope-in-reply-to, imap-message-envelope-message-id
65 ;; imap-message-body, imap-message-flag-permanent-p
66 ;; imap-message-flags-set, imap-message-flags-del
67 ;; imap-message-flags-add, imap-message-copyuid
68 ;; imap-message-copy, imap-message-appenduid
69 ;; imap-message-append, imap-envelope-from
72 ;; It is my hope that theese commands should be pretty self
73 ;; explanatory for someone that know IMAP. All functions have
74 ;; additional documentation on how to invoke them.
76 ;; imap.el support RFC1730/2060 (IMAP4/IMAP4rev1), implemented IMAP
77 ;; extensions are RFC2195 (CRAM-MD5), RFC2086 (ACL), RFC2342
78 ;; (NAMESPACE), RFC2359 (UIDPLUS), the IMAP-part of RFC2595 (STARTTLS,
79 ;; LOGINDISABLED) (with use of external library starttls.el and
80 ;; program starttls) and the GSSAPI / kerberos V4 sections of RFC1731
81 ;; (with use of external program `imtest'). It also take advantage
82 ;; the UNSELECT extension in Cyrus IMAPD.
84 ;; Without the work of John McClary Prevost and Jim Radford this library
85 ;; would not have seen the light of day. Many thanks.
87 ;; This is a transcript of short interactive session for demonstration
90 ;; (imap-open "my.mail.server")
91 ;; => " *imap* my.mail.server:0"
93 ;; The rest are invoked with current buffer as the buffer returned by
94 ;; `imap-open'. It is possible to do all without this, but it would
95 ;; look ugly here since `buffer' is always the last argument for all
96 ;; imap.el API functions.
98 ;; (imap-authenticate "myusername" "mypassword")
101 ;; (imap-mailbox-lsub "*")
102 ;; => ("INBOX.sentmail" "INBOX.private" "INBOX.draft" "INBOX.spam")
104 ;; (imap-mailbox-list "INBOX.n%")
105 ;; => ("INBOX.namedroppers" "INBOX.nnimap" "INBOX.ntbugtraq")
107 ;; (imap-mailbox-select "INBOX.nnimap")
110 ;; (imap-mailbox-get 'exists)
113 ;; (imap-mailbox-get 'uidvalidity)
116 ;; (imap-search "FLAGGED SINCE 18-DEC-98")
119 ;; (imap-fetch 235 "RFC822.PEEK" 'RFC822)
120 ;; => "X-Sieve: cmu-sieve 1.3^M\nX-Username: <jas@pdc.kth.se>^M\r...."
124 ;; o Parse UIDs as strings? We need to overcome the 28 bit limit somehow.
125 ;; o Don't use `read' at all (important places already fixed)
126 ;; o Accept list of articles instead of message set string in most
127 ;; imap-message-* functions.
131 ;; - 19991218 added starttls/digest-md5 patch,
132 ;; by Daiki Ueno <ueno@ueda.info.waseda.ac.jp>
133 ;; NB! you need SLIM for starttls.el and digest-md5.el
134 ;; - 19991023 commited to pgnus
139 (eval-when-compile (require 'cl))
140 (eval-when-compile (require 'static))
145 (autoload 'open-ssl-stream "ssl")
146 (autoload 'starttls-open-stream "starttls")
147 (autoload 'starttls-negotiate "starttls")
148 (autoload 'rfc2104-hash "rfc2104")
149 (autoload 'md5 "md5")
150 (autoload 'utf7-encode "utf7")
151 (autoload 'utf7-decode "utf7")
152 (autoload 'format-spec "format-spec")
153 (autoload 'format-spec-make "format-spec")
154 ;; Avoid use gnus-point-at-eol so we're independent of Gnus. These
155 ;; days we have point-at-eol anyhow.
156 (if (fboundp 'point-at-eol)
157 (defalias 'imap-point-at-eol 'point-at-eol)
158 (defun imap-point-at-eol ()
162 (autoload 'sasl-digest-md5-digest-response "sasl"))
167 "Low-level IMAP issues."
171 (defcustom imap-kerberos4-program '("imtest -m kerberos_v4 -u %l -p %p %s"
173 "List of strings containing commands for Kerberos 4 authentication.
174 %s is replaced with server hostname, %p with port to connect to, and
175 %l with the value of `imap-default-user'. The program should accept
176 IMAP commands on stdin and return responses to stdout. Each entry in
177 the list is tried until a successful connection is made."
179 :type '(repeat string))
181 (defcustom imap-gssapi-program '("imtest -m gssapi -u %l -p %p %s")
182 "List of strings containing commands for GSSAPI (krb5) authentication.
183 %s is replaced with server hostname, %p with port to connect to, and
184 %l with the value of `imap-default-user'. The program should accept
185 IMAP commands on stdin and return responses to stdout. Each entry in
186 the list is tried until a successful connection is made."
188 :type '(repeat string))
190 (defcustom imap-ssl-program '("openssl s_client -quiet -ssl3 -connect %s:%p"
191 "openssl s_client -quiet -ssl2 -connect %s:%p"
192 "s_client -quiet -ssl3 -connect %s:%p"
193 "s_client -quiet -ssl2 -connect %s:%p")
194 "A string, or list of strings, containing commands for SSL connections.
195 Within a string, %s is replaced with the server address and %p with
196 port number on server. The program should accept IMAP commands on
197 stdin and return responses to stdout. Each entry in the list is tried
198 until a successful connection is made."
200 :type '(choice string
203 (defcustom imap-shell-program '("ssh %s imapd"
205 "ssh %g ssh %s imapd"
206 "rsh %g rsh %s imapd")
207 "A list of strings, containing commands for IMAP connection.
208 Within a string, %s is replaced with the server address, %p with port
209 number on server, %g with `imap-shell-host', and %l with
210 `imap-default-user'. The program should read IMAP commands from stdin
211 and write IMAP response to stdout. Each entry in the list is tried
212 until a successful connection is made."
214 :type '(repeat string))
216 (defcustom imap-process-connection-type nil
217 "*Value for `process-connection-type' to use for Kerberos4 and GSSAPI."
221 (defcustom imap-use-utf7 t
222 "If non-nil, do utf7 encoding/decoding of mailbox names.
223 Since the UTF7 decoding currently only decodes into ISO-8859-1
224 characters, you may disable this decoding if you need to access UTF7
225 encoded mailboxes which doesn't translate into ISO-8859-1."
229 (defcustom imap-log nil
230 "If non-nil, a imap session trace is placed in *imap-log* buffer."
234 (defcustom imap-debug nil
235 "If non-nil, random debug spews are placed in *imap-debug* buffer."
239 (defcustom imap-shell-host "gateway"
240 "Hostname of rlogin proxy."
244 (defcustom imap-default-user (user-login-name)
245 "Default username to use."
249 ;; Various variables.
251 (defvar imap-fetch-data-hook nil
252 "Hooks called after receiving each FETCH response.")
254 (defvar imap-streams '(gssapi kerberos4 starttls ssl network shell)
255 "Priority of streams to consider when opening connection to server.")
257 (defvar imap-stream-alist
258 '((gssapi imap-gssapi-stream-p imap-gssapi-open)
259 (kerberos4 imap-kerberos4-stream-p imap-kerberos4-open)
260 (ssl imap-ssl-p imap-ssl-open)
261 (network imap-network-p imap-network-open)
262 (shell imap-shell-p imap-shell-open)
263 (starttls imap-starttls-p imap-starttls-open))
264 "Definition of network streams.
268 NAME names the stream, CHECK is a function returning non-nil if the
269 server support the stream and OPEN is a function for opening the
272 (defvar imap-authenticators '(gssapi
278 "Priority of authenticators to consider when authenticating to server.")
280 (defvar imap-authenticator-alist
281 '((gssapi imap-gssapi-auth-p imap-gssapi-auth)
282 (kerberos4 imap-kerberos4-auth-p imap-kerberos4-auth)
283 (cram-md5 imap-cram-md5-p imap-cram-md5-auth)
284 (login imap-login-p imap-login-auth)
285 (anonymous imap-anonymous-p imap-anonymous-auth)
286 (digest-md5 imap-digest-md5-p imap-digest-md5-auth))
287 "Definition of authenticators.
289 \(NAME CHECK AUTHENTICATE)
291 NAME names the authenticator. CHECK is a function returning non-nil if
292 the server support the authenticator and AUTHENTICATE is a function
293 for doing the actual authentication.")
295 (defvar imap-error nil
296 "Error codes from the last command.")
298 ;; Internal constants. Change theese and die.
300 (defconst imap-default-port 143)
301 (defconst imap-default-ssl-port 993)
302 (defconst imap-default-stream 'network)
303 (defconst imap-local-variables '(imap-server
312 imap-current-target-mailbox
321 imap-calculate-literal-size-first
323 (defconst imap-log-buffer "*imap-log*")
324 (defconst imap-debug-buffer "*imap-debug*")
326 ;; Internal variables.
328 (defvar imap-stream nil)
329 (defvar imap-auth nil)
330 (defvar imap-server nil)
331 (defvar imap-port nil)
332 (defvar imap-username nil)
333 (defvar imap-password nil)
334 (defvar imap-calculate-literal-size-first nil)
335 (defvar imap-state 'closed
337 Valid states are `closed', `initial', `nonauth', `auth', `selected'
340 (defvar imap-server-eol "\r\n"
341 "The EOL string sent from the server.")
343 (defvar imap-client-eol "\r\n"
344 "The EOL string we send to the server.")
346 (defvar imap-current-mailbox nil
347 "Current mailbox name.")
349 (defvar imap-current-target-mailbox nil
350 "Current target mailbox for COPY and APPEND commands.")
352 (defvar imap-mailbox-data nil
353 "Obarray with mailbox data.")
355 (defvar imap-mailbox-prime 997
356 "Length of imap-mailbox-data.")
358 (defvar imap-current-message nil
359 "Current message number.")
361 (defvar imap-message-data nil
362 "Obarray with message data.")
364 (defvar imap-message-prime 997
365 "Length of imap-message-data.")
367 (defvar imap-capability nil
368 "Capability for server.")
370 (defvar imap-namespace nil
371 "Namespace for current server.")
373 (defvar imap-reached-tag 0
374 "Lower limit on command tags that have been parsed.")
376 (defvar imap-failed-tags nil
377 "Alist of tags that failed.
378 Each element is a list with four elements; tag (a integer), response
379 state (a symbol, `OK', `NO' or `BAD'), response code (a string), and
380 human readable response text (a string).")
383 "Command tag number.")
385 (defvar imap-process nil
388 (defvar imap-continuation nil
389 "Non-nil indicates that the server emitted a continuation request.
390 The actually value is really the text on the continuation line.")
392 (defvar imap-callbacks nil
393 "List of response tags and callbacks, on the form `(number . function)'.
394 The function should take two arguments, the first the IMAP tag and the
395 second the status (OK, NO, BAD etc) of the command.")
398 ;; Utility functions:
400 (defun imap-remassoc (key alist)
401 "Delete by side effect any elements of LIST whose car is `equal' to KEY.
402 The modified LIST is returned. If the first member
403 of LIST has a car that is `equal' to KEY, there is no way to remove it
404 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
405 sure of changing the value of `foo'."
407 (if (equal key (caar alist))
409 (setcdr alist (imap-remassoc key (cdr alist)))
412 (defun imap-read-passwd (prompt &rest args)
413 "Read a password using PROMPT.
414 If ARGS, PROMPT is used as an argument to `format'."
415 (let ((prompt (if args
416 (apply 'format prompt args)
418 (funcall (if (or (fboundp 'read-passwd)
420 (fboundp 'read-passwd))
421 (and (load "passwd" t)
422 (fboundp 'read-passwd)))
424 (autoload 'ange-ftp-read-passwd "ange-ftp")
425 'ange-ftp-read-passwd)
428 (defsubst imap-utf7-encode (string)
432 (utf7-encode string t)
434 "imap: Could not UTF7 encode `%s', using it unencoded..."
439 (defsubst imap-utf7-decode (string)
443 (utf7-decode string t)
445 "imap: Could not UTF7 decode `%s', using it undecoded..."
450 (defsubst imap-ok-p (status)
453 (setq imap-error status)
456 (defun imap-error-text (&optional buffer)
457 (with-current-buffer (or buffer (current-buffer))
458 (nth 3 (car imap-failed-tags))))
461 ;; Server functions; stream stuff:
463 (defun imap-kerberos4-stream-p (buffer)
464 (imap-capability 'AUTH=KERBEROS_V4 buffer))
466 (defun imap-kerberos4-open (name buffer server port)
467 (let ((cmds imap-kerberos4-program)
469 (while (and (not done) (setq cmd (pop cmds)))
470 (message "Opening Kerberos 4 IMAP connection with `%s'..." cmd)
472 (let* ((port (or port imap-default-port))
473 (process-connection-type imap-process-connection-type)
474 (process (as-binary-process
476 name buffer shell-file-name shell-command-switch
481 ?p (number-to-string port)
482 ?l imap-default-user)))))
485 (with-current-buffer buffer
486 (setq imap-client-eol "\n"
487 imap-calculate-literal-size-first t)
488 (while (and (memq (process-status process) '(open run))
489 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
490 (goto-char (point-min))
491 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
492 (or (while (looking-at "^C:")
495 ;; cyrus 1.6 imtest print "S: " before server greeting
496 (or (not (looking-at "S: "))
499 (not (and (imap-parse-greeting)
500 ;; success in imtest < 1.6:
501 (or (re-search-forward
502 "^__\\(.*\\)__\n" nil t)
503 ;; success in imtest 1.6:
505 "^\\(Authenticat.*\\)" nil t))
506 (setq response (match-string 1)))))
507 (accept-process-output process 1)
510 (with-current-buffer (get-buffer-create imap-log-buffer)
511 (buffer-disable-undo)
512 (goto-char (point-max))
513 (insert-buffer-substring buffer)))
515 (message "Opening Kerberos 4 IMAP connection with `%s'...%s" cmd
516 (if response (concat "done, " response) "failed"))
517 (if (and response (let ((case-fold-search nil))
518 (not (string-match "failed" response))))
520 (if (memq (process-status process) '(open run))
521 (imap-send-command-wait "LOGOUT"))
522 (delete-process process)
526 (defun imap-gssapi-stream-p (buffer)
527 (imap-capability 'AUTH=GSSAPI buffer))
529 (defun imap-gssapi-open (name buffer server port)
530 (let ((cmds imap-gssapi-program)
532 (while (and (not done) (setq cmd (pop cmds)))
533 (message "Opening GSSAPI IMAP connection with `%s'..." cmd)
534 (let* ((port (or port imap-default-port))
535 (process-connection-type imap-process-connection-type)
536 (process (as-binary-process
538 name buffer shell-file-name shell-command-switch
543 ?p (number-to-string port)
544 ?l imap-default-user)))))
547 (with-current-buffer buffer
548 (setq imap-client-eol "\n"
549 imap-calculate-literal-size-first t)
550 (while (and (memq (process-status process) '(open run))
551 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
552 (goto-char (point-min))
553 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
554 (or (while (looking-at "^C:")
557 ;; cyrus 1.6 imtest print "S: " before server greeting
558 (or (not (looking-at "S: "))
561 (not (and (imap-parse-greeting)
562 ;; success in imtest 1.6:
564 "^\\(Authenticat.*\\)" nil t)
565 (setq response (match-string 1)))))
566 (accept-process-output process 1)
569 (with-current-buffer (get-buffer-create imap-log-buffer)
570 (buffer-disable-undo)
571 (goto-char (point-max))
572 (insert-buffer-substring buffer)))
574 (message "GSSAPI IMAP connection: %s" (or response "failed"))
575 (if (and response (let ((case-fold-search nil))
576 (not (string-match "failed" response))))
578 (if (memq (process-status process) '(open run))
579 (imap-send-command-wait "LOGOUT"))
580 (delete-process process)
584 (defun imap-ssl-p (buffer)
587 (defun imap-ssl-open (name buffer server port)
588 "Open a SSL connection to server."
589 (let ((cmds (if (listp imap-ssl-program) imap-ssl-program
590 (list imap-ssl-program)))
595 (while (and (not done) (setq cmd (pop cmds)))
596 (message "imap: Opening SSL connection with `%s'..." cmd)
597 (let* ((port (or port imap-default-ssl-port))
598 (ssl-program-name shell-file-name)
599 (ssl-program-arguments
600 (list shell-command-switch
601 (format-spec cmd (format-spec-make
603 ?p (number-to-string port)))))
607 (cond ((eq system-type 'windows-nt)
608 (let (selective-display
609 (coding-system-for-write 'binary)
610 (coding-system-for-read 'raw-text-dos)
611 (output-coding-system 'binary)
612 (input-coding-system 'raw-text-dos))
613 (open-ssl-stream name buffer server port)))
616 (open-ssl-stream name buffer server port))))
618 (with-current-buffer buffer
619 (goto-char (point-min))
620 (while (and (memq (process-status process) '(open run))
621 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
622 (goto-char (point-max))
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)))
633 (when (memq (process-status process) '(open run))
634 (setq done process))))))
637 (message "imap: Opening SSL connection with `%s'...done" cmd)
639 (message "imap: Opening SSL connection with `%s'...failed" cmd)
642 (defun imap-network-p (buffer)
645 (defun imap-network-open (name buffer server port)
646 (let* ((port (or port imap-default-port))
647 (process (open-network-stream-as-binary name buffer server port)))
649 (while (and (memq (process-status process) '(open run))
650 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
651 (goto-char (point-min))
652 (not (imap-parse-greeting)))
653 (accept-process-output process 1)
656 (with-current-buffer (get-buffer-create imap-log-buffer)
657 (buffer-disable-undo)
658 (goto-char (point-max))
659 (insert-buffer-substring buffer)))
660 (when (memq (process-status process) '(open run))
663 (defun imap-shell-p (buffer)
666 (defun imap-shell-open (name buffer server port)
667 (let ((cmds imap-shell-program)
669 (while (and (not done) (setq cmd (pop cmds)))
670 (message "imap: Opening IMAP connection with `%s'..." cmd)
671 (setq imap-client-eol "\n")
672 (let* ((port (or port imap-default-port))
673 (process (as-binary-process
675 name buffer shell-file-name shell-command-switch
681 ?p (number-to-string port)
682 ?l imap-default-user))))))
684 (while (and (memq (process-status process) '(open run))
685 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
686 (goto-char (point-min))
687 (not (imap-parse-greeting)))
688 (accept-process-output process 1)
691 (with-current-buffer (get-buffer-create imap-log-buffer)
692 (buffer-disable-undo)
693 (goto-char (point-max))
694 (insert-buffer-substring buffer)))
696 (when (memq (process-status process) '(open run))
697 (setq done process)))))
700 (message "imap: Opening IMAP connection with `%s'...done" cmd)
702 (message "imap: Opening IMAP connection with `%s'...failed" cmd)
705 (defun imap-starttls-p (buffer)
706 (and (imap-capability 'STARTTLS buffer)
710 (call-process "starttls"))
713 (defun imap-starttls-open (name buffer server port)
714 (let* ((port (or port imap-default-port))
715 (process (as-binary-process
716 (starttls-open-stream name buffer server port)))
718 (message "imap: Connecting with STARTTLS...")
720 (while (and (memq (process-status process) '(open run))
721 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
722 (goto-char (point-min))
723 (not (imap-parse-greeting)))
724 (accept-process-output process 1)
727 (with-current-buffer (get-buffer-create imap-log-buffer)
728 (buffer-disable-undo)
729 (goto-char (point-max))
730 (insert-buffer-substring buffer)))
731 (let ((imap-process process))
734 (set-process-filter imap-process 'imap-arrival-filter)
735 (when (and (eq imap-stream 'starttls)
736 (imap-ok-p (imap-send-command-wait "STARTTLS")))
737 (starttls-negotiate imap-process)))
738 (set-process-filter imap-process nil)))
739 (when (memq (process-status process) '(open run))
740 (setq done process)))
743 (message "imap: Connecting with STARTTLS...done")
745 (message "imap: Connecting with STARTTLS...failed")
748 ;; Server functions; authenticator stuff:
750 (defun imap-interactive-login (buffer loginfunc)
751 "Login to server in BUFFER.
752 LOGINFUNC is passed a username and a password, it should return t if
753 it where sucessful authenticating itself to the server, nil otherwise.
754 Returns t if login was successful, nil otherwise."
755 (with-current-buffer buffer
756 (make-local-variable 'imap-username)
757 (make-local-variable 'imap-password)
758 (let (user passwd ret)
759 ;; (condition-case ()
760 (while (or (not user) (not passwd))
761 (setq user (or imap-username
762 (read-from-minibuffer
763 (concat "IMAP username for " imap-server ": ")
764 (or user imap-default-user))))
765 (setq passwd (or imap-password
767 (concat "IMAP password for " user "@"
769 (when (and user passwd)
770 (if (funcall loginfunc user passwd)
774 (if (and (not imap-password)
775 (y-or-n-p "Store password for this session? "))
776 (setq imap-password passwd)))
777 (message "Login failed...")
780 ;; (quit (with-current-buffer buffer
783 ;; (error (with-current-buffer buffer
788 (defun imap-gssapi-auth-p (buffer)
789 (and (imap-capability 'AUTH=GSSAPI buffer)
791 (let (prg (prgs imap-gssapi-program))
792 (while (setq prg (pop prgs))
794 (and (call-process (substring prg 0 (string-match " " prg)))
795 (throw 'imtest-found t))
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)
806 (let (prg (prgs imap-kerberos4-program))
807 (while (setq prg (pop prgs))
809 (and (call-process (substring prg 0 (string-match " " prg)))
810 (throw 'imtest-found t))
813 (defun imap-kerberos4-auth (buffer)
814 (message "imap: Authenticating using Kerberos 4...%s"
815 (if (eq imap-stream 'kerberos4) "done" "failed"))
816 (eq imap-stream 'kerberos4))
818 (defun imap-cram-md5-p (buffer)
819 (imap-capability 'AUTH=CRAM-MD5 buffer))
821 (defun imap-cram-md5-auth (buffer)
822 "Login to server using the AUTH CRAM-MD5 method."
823 (message "imap: Authenticating using CRAM-MD5...")
824 (let ((done (imap-interactive-login
826 (lambda (user passwd)
828 (imap-send-command-wait
830 "AUTHENTICATE CRAM-MD5"
832 (let* ((decoded (base64-decode-string challenge))
834 (if (and (featurep 'xemacs)
835 (>= (function-max-args 'md5) 4))
836 (lambda (object &optional start end)
837 (md5 object start end 'binary))
839 (hash (rfc2104-hash hash-function 64 16
841 (response (concat user " " hash))
842 (encoded (base64-encode-string response)))
845 (message "imap: Authenticating using CRAM-MD5...done")
846 (message "imap: Authenticating using CRAM-MD5...failed"))))
848 (defun imap-login-p (buffer)
849 (and (not (imap-capability 'LOGINDISABLED buffer))
850 (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
852 (defun imap-login-auth (buffer)
853 "Login to server using the LOGIN command."
854 (message "imap: Plaintext authentication...")
855 (imap-interactive-login buffer
856 (lambda (user passwd)
857 (imap-ok-p (imap-send-command-wait
858 (concat "LOGIN \"" user "\" \""
861 (defun imap-anonymous-p (buffer)
864 (defun imap-anonymous-auth (buffer)
865 (message "imap: Loging in anonymously...")
866 (with-current-buffer buffer
867 (imap-ok-p (imap-send-command-wait
868 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
869 (system-name)) "\"")))))
871 (defun imap-digest-md5-p (buffer)
872 (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
874 (require 'digest-md5)
877 (defun imap-digest-md5-auth (buffer)
878 "Login to server using the AUTH DIGEST-MD5 method."
879 (message "imap: Authenticating using DIGEST-MD5...")
880 (imap-interactive-login
882 (lambda (user passwd)
886 "AUTHENTICATE DIGEST-MD5"
888 (base64-encode-string
889 (sasl-digest-md5-digest-response
890 (base64-decode-string challenge)
891 user passwd "imap" imap-server)
893 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
895 (setq imap-continuation nil)
896 (imap-send-command-1 "")
897 (imap-ok-p (imap-wait-for-tag tag)))))))
901 (defun imap-open-1 (buffer)
902 (with-current-buffer buffer
904 (setq imap-current-mailbox nil
905 imap-current-message nil
907 imap-process (condition-case ()
908 (funcall (nth 2 (assq imap-stream
910 "imap" buffer imap-server imap-port)
913 (set-process-filter imap-process 'imap-arrival-filter)
914 (set-process-sentinel imap-process 'imap-sentinel)
915 (while (and (eq imap-state 'initial)
916 (memq (process-status imap-process) '(open run)))
917 (message "Waiting for response from %s..." imap-server)
918 (accept-process-output imap-process 1))
919 (message "Waiting for response from %s...done" imap-server)
920 (and (memq (process-status imap-process) '(open run))
923 (defun imap-open (server &optional port stream auth buffer)
924 "Open a IMAP connection to host SERVER at PORT returning a buffer.
925 If PORT is unspecified, a default value is used (143 except
926 for SSL which use 993).
927 STREAM indicates the stream to use, see `imap-streams' for available
928 streams. If nil, it choices the best stream the server is capable of.
929 AUTH indicates authenticator to use, see `imap-authenticators' for
930 available authenticators. If nil, it choices the best stream the
931 server is capable of.
932 BUFFER can be a buffer or a name of a buffer, which is created if
933 necessery. If nil, the buffer name is generated."
934 (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
935 (with-current-buffer (get-buffer-create buffer)
936 (if (imap-opened buffer)
938 (mapcar 'make-local-variable imap-local-variables)
939 (set-buffer-multibyte nil)
940 (buffer-disable-undo)
941 (setq imap-server (or server imap-server))
942 (setq imap-port (or port imap-port))
943 (setq imap-auth (or auth imap-auth))
944 (setq imap-stream (or stream imap-stream))
945 (message "imap: Connecting to %s..." imap-server)
946 (if (let ((imap-stream (or imap-stream imap-default-stream)))
947 (imap-open-1 buffer))
949 (let (stream-changed)
950 (message "imap: Connecting to %s...done" imap-server)
951 (when (null imap-stream)
952 (let ((streams imap-streams))
953 (while (setq stream (pop streams))
954 (if (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
955 (setq stream-changed (not (eq (or imap-stream
961 (error "Couldn't figure out a stream for server"))))
963 (message "imap: Reconnecting with stream `%s'..." imap-stream)
965 (if (imap-open-1 buffer)
966 (message "imap: Reconnecting with stream `%s'...done"
968 (message "imap: Reconnecting with stream `%s'...failed"
970 (setq imap-capability nil))
971 (if (imap-opened buffer)
972 ;; Choose authenticator
973 (when (and (null imap-auth) (not (eq imap-state 'auth)))
974 (let ((auths imap-authenticators))
975 (while (setq auth (pop auths))
976 (if (funcall (nth 1 (assq auth imap-authenticator-alist))
981 (error "Couldn't figure out authenticator for server"))))))
982 (message "imap: Connecting to %s...failed" imap-server))
983 (when (imap-opened buffer)
984 (setq imap-mailbox-data (make-vector imap-mailbox-prime 0))
987 (defun imap-opened (&optional buffer)
988 "Return non-nil if connection to imap server in BUFFER is open.
989 If BUFFER is nil then the current buffer is used."
990 (and (setq buffer (get-buffer (or buffer (current-buffer))))
991 (buffer-live-p buffer)
992 (with-current-buffer buffer
994 (memq (process-status imap-process) '(open run))))))
996 (defun imap-authenticate (&optional user passwd buffer)
997 "Authenticate to server in BUFFER, using current buffer if nil.
998 It uses the authenticator specified when opening the server. If the
999 authenticator requires username/passwords, they are queried from the
1000 user and optionally stored in the buffer. If USER and/or PASSWD is
1001 specified, the user will not be questioned and the username and/or
1002 password is remembered in the buffer."
1003 (with-current-buffer (or buffer (current-buffer))
1004 (if (not (eq imap-state 'nonauth))
1005 (or (eq imap-state 'auth)
1006 (eq imap-state 'select)
1007 (eq imap-state 'examine))
1008 (make-local-variable 'imap-username)
1009 (make-local-variable 'imap-password)
1010 (if user (setq imap-username user))
1011 (if passwd (setq imap-password passwd))
1012 (if (funcall (nth 2 (assq imap-auth imap-authenticator-alist)) buffer)
1013 (setq imap-state 'auth)))))
1015 (defun imap-close (&optional buffer)
1016 "Close connection to server in BUFFER.
1017 If BUFFER is nil, the current buffer is used."
1018 (with-current-buffer (or buffer (current-buffer))
1020 (imap-send-command-wait "LOGOUT"))
1021 (when (and imap-process
1022 (memq (process-status imap-process) '(open run)))
1023 (delete-process imap-process))
1024 (setq imap-current-mailbox nil
1025 imap-current-message nil
1030 (defun imap-capability (&optional identifier buffer)
1031 "Return a list of identifiers which server in BUFFER support.
1032 If IDENTIFIER, return non-nil if it's among the servers capabilities.
1033 If BUFFER is nil, the current buffer is assumed."
1034 (with-current-buffer (or buffer (current-buffer))
1035 (unless imap-capability
1036 (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
1037 (setq imap-capability '(IMAP2))))
1039 (memq (intern (upcase (symbol-name identifier))) imap-capability)
1042 (defun imap-namespace (&optional buffer)
1043 "Return a namespace hierarchy at server in BUFFER.
1044 If BUFFER is nil, the current buffer is assumed."
1045 (with-current-buffer (or buffer (current-buffer))
1046 (unless imap-namespace
1047 (when (imap-capability 'NAMESPACE)
1048 (imap-send-command-wait "NAMESPACE")))
1051 (defun imap-send-command-wait (command &optional buffer)
1052 (imap-wait-for-tag (imap-send-command command buffer) buffer))
1055 ;; Mailbox functions:
1057 (defun imap-mailbox-put (propname value &optional mailbox buffer)
1058 (with-current-buffer (or buffer (current-buffer))
1059 (if imap-mailbox-data
1060 (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
1062 (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
1063 propname value mailbox (current-buffer)))
1066 (defsubst imap-mailbox-get-1 (propname &optional mailbox)
1067 (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
1070 (defun imap-mailbox-get (propname &optional mailbox buffer)
1071 (let ((mailbox (imap-utf7-encode mailbox)))
1072 (with-current-buffer (or buffer (current-buffer))
1073 (imap-mailbox-get-1 propname (or mailbox imap-current-mailbox)))))
1075 (defun imap-mailbox-map-1 (func &optional mailbox-decoder buffer)
1076 (with-current-buffer (or buffer (current-buffer))
1080 (push (funcall func (if mailbox-decoder
1081 (funcall mailbox-decoder (symbol-name s))
1082 (symbol-name s))) result))
1086 (defun imap-mailbox-map (func &optional buffer)
1087 "Map a function across each mailbox in `imap-mailbox-data', returning a list.
1088 Function should take a mailbox name (a string) as
1090 (imap-mailbox-map-1 func 'imap-utf7-decode buffer))
1092 (defun imap-current-mailbox (&optional buffer)
1093 (with-current-buffer (or buffer (current-buffer))
1094 (imap-utf7-decode imap-current-mailbox)))
1096 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
1097 (and (string= mailbox imap-current-mailbox)
1099 (eq imap-state 'examine))
1101 (eq imap-state 'selected)))))
1103 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
1104 (with-current-buffer (or buffer (current-buffer))
1105 (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
1107 (defun imap-mailbox-select-1 (mailbox &optional examine)
1108 "Select MAILBOX on server in BUFFER.
1109 If EXAMINE is non-nil, do a read-only select."
1110 (if (imap-current-mailbox-p-1 mailbox examine)
1111 imap-current-mailbox
1112 (setq imap-current-mailbox mailbox)
1113 (if (imap-ok-p (imap-send-command-wait
1114 (concat (if examine "EXAMINE" "SELECT") " \""
1117 (setq imap-message-data (make-vector imap-message-prime 0)
1118 imap-state (if examine 'examine 'selected))
1119 imap-current-mailbox)
1120 ;; Failed SELECT/EXAMINE unselects current mailbox
1121 (setq imap-current-mailbox nil))))
1123 (defun imap-mailbox-select (mailbox &optional examine buffer)
1124 (with-current-buffer (or buffer (current-buffer))
1126 (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
1128 (defun imap-mailbox-examine-1 (mailbox &optional buffer)
1129 (with-current-buffer (or buffer (current-buffer))
1130 (imap-mailbox-select-1 mailbox 'examine)))
1132 (defun imap-mailbox-examine (mailbox &optional buffer)
1133 "Examine MAILBOX on server in BUFFER."
1134 (imap-mailbox-select mailbox 'examine buffer))
1136 (defun imap-mailbox-unselect (&optional buffer)
1137 "Close current folder in BUFFER, without expunging articles."
1138 (with-current-buffer (or buffer (current-buffer))
1139 (when (or (eq imap-state 'auth)
1140 (and (imap-capability 'UNSELECT)
1141 (imap-ok-p (imap-send-command-wait "UNSELECT")))
1143 (imap-send-command-wait (concat "EXAMINE \""
1144 imap-current-mailbox
1146 (imap-ok-p (imap-send-command-wait "CLOSE"))))
1147 (setq imap-current-mailbox nil
1148 imap-message-data nil
1152 (defun imap-mailbox-expunge (&optional asynch buffer)
1153 "Expunge articles in current folder in BUFFER.
1154 If ASYNCH, do not wait for succesful completion of the command.
1155 If BUFFER is nil the current buffer is assumed."
1156 (with-current-buffer (or buffer (current-buffer))
1157 (when (and imap-current-mailbox (not (eq imap-state 'examine)))
1159 (imap-send-command "EXPUNGE")
1160 (imap-ok-p (imap-send-command-wait "EXPUNGE"))))))
1162 (defun imap-mailbox-close (&optional asynch buffer)
1163 "Expunge articles and close current folder in BUFFER.
1164 If ASYNCH, do not wait for succesful completion of the command.
1165 If BUFFER is nil the current buffer is assumed."
1166 (with-current-buffer (or buffer (current-buffer))
1167 (when imap-current-mailbox
1169 (imap-add-callback (imap-send-command "CLOSE")
1170 `(lambda (tag status)
1171 (message "IMAP mailbox `%s' closed... %s"
1172 imap-current-mailbox status)
1173 (when (eq ,imap-current-mailbox
1174 imap-current-mailbox)
1175 ;; Don't wipe out data if another mailbox
1177 (setq imap-current-mailbox nil
1178 imap-message-data nil
1179 imap-state 'auth))))
1180 (when (imap-ok-p (imap-send-command-wait "CLOSE"))
1181 (setq imap-current-mailbox nil
1182 imap-message-data nil
1186 (defun imap-mailbox-create-1 (mailbox)
1187 (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
1189 (defun imap-mailbox-create (mailbox &optional buffer)
1190 "Create MAILBOX on server in BUFFER.
1191 If BUFFER is nil the current buffer is assumed."
1192 (with-current-buffer (or buffer (current-buffer))
1193 (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
1195 (defun imap-mailbox-delete (mailbox &optional buffer)
1196 "Delete MAILBOX on server in BUFFER.
1197 If BUFFER is nil the current buffer is assumed."
1198 (let ((mailbox (imap-utf7-encode mailbox)))
1199 (with-current-buffer (or buffer (current-buffer))
1201 (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1203 (defun imap-mailbox-rename (oldname newname &optional buffer)
1204 "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1205 If BUFFER is nil the current buffer is assumed."
1206 (let ((oldname (imap-utf7-encode oldname))
1207 (newname (imap-utf7-encode newname)))
1208 (with-current-buffer (or buffer (current-buffer))
1210 (imap-send-command-wait (list "RENAME \"" oldname "\" "
1211 "\"" newname "\""))))))
1213 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1214 "Return a list of subscribed mailboxes on server in BUFFER.
1215 If ROOT is non-nil, only list matching mailboxes. If ADD-DELIMITER is
1216 non-nil, a hierarchy delimiter is added to root. REFERENCE is a
1217 implementation-specific string that has to be passed to lsub command."
1218 (with-current-buffer (or buffer (current-buffer))
1219 ;; Make sure we know the hierarchy separator for root's hierarchy
1220 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1221 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1222 (imap-utf7-encode root) "\"")))
1223 ;; clear list data (NB not delimiter and other stuff)
1224 (imap-mailbox-map-1 (lambda (mailbox)
1225 (imap-mailbox-put 'lsub nil mailbox)))
1227 (imap-send-command-wait
1228 (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1229 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1232 (imap-mailbox-map-1 (lambda (mailbox)
1233 (when (imap-mailbox-get-1 'lsub mailbox)
1234 (push (imap-utf7-decode mailbox) out))))
1237 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1238 "Return a list of mailboxes matching ROOT on server in BUFFER.
1239 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1240 root. REFERENCE is a implementation-specific string that has to be
1241 passed to list command."
1242 (with-current-buffer (or buffer (current-buffer))
1243 ;; Make sure we know the hierarchy separator for root's hierarchy
1244 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1245 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1246 (imap-utf7-encode root) "\"")))
1247 ;; clear list data (NB not delimiter and other stuff)
1248 (imap-mailbox-map-1 (lambda (mailbox)
1249 (imap-mailbox-put 'list nil mailbox)))
1251 (imap-send-command-wait
1252 (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1253 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1256 (imap-mailbox-map-1 (lambda (mailbox)
1257 (when (imap-mailbox-get-1 'list mailbox)
1258 (push (imap-utf7-decode mailbox) out))))
1261 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1262 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1263 Returns non-nil if successful."
1264 (with-current-buffer (or buffer (current-buffer))
1265 (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1266 (imap-utf7-encode mailbox)
1269 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1270 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1271 Returns non-nil if successful."
1272 (with-current-buffer (or buffer (current-buffer))
1273 (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1274 (imap-utf7-encode mailbox)
1277 (defun imap-mailbox-status (mailbox items &optional buffer)
1278 "Get status items ITEM in MAILBOX from server in BUFFER.
1279 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1280 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1281 or 'unseen. If ITEMS is a list of symbols, a list of values is
1282 returned, if ITEMS is a symbol only it's value is returned."
1283 (with-current-buffer (or buffer (current-buffer))
1285 (imap-send-command-wait (list "STATUS \""
1286 (imap-utf7-encode mailbox)
1293 (mapcar (lambda (item)
1294 (imap-mailbox-get item mailbox))
1296 (imap-mailbox-get items mailbox)))))
1298 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1299 "Get ACL on mailbox from server in BUFFER."
1300 (let ((mailbox (imap-utf7-encode mailbox)))
1301 (with-current-buffer (or buffer (current-buffer))
1303 (imap-send-command-wait (list "GETACL \""
1304 (or mailbox imap-current-mailbox)
1306 (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1308 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1309 "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
1310 (let ((mailbox (imap-utf7-encode mailbox)))
1311 (with-current-buffer (or buffer (current-buffer))
1313 (imap-send-command-wait (list "SETACL \""
1314 (or mailbox imap-current-mailbox)
1320 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1321 "Removes any <identifier,rights> pair for IDENTIFIER in MAILBOX from server in BUFFER."
1322 (let ((mailbox (imap-utf7-encode mailbox)))
1323 (with-current-buffer (or buffer (current-buffer))
1325 (imap-send-command-wait (list "DELETEACL \""
1326 (or mailbox imap-current-mailbox)
1331 ;; Message functions:
1333 (defun imap-current-message (&optional buffer)
1334 (with-current-buffer (or buffer (current-buffer))
1335 imap-current-message))
1337 (defun imap-list-to-message-set (list)
1338 (mapconcat (lambda (item)
1339 (number-to-string item))
1345 (defun imap-range-to-message-set (range)
1350 (car item) (cdr item))
1351 (format "%d" item)))
1352 (if (and (listp range) (not (listp (cdr range))))
1353 (list range) ;; make (1 . 2) into ((1 . 2))
1357 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1358 (with-current-buffer (or buffer (current-buffer))
1359 (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1361 (imap-list-to-message-set uids)
1365 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1366 "Fetch properties PROPS from message set UIDS from server in BUFFER.
1367 UIDS can be a string, number or a list of numbers. If RECEIVE
1368 is non-nil return theese properties."
1369 (with-current-buffer (or buffer (current-buffer))
1370 (when (imap-ok-p (imap-send-command-wait
1371 (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1373 (imap-list-to-message-set uids)
1376 (if (or (null receive) (stringp uids))
1379 (mapcar (lambda (uid)
1381 (mapcar (lambda (prop)
1382 (imap-message-get uid prop))
1384 (imap-message-get uid receive)))
1386 (imap-message-get uids receive))))))
1388 (defun imap-message-put (uid propname value &optional buffer)
1389 (with-current-buffer (or buffer (current-buffer))
1390 (if imap-message-data
1391 (put (intern (number-to-string uid) imap-message-data)
1393 (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1394 uid propname value (current-buffer)))
1397 (defun imap-message-get (uid propname &optional buffer)
1398 (with-current-buffer (or buffer (current-buffer))
1399 (get (intern-soft (number-to-string uid) imap-message-data)
1402 (defun imap-message-map (func propname &optional buffer)
1403 "Map a function across each mailbox in `imap-message-data', returning a list."
1404 (with-current-buffer (or buffer (current-buffer))
1408 (push (funcall func (get s 'UID) (get s propname)) result))
1412 (defmacro imap-message-envelope-date (uid &optional buffer)
1413 `(with-current-buffer (or ,buffer (current-buffer))
1414 (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1416 (defmacro imap-message-envelope-subject (uid &optional buffer)
1417 `(with-current-buffer (or ,buffer (current-buffer))
1418 (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1420 (defmacro imap-message-envelope-from (uid &optional buffer)
1421 `(with-current-buffer (or ,buffer (current-buffer))
1422 (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1424 (defmacro imap-message-envelope-sender (uid &optional buffer)
1425 `(with-current-buffer (or ,buffer (current-buffer))
1426 (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1428 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1429 `(with-current-buffer (or ,buffer (current-buffer))
1430 (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1432 (defmacro imap-message-envelope-to (uid &optional buffer)
1433 `(with-current-buffer (or ,buffer (current-buffer))
1434 (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1436 (defmacro imap-message-envelope-cc (uid &optional buffer)
1437 `(with-current-buffer (or ,buffer (current-buffer))
1438 (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1440 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1441 `(with-current-buffer (or ,buffer (current-buffer))
1442 (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1444 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1445 `(with-current-buffer (or ,buffer (current-buffer))
1446 (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1448 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1449 `(with-current-buffer (or ,buffer (current-buffer))
1450 (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1452 (defmacro imap-message-body (uid &optional buffer)
1453 `(with-current-buffer (or ,buffer (current-buffer))
1454 (imap-message-get ,uid 'BODY)))
1456 (defun imap-search (predicate &optional buffer)
1457 (with-current-buffer (or buffer (current-buffer))
1458 (imap-mailbox-put 'search 'dummy)
1459 (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1460 (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1462 (message "Missing SEARCH response to a SEARCH command (server not RFC compliant)...")
1464 (imap-mailbox-get-1 'search imap-current-mailbox)))))
1466 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1467 "Return t iff FLAG can be permanently (between IMAP sessions) saved on articles, in MAILBOX on server in BUFFER."
1468 (with-current-buffer (or buffer (current-buffer))
1469 (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1470 (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1472 (defun imap-message-flags-set (articles flags &optional silent buffer)
1473 (when (and articles flags)
1474 (with-current-buffer (or buffer (current-buffer))
1475 (imap-ok-p (imap-send-command-wait
1476 (concat "UID STORE " articles
1477 " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1479 (defun imap-message-flags-del (articles flags &optional silent buffer)
1480 (when (and articles flags)
1481 (with-current-buffer (or buffer (current-buffer))
1482 (imap-ok-p (imap-send-command-wait
1483 (concat "UID STORE " articles
1484 " -FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1486 (defun imap-message-flags-add (articles flags &optional silent buffer)
1487 (when (and articles flags)
1488 (with-current-buffer (or buffer (current-buffer))
1489 (imap-ok-p (imap-send-command-wait
1490 (concat "UID STORE " articles
1491 " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1493 (defun imap-message-copyuid-1 (mailbox)
1494 (if (imap-capability 'UIDPLUS)
1495 (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1496 (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1497 (let ((old-mailbox imap-current-mailbox)
1499 (imap-message-data (make-vector 2 0)))
1500 (when (imap-mailbox-examine-1 mailbox)
1502 (and (imap-fetch "*" "UID")
1503 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1504 (apply 'max (imap-message-map
1505 (lambda (uid prop) uid) 'UID))))
1507 (imap-mailbox-select old-mailbox (eq state 'examine))
1508 (imap-mailbox-unselect)))))))
1510 (defun imap-message-copyuid (mailbox &optional buffer)
1511 (with-current-buffer (or buffer (current-buffer))
1512 (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1514 (defun imap-message-copy (articles mailbox
1515 &optional dont-create no-copyuid buffer)
1516 "Copy ARTICLES (a string message set) to MAILBOX on server in
1517 BUFFER, creating mailbox if it doesn't exist. If dont-create is
1518 non-nil, it will not create a mailbox. On success, return a list with
1519 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1520 first element, rest of list contain the saved articles' UIDs."
1522 (with-current-buffer (or buffer (current-buffer))
1523 (let ((mailbox (imap-utf7-encode mailbox)))
1524 (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1525 (imap-current-target-mailbox mailbox))
1526 (if (imap-ok-p (imap-send-command-wait cmd))
1528 (when (and (not dont-create)
1529 ;; removed because of buggy Oracle server
1530 ;; that doesn't send TRYCREATE tags (which
1531 ;; is a MUST according to specifications):
1532 ;;(imap-mailbox-get-1 'trycreate mailbox)
1533 (imap-mailbox-create-1 mailbox))
1534 (imap-ok-p (imap-send-command-wait cmd)))))
1536 (imap-message-copyuid-1 mailbox)))))))
1538 (defun imap-message-appenduid-1 (mailbox)
1539 (if (imap-capability 'UIDPLUS)
1540 (imap-mailbox-get-1 'appenduid mailbox)
1541 (let ((old-mailbox imap-current-mailbox)
1543 (imap-message-data (make-vector 2 0)))
1544 (when (imap-mailbox-examine-1 mailbox)
1546 (and (imap-fetch "*" "UID")
1547 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1548 (apply 'max (imap-message-map
1549 (lambda (uid prop) uid) 'UID))))
1551 (imap-mailbox-select old-mailbox (eq state 'examine))
1552 (imap-mailbox-unselect)))))))
1554 (defun imap-message-appenduid (mailbox &optional buffer)
1555 (with-current-buffer (or buffer (current-buffer))
1556 (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1558 (defun imap-message-append (mailbox article &optional flags date-time buffer)
1559 "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1560 FLAGS and DATE-TIME is currently not used. Return a cons holding
1561 uidvalidity of MAILBOX and UID the newly created article got, or nil
1563 (let ((mailbox (imap-utf7-encode mailbox)))
1564 (with-current-buffer (or buffer (current-buffer))
1565 (and (let ((imap-current-target-mailbox mailbox))
1567 (imap-send-command-wait
1568 (list "APPEND \"" mailbox "\" " article))))
1569 (imap-message-appenduid-1 mailbox)))))
1571 (defun imap-body-lines (body)
1572 "Return number of lines in article by looking at the mime bodystructure BODY."
1574 (if (stringp (car body))
1575 (cond ((and (string= (upcase (car body)) "TEXT")
1576 (numberp (nth 7 body)))
1578 ((and (string= (upcase (car body)) "MESSAGE")
1579 (numberp (nth 9 body)))
1582 (apply '+ (mapcar 'imap-body-lines body)))
1585 (defun imap-envelope-from (from)
1586 "Return a from string line."
1588 (concat (aref from 0)
1589 (if (aref from 0) " <")
1593 (if (aref from 0) ">"))))
1596 ;; Internal functions.
1598 (defun imap-add-callback (tag func)
1599 (setq imap-callbacks (append (list (cons tag func)) imap-callbacks)))
1601 (defun imap-send-command-1 (cmdstr)
1602 (setq cmdstr (concat cmdstr imap-client-eol))
1604 (with-current-buffer (get-buffer-create imap-log-buffer)
1605 (buffer-disable-undo)
1606 (goto-char (point-max))
1608 (process-send-string imap-process cmdstr))
1610 (defun imap-send-command (command &optional buffer)
1611 (with-current-buffer (or buffer (current-buffer))
1612 (if (not (listp command)) (setq command (list command)))
1613 (let ((tag (setq imap-tag (1+ imap-tag)))
1615 (setq cmdstr (concat (number-to-string imap-tag) " "))
1616 (while (setq cmd (pop command))
1617 (cond ((stringp cmd)
1618 (setq cmdstr (concat cmdstr cmd)))
1620 (let ((eol imap-client-eol)
1621 (calcfirst imap-calculate-literal-size-first)
1623 (with-current-buffer cmd
1625 (setq size (buffer-size)))
1626 (when (not (equal eol "\r\n"))
1627 ;; XXX modifies buffer!
1628 (goto-char (point-min))
1629 (while (search-forward "\r\n" nil t)
1630 (replace-match eol)))
1632 (setq size (buffer-size))))
1634 (concat cmdstr (format "{%d}" size))))
1637 (imap-send-command-1 cmdstr)
1639 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1640 (setq command nil);; abort command if no cont-req
1641 (let ((process imap-process)
1642 (stream imap-stream)
1643 (eol imap-client-eol))
1644 (with-current-buffer cmd
1646 (with-current-buffer (get-buffer-create
1648 (buffer-disable-undo)
1649 (goto-char (point-max))
1650 (insert-buffer-substring cmd)))
1651 (process-send-region process (point-min)
1653 (process-send-string process imap-client-eol))))
1654 (setq imap-continuation nil)))
1656 (imap-send-command-1 cmdstr)
1659 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1660 (setq command nil);; abort command if no cont-req
1661 (setq command (cons (funcall cmd imap-continuation)
1663 (setq imap-continuation nil)))
1665 (error "Unknown command type"))))
1667 (imap-send-command-1 cmdstr))
1670 (defun imap-wait-for-tag (tag &optional buffer)
1671 (with-current-buffer (or buffer (current-buffer))
1672 (let (imap-have-messaged)
1673 (while (and (null imap-continuation)
1674 (memq (process-status imap-process) '(open run))
1675 (< imap-reached-tag tag))
1676 (let ((len (/ (point-max) 1024))
1679 (setq imap-have-messaged t)
1680 (message "imap read: %dk" len))
1681 (accept-process-output imap-process 1)))
1682 (when imap-have-messaged
1684 (and (memq (process-status imap-process) '(open run))
1685 (or (assq tag imap-failed-tags)
1686 (if imap-continuation
1690 (defun imap-sentinel (process string)
1691 (delete-process process))
1693 (defun imap-find-next-line ()
1694 "Return point at end of current line, taking into account literals.
1695 Return nil if no complete line has arrived."
1696 (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
1699 (if (match-string 1)
1700 (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1702 (goto-char (+ (point) (string-to-number (match-string 1))))
1703 (imap-find-next-line))
1706 (defun imap-arrival-filter (proc string)
1707 "IMAP process filter."
1708 (with-current-buffer (process-buffer proc)
1709 (goto-char (point-max))
1712 (with-current-buffer (get-buffer-create imap-log-buffer)
1713 (buffer-disable-undo)
1714 (goto-char (point-max))
1717 (goto-char (point-min))
1718 (while (setq end (imap-find-next-line))
1720 (narrow-to-region (point-min) end)
1721 (delete-backward-char (length imap-server-eol))
1722 (goto-char (point-min))
1724 (cond ((eq imap-state 'initial)
1725 (imap-parse-greeting))
1726 ((or (eq imap-state 'auth)
1727 (eq imap-state 'nonauth)
1728 (eq imap-state 'selected)
1729 (eq imap-state 'examine))
1730 (imap-parse-response))
1732 (message "Unknown state %s in arrival filter"
1734 (delete-region (point-min) (point-max))))))))
1739 (defsubst imap-forward ()
1740 (or (eobp) (forward-char)))
1743 ;; ; Unsigned 32-bit integer
1744 ;; ; (0 <= n < 4,294,967,296)
1746 (defsubst imap-parse-number ()
1747 (when (looking-at "[0-9]+")
1749 (string-to-number (match-string 0))
1750 (goto-char (match-end 0)))))
1752 ;; literal = "{" number "}" CRLF *CHAR8
1753 ;; ; Number represents the number of CHAR8s
1755 (defsubst imap-parse-literal ()
1756 (when (looking-at "{\\([0-9]+\\)}\r\n")
1757 (let ((pos (match-end 0))
1758 (len (string-to-number (match-string 1))))
1759 (if (< (point-max) (+ pos len))
1761 (goto-char (+ pos len))
1762 (buffer-substring pos (+ pos len))))))
1764 ;; string = quoted / literal
1766 ;; quoted = DQUOTE *QUOTED-CHAR DQUOTE
1768 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
1769 ;; "\" quoted-specials
1771 ;; quoted-specials = DQUOTE / "\"
1773 ;; TEXT-CHAR = <any CHAR except CR and LF>
1775 (defsubst imap-parse-string ()
1776 (cond ((eq (char-after) ?\")
1778 (let ((p (point)) (name ""))
1779 (skip-chars-forward "^\"\\\\")
1780 (setq name (buffer-substring p (point)))
1781 (while (eq (char-after) ?\\)
1782 (setq p (1+ (point)))
1784 (skip-chars-forward "^\"\\\\")
1785 (setq name (concat name (buffer-substring p (point)))))
1788 ((eq (char-after) ?{)
1789 (imap-parse-literal))))
1793 (defsubst imap-parse-nil ()
1794 (if (looking-at "NIL")
1795 (goto-char (match-end 0))))
1797 ;; nstring = string / nil
1799 (defsubst imap-parse-nstring ()
1800 (or (imap-parse-string)
1801 (and (imap-parse-nil)
1804 ;; astring = atom / string
1806 ;; atom = 1*ATOM-CHAR
1808 ;; ATOM-CHAR = <any CHAR except atom-specials>
1810 ;; atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards /
1813 ;; list-wildcards = "%" / "*"
1815 ;; quoted-specials = DQUOTE / "\"
1817 (defsubst imap-parse-astring ()
1818 (or (imap-parse-string)
1819 (buffer-substring (point)
1820 (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
1821 (goto-char (1- (match-end 0)))
1825 ;; address = "(" addr-name SP addr-adl SP addr-mailbox SP
1828 ;; addr-adl = nstring
1829 ;; ; Holds route from [RFC-822] route-addr if
1832 ;; addr-host = nstring
1833 ;; ; nil indicates [RFC-822] group syntax.
1834 ;; ; Otherwise, holds [RFC-822] domain name
1836 ;; addr-mailbox = nstring
1837 ;; ; nil indicates end of [RFC-822] group; if
1838 ;; ; non-nil and addr-host is nil, holds
1839 ;; ; [RFC-822] group name.
1840 ;; ; Otherwise, holds [RFC-822] local-part
1841 ;; ; after removing [RFC-822] quoting
1843 ;; addr-name = nstring
1844 ;; ; If non-nil, holds phrase from [RFC-822]
1845 ;; ; mailbox after removing [RFC-822] quoting
1848 (defsubst imap-parse-address ()
1850 (when (eq (char-after) ?\()
1852 (setq address (vector (prog1 (imap-parse-nstring)
1854 (prog1 (imap-parse-nstring)
1856 (prog1 (imap-parse-nstring)
1858 (imap-parse-nstring)))
1859 (when (eq (char-after) ?\))
1863 ;; address-list = "(" 1*address ")" / nil
1867 (defsubst imap-parse-address-list ()
1868 (if (eq (char-after) ?\()
1869 (let (address addresses)
1871 (while (and (not (eq (char-after) ?\)))
1872 ;; next line for MS Exchange bug
1873 (progn (and (eq (char-after) ? ) (imap-forward)) t)
1874 (setq address (imap-parse-address)))
1875 (setq addresses (cons address addresses)))
1876 (when (eq (char-after) ?\))
1878 (nreverse addresses)))
1879 (assert (imap-parse-nil) t "In imap-parse-address-list")))
1881 ;; mailbox = "INBOX" / astring
1882 ;; ; INBOX is case-insensitive. All case variants of
1883 ;; ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
1884 ;; ; not as an astring. An astring which consists of
1885 ;; ; the case-insensitive sequence "I" "N" "B" "O" "X"
1886 ;; ; is considered to be INBOX and not an astring.
1887 ;; ; Refer to section 5.1 for further
1888 ;; ; semantic details of mailbox names.
1890 (defsubst imap-parse-mailbox ()
1891 (let ((mailbox (imap-parse-astring)))
1892 (if (string-equal "INBOX" (upcase mailbox))
1896 ;; greeting = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
1898 ;; resp-cond-auth = ("OK" / "PREAUTH") SP resp-text
1899 ;; ; Authentication condition
1901 ;; resp-cond-bye = "BYE" SP resp-text
1903 (defun imap-parse-greeting ()
1904 "Parse a IMAP greeting."
1905 (cond ((looking-at "\\* OK ")
1906 (setq imap-state 'nonauth))
1907 ((looking-at "\\* PREAUTH ")
1908 (setq imap-state 'auth))
1909 ((looking-at "\\* BYE ")
1910 (setq imap-state 'closed))))
1912 ;; response = *(continue-req / response-data) response-done
1914 ;; continue-req = "+" SP (resp-text / base64) CRLF
1916 ;; response-data = "*" SP (resp-cond-state / resp-cond-bye /
1917 ;; mailbox-data / message-data / capability-data) CRLF
1919 ;; response-done = response-tagged / response-fatal
1921 ;; response-fatal = "*" SP resp-cond-bye CRLF
1922 ;; ; Server closes connection immediately
1924 ;; response-tagged = tag SP resp-cond-state CRLF
1926 ;; resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
1927 ;; ; Status condition
1929 ;; resp-cond-bye = "BYE" SP resp-text
1931 ;; mailbox-data = "FLAGS" SP flag-list /
1932 ;; "LIST" SP mailbox-list /
1933 ;; "LSUB" SP mailbox-list /
1934 ;; "SEARCH" *(SP nz-number) /
1935 ;; "STATUS" SP mailbox SP "("
1936 ;; [status-att SP number *(SP status-att SP number)] ")" /
1937 ;; number SP "EXISTS" /
1938 ;; number SP "RECENT"
1940 ;; message-data = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
1942 ;; capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
1944 ;; ; IMAP4rev1 servers which offer RFC 1730
1945 ;; ; compatibility MUST list "IMAP4" as the first
1948 (defun imap-parse-response ()
1949 "Parse a IMAP command response."
1951 (case (setq token (read (current-buffer)))
1952 (+ (setq imap-continuation
1953 (or (buffer-substring (min (point-max) (1+ (point)))
1956 (* (case (prog1 (setq token (read (current-buffer)))
1958 (OK (imap-parse-resp-text))
1959 (NO (imap-parse-resp-text))
1960 (BAD (imap-parse-resp-text))
1961 (BYE (imap-parse-resp-text))
1962 (FLAGS (imap-mailbox-put 'flags (imap-parse-flag-list)))
1963 (LIST (imap-parse-data-list 'list))
1964 (LSUB (imap-parse-data-list 'lsub))
1965 (SEARCH (imap-mailbox-put
1967 (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
1968 (STATUS (imap-parse-status))
1969 (CAPABILITY (setq imap-capability
1970 (read (concat "(" (upcase (buffer-substring
1971 (point) (point-max)))
1973 (ACL (imap-parse-acl))
1974 (t (case (prog1 (read (current-buffer))
1976 (EXISTS (imap-mailbox-put 'exists token))
1977 (RECENT (imap-mailbox-put 'recent token))
1979 (FETCH (imap-parse-fetch token))
1980 (t (message "Garbage: %s" (buffer-string)))))))
1982 (if (not (integerp token))
1983 (message "Garbage: %s" (buffer-string))
1984 (case (prog1 (setq status (read (current-buffer)))
1987 (setq imap-reached-tag (max imap-reached-tag token))
1988 (imap-parse-resp-text)))
1990 (setq imap-reached-tag (max imap-reached-tag token))
1992 (imap-parse-resp-text))
1994 (when (eq (char-after) ?\[)
1995 (setq code (buffer-substring (point)
1996 (search-forward "]")))
1998 (setq text (buffer-substring (point) (point-max)))
1999 (push (list token status code text)
2000 imap-failed-tags))))
2002 (setq imap-reached-tag (max imap-reached-tag token))
2004 (imap-parse-resp-text))
2006 (when (eq (char-after) ?\[)
2007 (setq code (buffer-substring (point)
2008 (search-forward "]")))
2010 (setq text (buffer-substring (point) (point-max)))
2011 (push (list token status code text) imap-failed-tags)
2012 (error "Internal error, tag %s status %s code %s text %s"
2013 token status code text))))
2014 (t (message "Garbage: %s" (buffer-string))))
2015 (when (assq token imap-callbacks)
2016 (funcall (cdr (assq token imap-callbacks)) token status)
2017 (setq imap-callbacks
2018 (imap-remassoc token imap-callbacks)))))))))
2020 ;; resp-text = ["[" resp-text-code "]" SP] text
2022 ;; text = 1*TEXT-CHAR
2024 ;; TEXT-CHAR = <any CHAR except CR and LF>
2026 (defun imap-parse-resp-text ()
2027 (imap-parse-resp-text-code))
2029 ;; resp-text-code = "ALERT" /
2030 ;; "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
2031 ;; "NEWNAME" SP string SP string /
2033 ;; "PERMANENTFLAGS" SP "("
2034 ;; [flag-perm *(SP flag-perm)] ")" /
2038 ;; "UIDNEXT" SP nz-number /
2039 ;; "UIDVALIDITY" SP nz-number /
2040 ;; "UNSEEN" SP nz-number /
2041 ;; resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
2043 ;; resp_code_apnd = "APPENDUID" SPACE nz_number SPACE uniqueid
2045 ;; resp_code_copy = "COPYUID" SPACE nz_number SPACE set SPACE set
2047 ;; set = sequence-num / (sequence-num ":" sequence-num) /
2049 ;; ; Identifies a set of messages. For message
2050 ;; ; sequence numbers, these are consecutive
2051 ;; ; numbers from 1 to the number of messages in
2053 ;; ; Comma delimits individual numbers, colon
2054 ;; ; delimits between two numbers inclusive.
2055 ;; ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
2056 ;; ; 14,15 for a mailbox with 15 messages.
2058 ;; sequence-num = nz-number / "*"
2059 ;; ; * is the largest number in use. For message
2060 ;; ; sequence numbers, it is the number of messages
2061 ;; ; in the mailbox. For unique identifiers, it is
2062 ;; ; the unique identifier of the last message in
2065 ;; flag-perm = flag / "\*"
2067 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2068 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2069 ;; ; Does not include "\Recent"
2071 ;; flag-extension = "\" atom
2072 ;; ; Future expansion. Client implementations
2073 ;; ; MUST accept flag-extension flags. Server
2074 ;; ; implementations MUST NOT generate
2075 ;; ; flag-extension flags except as defined by
2076 ;; ; future standard or standards-track
2077 ;; ; revisions of this specification.
2079 ;; flag-keyword = atom
2081 ;; resp-text-atom = 1*<any ATOM-CHAR except "]">
2083 (defun imap-parse-resp-text-code ()
2084 ;; xxx next line for stalker communigate pro 3.3.1 bug
2085 (when (looking-at " \\[")
2087 (when (eq (char-after) ?\[)
2089 (cond ((search-forward "PERMANENTFLAGS " nil t)
2090 (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2091 ((search-forward "UIDNEXT " nil t)
2092 (imap-mailbox-put 'uidnext (read (current-buffer))))
2093 ((search-forward "UNSEEN " nil t)
2094 (imap-mailbox-put 'unseen (read (current-buffer))))
2095 ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2096 (imap-mailbox-put 'uidvalidity (match-string 1)))
2097 ((search-forward "READ-ONLY" nil t)
2098 (imap-mailbox-put 'read-only t))
2099 ((search-forward "NEWNAME " nil t)
2100 (let (oldname newname)
2101 (setq oldname (imap-parse-string))
2103 (setq newname (imap-parse-string))
2104 (imap-mailbox-put 'newname newname oldname)))
2105 ((search-forward "TRYCREATE" nil t)
2106 (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2107 ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2108 (imap-mailbox-put 'appenduid
2109 (list (match-string 1)
2110 (string-to-number (match-string 2)))
2111 imap-current-target-mailbox))
2112 ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2113 (imap-mailbox-put 'copyuid (list (match-string 1)
2116 imap-current-target-mailbox))
2117 ((search-forward "ALERT] " nil t)
2118 (message "Imap server %s information: %s" imap-server
2119 (buffer-substring (point) (point-max)))))))
2121 ;; mailbox-list = "(" [mbx-list-flags] ")" SP
2122 ;; (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2124 ;; mbx-list-flags = *(mbx-list-oflag SP) mbx-list-sflag
2125 ;; *(SP mbx-list-oflag) /
2126 ;; mbx-list-oflag *(SP mbx-list-oflag)
2128 ;; mbx-list-oflag = "\Noinferiors" / flag-extension
2129 ;; ; Other flags; multiple possible per LIST response
2131 ;; mbx-list-sflag = "\Noselect" / "\Marked" / "\Unmarked"
2132 ;; ; Selectability flags; only one per LIST response
2134 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2135 ;; "\" quoted-specials
2137 ;; quoted-specials = DQUOTE / "\"
2139 (defun imap-parse-data-list (type)
2140 (let (flags delimiter mailbox)
2141 (setq flags (imap-parse-flag-list))
2142 (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2143 (setq delimiter (match-string 1))
2144 (goto-char (1+ (match-end 0)))
2145 (when (setq mailbox (imap-parse-mailbox))
2146 (imap-mailbox-put type t mailbox)
2147 (imap-mailbox-put 'list-flags flags mailbox)
2148 (imap-mailbox-put 'delimiter delimiter mailbox)))))
2150 ;; msg_att ::= "(" 1#("ENVELOPE" SPACE envelope /
2151 ;; "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2152 ;; "INTERNALDATE" SPACE date_time /
2153 ;; "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2154 ;; "RFC822.SIZE" SPACE number /
2155 ;; "BODY" ["STRUCTURE"] SPACE body /
2156 ;; "BODY" section ["<" number ">"] SPACE nstring /
2157 ;; "UID" SPACE uniqueid) ")"
2159 ;; date_time ::= <"> date_day_fixed "-" date_month "-" date_year
2160 ;; SPACE time SPACE zone <">
2162 ;; section ::= "[" [section_text / (nz_number *["." nz_number]
2163 ;; ["." (section_text / "MIME")])] "]"
2165 ;; section_text ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2166 ;; SPACE header_list / "TEXT"
2168 ;; header_fld_name ::= astring
2170 ;; header_list ::= "(" 1#header_fld_name ")"
2172 (defsubst imap-parse-header-list ()
2173 (when (eq (char-after) ?\()
2175 (while (not (eq (char-after) ?\)))
2177 (push (imap-parse-astring) strlist))
2179 (nreverse strlist))))
2181 (defsubst imap-parse-fetch-body-section ()
2183 (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2184 (if (eq (char-before) ? )
2186 (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2187 (search-forward "]" nil t))
2190 (defun imap-parse-fetch (response)
2191 (when (eq (char-after) ?\()
2192 (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2193 rfc822size body bodydetail bodystructure flags-empty)
2194 (while (not (eq (char-after) ?\)))
2196 (let ((token (read (current-buffer))))
2198 (cond ((eq token 'UID)
2199 (setq uid (condition-case ()
2200 (read (current-buffer))
2203 (setq flags (imap-parse-flag-list))
2205 (setq flags-empty 't)))
2206 ((eq token 'ENVELOPE)
2207 (setq envelope (imap-parse-envelope)))
2208 ((eq token 'INTERNALDATE)
2209 (setq internaldate (imap-parse-string)))
2211 (setq rfc822 (imap-parse-nstring)))
2212 ((eq token 'RFC822.HEADER)
2213 (setq rfc822header (imap-parse-nstring)))
2214 ((eq token 'RFC822.TEXT)
2215 (setq rfc822text (imap-parse-nstring)))
2216 ((eq token 'RFC822.SIZE)
2217 (setq rfc822size (read (current-buffer))))
2219 (if (eq (char-before) ?\[)
2221 (upcase (imap-parse-fetch-body-section))
2222 (and (eq (char-after) ?<)
2223 (buffer-substring (1+ (point))
2224 (search-forward ">" nil t)))
2225 (progn (imap-forward)
2226 (imap-parse-nstring)))
2228 (setq body (imap-parse-body))))
2229 ((eq token 'BODYSTRUCTURE)
2230 (setq bodystructure (imap-parse-body))))))
2232 (setq imap-current-message uid)
2233 (imap-message-put uid 'UID uid)
2234 (and (or flags flags-empty) (imap-message-put uid 'FLAGS flags))
2235 (and envelope (imap-message-put uid 'ENVELOPE envelope))
2236 (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2237 (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2238 (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2239 (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2240 (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2241 (and body (imap-message-put uid 'BODY body))
2242 (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2243 (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2244 (run-hooks 'imap-fetch-data-hook)))))
2246 ;; mailbox-data = ...
2247 ;; "STATUS" SP mailbox SP "("
2248 ;; [status-att SP number
2249 ;; *(SP status-att SP number)] ")"
2252 ;; status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2255 (defun imap-parse-status ()
2256 (let ((mailbox (imap-parse-mailbox)))
2257 (when (and mailbox (search-forward "(" nil t))
2258 (while (not (eq (char-after) ?\)))
2259 (let ((token (read (current-buffer))))
2260 (cond ((eq token 'MESSAGES)
2261 (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2263 (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2264 ((eq token 'UIDNEXT)
2265 (imap-mailbox-put 'uidnext (read (current-buffer)) mailbox))
2266 ((eq token 'UIDVALIDITY)
2267 (and (looking-at " \\([0-9]+\\)")
2268 (imap-mailbox-put 'uidvalidity (match-string 1) mailbox)
2269 (goto-char (match-end 1))))
2271 (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2273 (message "Unknown status data %s in mailbox %s ignored"
2274 token mailbox))))))))
2276 ;; acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2279 ;; identifier ::= astring
2281 ;; rights ::= astring
2283 (defun imap-parse-acl ()
2284 (let ((mailbox (imap-parse-mailbox))
2285 identifier rights acl)
2286 (while (eq (char-after) ?\ )
2288 (setq identifier (imap-parse-astring))
2290 (setq rights (imap-parse-astring))
2291 (setq acl (append acl (list (cons identifier rights)))))
2292 (imap-mailbox-put 'acl acl mailbox)))
2294 ;; flag-list = "(" [flag *(SP flag)] ")"
2296 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2297 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2298 ;; ; Does not include "\Recent"
2300 ;; flag-keyword = atom
2302 ;; flag-extension = "\" atom
2303 ;; ; Future expansion. Client implementations
2304 ;; ; MUST accept flag-extension flags. Server
2305 ;; ; implementations MUST NOT generate
2306 ;; ; flag-extension flags except as defined by
2307 ;; ; future standard or standards-track
2308 ;; ; revisions of this specification.
2310 (defun imap-parse-flag-list ()
2311 (let (flag-list start)
2312 (assert (eq (char-after) ?\() t "In imap-parse-flag-list")
2313 (while (and (not (eq (char-after) ?\)))
2316 ;; next line for Courier IMAP bug.
2317 (skip-chars-forward " ")
2319 (> (skip-chars-forward "^ )" (imap-point-at-eol)) 0))
2320 (push (buffer-substring start (point)) flag-list))
2321 (assert (eq (char-after) ?\)) t "In imap-parse-flag-list")
2323 (nreverse flag-list)))
2325 ;; envelope = "(" env-date SP env-subject SP env-from SP env-sender SP
2326 ;; env-reply-to SP env-to SP env-cc SP env-bcc SP
2327 ;; env-in-reply-to SP env-message-id ")"
2329 ;; env-bcc = "(" 1*address ")" / nil
2331 ;; env-cc = "(" 1*address ")" / nil
2333 ;; env-date = nstring
2335 ;; env-from = "(" 1*address ")" / nil
2337 ;; env-in-reply-to = nstring
2339 ;; env-message-id = nstring
2341 ;; env-reply-to = "(" 1*address ")" / nil
2343 ;; env-sender = "(" 1*address ")" / nil
2345 ;; env-subject = nstring
2347 ;; env-to = "(" 1*address ")" / nil
2349 (defun imap-parse-envelope ()
2350 (when (eq (char-after) ?\()
2352 (vector (prog1 (imap-parse-nstring);; date
2354 (prog1 (imap-parse-nstring);; subject
2356 (prog1 (imap-parse-address-list);; from
2358 (prog1 (imap-parse-address-list);; sender
2360 (prog1 (imap-parse-address-list);; reply-to
2362 (prog1 (imap-parse-address-list);; to
2364 (prog1 (imap-parse-address-list);; cc
2366 (prog1 (imap-parse-address-list);; bcc
2368 (prog1 (imap-parse-nstring);; in-reply-to
2370 (prog1 (imap-parse-nstring);; message-id
2373 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2375 (defsubst imap-parse-string-list ()
2376 (cond ((eq (char-after) ?\();; body-fld-param
2379 (while (setq str (imap-parse-string))
2381 ;; buggy stalker communigate pro 3.0 doesn't print SPC
2382 ;; between body-fld-param's sometimes
2383 (or (eq (char-after) ?\")
2385 (nreverse strlist)))
2389 ;; body-extension = nstring / number /
2390 ;; "(" body-extension *(SP body-extension) ")"
2391 ;; ; Future expansion. Client implementations
2392 ;; ; MUST accept body-extension fields. Server
2393 ;; ; implementations MUST NOT generate
2394 ;; ; body-extension fields except as defined by
2395 ;; ; future standard or standards-track
2396 ;; ; revisions of this specification.
2398 (defun imap-parse-body-extension ()
2399 (if (eq (char-after) ?\()
2402 (push (imap-parse-body-extension) b-e)
2403 (while (eq (char-after) ?\ )
2405 (push (imap-parse-body-extension) b-e))
2406 (assert (eq (char-after) ?\)) t "In imap-parse-body-extension")
2409 (or (imap-parse-number)
2410 (imap-parse-nstring))))
2412 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2413 ;; *(SP body-extension)]]
2414 ;; ; MUST NOT be returned on non-extensible
2417 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2418 ;; *(SP body-extension)]]
2419 ;; ; MUST NOT be returned on non-extensible
2422 (defsubst imap-parse-body-ext ()
2424 (when (eq (char-after) ?\ );; body-fld-dsp
2427 (if (eq (char-after) ?\()
2430 (push (imap-parse-string) dsp)
2432 (push (imap-parse-string-list) dsp)
2434 (assert (imap-parse-nil) t "In imap-parse-body-ext"))
2435 (push (nreverse dsp) ext))
2436 (when (eq (char-after) ?\ );; body-fld-lang
2438 (if (eq (char-after) ?\()
2439 (push (imap-parse-string-list) ext)
2440 (push (imap-parse-nstring) ext))
2441 (while (eq (char-after) ?\ );; body-extension
2443 (setq ext (append (imap-parse-body-extension) ext)))))
2446 ;; body = "(" body-type-1part / body-type-mpart ")"
2448 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2449 ;; *(SP body-extension)]]
2450 ;; ; MUST NOT be returned on non-extensible
2453 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2454 ;; *(SP body-extension)]]
2455 ;; ; MUST NOT be returned on non-extensible
2458 ;; body-fields = body-fld-param SP body-fld-id SP body-fld-desc SP
2459 ;; body-fld-enc SP body-fld-octets
2461 ;; body-fld-desc = nstring
2463 ;; body-fld-dsp = "(" string SP body-fld-param ")" / nil
2465 ;; body-fld-enc = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2466 ;; "QUOTED-PRINTABLE") DQUOTE) / string
2468 ;; body-fld-id = nstring
2470 ;; body-fld-lang = nstring / "(" string *(SP string) ")"
2472 ;; body-fld-lines = number
2474 ;; body-fld-md5 = nstring
2476 ;; body-fld-octets = number
2478 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2480 ;; body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2481 ;; [SP body-ext-1part]
2483 ;; body-type-basic = media-basic SP body-fields
2484 ;; ; MESSAGE subtype MUST NOT be "RFC822"
2486 ;; body-type-msg = media-message SP body-fields SP envelope
2487 ;; SP body SP body-fld-lines
2489 ;; body-type-text = media-text SP body-fields SP body-fld-lines
2491 ;; body-type-mpart = 1*body SP media-subtype
2492 ;; [SP body-ext-mpart]
2494 ;; media-basic = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2495 ;; "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2496 ;; ; Defined in [MIME-IMT]
2498 ;; media-message = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2499 ;; ; Defined in [MIME-IMT]
2501 ;; media-subtype = string
2502 ;; ; Defined in [MIME-IMT]
2504 ;; media-text = DQUOTE "TEXT" DQUOTE SP media-subtype
2505 ;; ; Defined in [MIME-IMT]
2507 (defun imap-parse-body ()
2509 (when (eq (char-after) ?\()
2511 (if (eq (char-after) ?\()
2513 (while (and (eq (char-after) ?\()
2514 (setq subbody (imap-parse-body)))
2515 ;; buggy stalker communigate pro 3.0 insert a SPC between
2516 ;; parts in multiparts
2517 (when (and (eq (char-after) ?\ )
2518 (eq (char-after (1+ (point))) ?\())
2520 (push subbody body))
2522 (push (imap-parse-string) body);; media-subtype
2523 (when (eq (char-after) ?\ );; body-ext-mpart:
2525 (if (eq (char-after) ?\();; body-fld-param
2526 (push (imap-parse-string-list) body)
2527 (push (and (imap-parse-nil) nil) body))
2529 (append (imap-parse-body-ext) body)));; body-ext-...
2530 (assert (eq (char-after) ?\)) t "In imap-parse-body")
2534 (push (imap-parse-string) body);; media-type
2536 (push (imap-parse-string) body);; media-subtype
2538 ;; next line for Sun SIMS bug
2539 (and (eq (char-after) ? ) (imap-forward))
2540 (if (eq (char-after) ?\();; body-fld-param
2541 (push (imap-parse-string-list) body)
2542 (push (and (imap-parse-nil) nil) body))
2544 (push (imap-parse-nstring) body);; body-fld-id
2546 (push (imap-parse-nstring) body);; body-fld-desc
2548 ;; next `or' for Sun SIMS bug, it regard body-fld-enc as a
2549 ;; nstring and return nil instead of defaulting back to 7BIT
2550 ;; as the standard says.
2551 (push (or (imap-parse-nstring) "7BIT") body);; body-fld-enc
2553 (push (imap-parse-number) body);; body-fld-octets
2555 ;; ok, we're done parsing the required parts, what comes now is one
2558 ;; envelope (then we're parsing body-type-msg)
2559 ;; body-fld-lines (then we're parsing body-type-text)
2560 ;; body-ext-1part (then we're parsing body-type-basic)
2562 ;; the problem is that the two first are in turn optionally followed
2563 ;; by the third. So we parse the first two here (if there are any)...
2565 (when (eq (char-after) ?\ )
2568 (cond ((eq (char-after) ?\();; body-type-msg:
2569 (push (imap-parse-envelope) body);; envelope
2571 (push (imap-parse-body) body);; body
2572 ;; buggy stalker communigate pro 3.0 doesn't print
2573 ;; number of lines in message/rfc822 attachment
2574 (if (eq (char-after) ?\))
2577 (push (imap-parse-number) body))) ;; body-fld-lines
2578 ((setq lines (imap-parse-number)) ;; body-type-text:
2579 (push lines body)) ;; body-fld-lines
2581 (backward-char))))) ;; no match...
2583 ;; ...and then parse the third one here...
2585 (when (eq (char-after) ?\ );; body-ext-1part:
2587 (push (imap-parse-nstring) body);; body-fld-md5
2588 (setq body (append (imap-parse-body-ext) body)));; body-ext-1part..
2590 (assert (eq (char-after) ?\)) t "In imap-parse-body 2")
2594 (when imap-debug ; (untrace-all)
2596 (buffer-disable-undo (get-buffer-create imap-debug-buffer))
2597 (mapcar (lambda (f) (trace-function-background f imap-debug-buffer))
2609 imap-interactive-login
2625 imap-send-command-wait
2630 imap-current-mailbox
2631 imap-current-mailbox-p-1
2632 imap-current-mailbox-p
2633 imap-mailbox-select-1
2635 imap-mailbox-examine-1
2636 imap-mailbox-examine
2637 imap-mailbox-unselect
2638 imap-mailbox-expunge
2640 imap-mailbox-create-1
2646 imap-mailbox-subscribe
2647 imap-mailbox-unsubscribe
2649 imap-mailbox-acl-get
2650 imap-mailbox-acl-set
2651 imap-mailbox-acl-delete
2652 imap-current-message
2653 imap-list-to-message-set
2660 imap-message-flag-permanent-p
2661 imap-message-flags-set
2662 imap-message-flags-del
2663 imap-message-flags-add
2664 imap-message-copyuid-1
2665 imap-message-copyuid
2667 imap-message-appenduid-1
2668 imap-message-appenduid
2680 imap-parse-resp-text
2681 imap-parse-resp-text-code
2682 imap-parse-data-list
2686 imap-parse-flag-list
2688 imap-parse-body-extension
2694 ;;; imap.el ends here