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))
141 (autoload 'base64-decode-string "base64")
142 (autoload 'base64-encode-string "base64")
143 (autoload 'starttls-open-stream "starttls")
144 (autoload 'starttls-negotiate "starttls")
145 (autoload 'digest-md5-parse-digest-challenge "digest-md5")
146 (autoload 'digest-md5-digest-response "digest-md5")
147 (autoload 'digest-md5-digest-uri "digest-md5")
148 (autoload 'digest-md5-challenge "digest-md5")
149 (autoload 'rfc2104-hash "rfc2104")
150 (autoload 'md5 "md5")
151 (autoload 'utf7-encode "utf7")
152 (autoload 'utf7-decode "utf7")
153 (autoload 'format-spec "format-spec")
154 (autoload 'format-spec-make "format-spec")
155 ;; Avoid use gnus-point-at-eol so we're independent of Gnus. These
156 ;; days we have point-at-eol anyhow.
157 (if (fboundp 'point-at-eol)
158 (defalias 'imap-point-at-eol 'point-at-eol)
159 (defun imap-point-at-eol ()
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-coding-system-for-read 'binary)
304 (defconst imap-coding-system-for-write 'binary)
305 (defconst imap-local-variables '(imap-server
314 imap-current-target-mailbox
323 imap-calculate-literal-size-first
325 (defconst imap-log-buffer "*imap-log*")
326 (defconst imap-debug-buffer "*imap-debug*")
328 ;; Internal variables.
330 (defvar imap-stream nil)
331 (defvar imap-auth nil)
332 (defvar imap-server nil)
333 (defvar imap-port nil)
334 (defvar imap-username nil)
335 (defvar imap-password nil)
336 (defvar imap-calculate-literal-size-first nil)
337 (defvar imap-state 'closed
339 Valid states are `closed', `initial', `nonauth', `auth', `selected'
342 (defvar imap-server-eol "\r\n"
343 "The EOL string sent from the server.")
345 (defvar imap-client-eol "\r\n"
346 "The EOL string we send to the server.")
348 (defvar imap-current-mailbox nil
349 "Current mailbox name.")
351 (defvar imap-current-target-mailbox nil
352 "Current target mailbox for COPY and APPEND commands.")
354 (defvar imap-mailbox-data nil
355 "Obarray with mailbox data.")
357 (defvar imap-mailbox-prime 997
358 "Length of imap-mailbox-data.")
360 (defvar imap-current-message nil
361 "Current message number.")
363 (defvar imap-message-data nil
364 "Obarray with message data.")
366 (defvar imap-message-prime 997
367 "Length of imap-message-data.")
369 (defvar imap-capability nil
370 "Capability for server.")
372 (defvar imap-namespace nil
373 "Namespace for current server.")
375 (defvar imap-reached-tag 0
376 "Lower limit on command tags that have been parsed.")
378 (defvar imap-failed-tags nil
379 "Alist of tags that failed.
380 Each element is a list with four elements; tag (a integer), response
381 state (a symbol, `OK', `NO' or `BAD'), response code (a string), and
382 human readable response text (a string).")
385 "Command tag number.")
387 (defvar imap-process nil
390 (defvar imap-continuation nil
391 "Non-nil indicates that the server emitted a continuation request.
392 The actual value is really the text on the continuation line.")
394 (defvar imap-callbacks nil
395 "List of response tags and callbacks, on the form `(number . function)'.
396 The function should take two arguments, the first the IMAP tag and the
397 second the status (OK, NO, BAD etc) of the command.")
400 ;; Utility functions:
402 (defun imap-remassoc (key alist)
403 "Delete by side effect any elements of LIST whose car is `equal' to KEY.
404 The modified LIST is returned. If the first member
405 of LIST has a car that is `equal' to KEY, there is no way to remove it
406 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
407 sure of changing the value of `foo'."
409 (if (equal key (caar alist))
411 (setcdr alist (imap-remassoc key (cdr alist)))
414 (defsubst imap-disable-multibyte ()
415 "Enable multibyte in the current buffer."
416 (when (fboundp 'set-buffer-multibyte)
417 (set-buffer-multibyte nil)))
419 (defsubst imap-utf7-encode (string)
423 (utf7-encode string t)
425 "imap: Could not UTF7 encode `%s', using it unencoded..."
430 (defsubst imap-utf7-decode (string)
434 (utf7-decode string t)
436 "imap: Could not UTF7 decode `%s', using it undecoded..."
441 (defsubst imap-ok-p (status)
444 (setq imap-error status)
447 (defun imap-error-text (&optional buffer)
448 (with-current-buffer (or buffer (current-buffer))
449 (nth 3 (car imap-failed-tags))))
452 ;; Server functions; stream stuff:
454 (defun imap-kerberos4-stream-p (buffer)
455 (imap-capability 'AUTH=KERBEROS_V4 buffer))
457 (defun imap-kerberos4-open (name buffer server port)
458 (let ((cmds imap-kerberos4-program)
460 (while (and (not done) (setq cmd (pop cmds)))
461 (message "Opening Kerberos 4 IMAP connection with `%s'..." cmd)
463 (let* ((port (or port imap-default-port))
464 (coding-system-for-read imap-coding-system-for-read)
465 (coding-system-for-write imap-coding-system-for-write)
466 (process-connection-type imap-process-connection-type)
467 (process (start-process
468 name buffer shell-file-name shell-command-switch
473 ?p (number-to-string port)
474 ?l imap-default-user))))
477 (with-current-buffer buffer
478 (setq imap-client-eol "\n"
479 imap-calculate-literal-size-first t)
480 (while (and (memq (process-status process) '(open run))
481 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
482 (goto-char (point-min))
483 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
484 (or (while (looking-at "^C:")
487 ;; cyrus 1.6 imtest print "S: " before server greeting
488 (or (not (looking-at "S: "))
491 (not (and (imap-parse-greeting)
492 ;; success in imtest < 1.6:
493 (or (re-search-forward
494 "^__\\(.*\\)__\n" nil t)
495 ;; success in imtest 1.6:
497 "^\\(Authenticat.*\\)" nil t))
498 (setq response (match-string 1)))))
499 (accept-process-output process 1)
502 (with-current-buffer (get-buffer-create imap-log-buffer)
503 (imap-disable-multibyte)
504 (buffer-disable-undo)
505 (goto-char (point-max))
506 (insert-buffer-substring buffer)))
508 (message "Opening Kerberos 4 IMAP connection with `%s'...%s" cmd
509 (if response (concat "done, " response) "failed"))
510 (if (and response (let ((case-fold-search nil))
511 (not (string-match "failed" response))))
513 (if (memq (process-status process) '(open run))
514 (imap-send-command "LOGOUT"))
515 (delete-process process)
519 (defun imap-gssapi-stream-p (buffer)
520 (imap-capability 'AUTH=GSSAPI buffer))
522 (defun imap-gssapi-open (name buffer server port)
523 (let ((cmds imap-gssapi-program)
525 (while (and (not done) (setq cmd (pop cmds)))
526 (message "Opening GSSAPI IMAP connection with `%s'..." cmd)
527 (let* ((port (or port imap-default-port))
528 (coding-system-for-read imap-coding-system-for-read)
529 (coding-system-for-write imap-coding-system-for-write)
530 (process-connection-type imap-process-connection-type)
531 (process (start-process
532 name buffer shell-file-name shell-command-switch
537 ?p (number-to-string port)
538 ?l imap-default-user))))
541 (with-current-buffer buffer
542 (setq imap-client-eol "\n"
543 imap-calculate-literal-size-first t)
544 (while (and (memq (process-status process) '(open run))
545 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
546 (goto-char (point-min))
547 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
548 (or (while (looking-at "^C:")
551 ;; cyrus 1.6 imtest print "S: " before server greeting
552 (or (not (looking-at "S: "))
555 (not (and (imap-parse-greeting)
556 ;; success in imtest 1.6:
558 "^\\(Authenticat.*\\)" nil t)
559 (setq response (match-string 1)))))
560 (accept-process-output process 1)
563 (with-current-buffer (get-buffer-create imap-log-buffer)
564 (imap-disable-multibyte)
565 (buffer-disable-undo)
566 (goto-char (point-max))
567 (insert-buffer-substring buffer)))
569 (message "GSSAPI IMAP connection: %s" (or response "failed"))
570 (if (and response (let ((case-fold-search nil))
571 (not (string-match "failed" response))))
573 (if (memq (process-status process) '(open run))
574 (imap-send-command "LOGOUT"))
575 (delete-process process)
579 (defun imap-ssl-p (buffer)
582 (defun imap-ssl-open (name buffer server port)
583 "Open a SSL connection to server."
584 (let ((cmds (if (listp imap-ssl-program) imap-ssl-program
585 (list imap-ssl-program)))
587 (while (and (not done) (setq cmd (pop cmds)))
588 (message "imap: Opening SSL connection with `%s'..." cmd)
589 (let* ((port (or port imap-default-ssl-port))
590 (coding-system-for-read imap-coding-system-for-read)
591 (coding-system-for-write imap-coding-system-for-write)
592 (process-connection-type nil)
595 (setq process (start-process
596 name buffer shell-file-name
601 ?p (number-to-string port)))))
602 (process-kill-without-query process)
604 (with-current-buffer buffer
605 (goto-char (point-min))
606 (while (and (memq (process-status process) '(open run))
607 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
608 (goto-char (point-max))
610 (not (imap-parse-greeting)))
611 (accept-process-output process 1)
614 (with-current-buffer (get-buffer-create imap-log-buffer)
615 (imap-disable-multibyte)
616 (buffer-disable-undo)
617 (goto-char (point-max))
618 (insert-buffer-substring buffer)))
620 (when (memq (process-status process) '(open run))
621 (setq done process))))))
624 (message "imap: Opening SSL connection with `%s'...done" cmd)
626 (message "imap: Opening SSL connection with `%s'...failed" cmd)
629 (defun imap-network-p (buffer)
632 (defun imap-network-open (name buffer server port)
633 (let* ((port (or port imap-default-port))
634 (coding-system-for-read imap-coding-system-for-read)
635 (coding-system-for-write imap-coding-system-for-write)
636 (process (open-network-stream name buffer server port)))
638 (while (and (memq (process-status process) '(open run))
639 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
640 (goto-char (point-min))
641 (not (imap-parse-greeting)))
642 (accept-process-output process 1)
645 (with-current-buffer (get-buffer-create imap-log-buffer)
646 (imap-disable-multibyte)
647 (buffer-disable-undo)
648 (goto-char (point-max))
649 (insert-buffer-substring buffer)))
650 (when (memq (process-status process) '(open run))
653 (defun imap-shell-p (buffer)
656 (defun imap-shell-open (name buffer server port)
657 (let ((cmds (if (listp imap-shell-program) imap-shell-program
658 (list imap-shell-program)))
660 (while (and (not done) (setq cmd (pop cmds)))
661 (message "imap: Opening IMAP connection with `%s'..." cmd)
662 (setq imap-client-eol "\n")
663 (let* ((port (or port imap-default-port))
664 (coding-system-for-read imap-coding-system-for-read)
665 (coding-system-for-write imap-coding-system-for-write)
666 (process (start-process
667 name buffer shell-file-name shell-command-switch
673 ?p (number-to-string port)
674 ?l imap-default-user)))))
676 (while (and (memq (process-status process) '(open run))
677 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
678 (goto-char (point-max))
680 (not (imap-parse-greeting)))
681 (accept-process-output process 1)
684 (with-current-buffer (get-buffer-create imap-log-buffer)
685 (imap-disable-multibyte)
686 (buffer-disable-undo)
687 (goto-char (point-max))
688 (insert-buffer-substring buffer)))
690 (when (memq (process-status process) '(open run))
691 (setq done process)))))
694 (message "imap: Opening IMAP connection with `%s'...done" cmd)
696 (message "imap: Opening IMAP connection with `%s'...failed" cmd)
699 (defun imap-starttls-p (buffer)
700 (imap-capability 'STARTTLS buffer))
702 (defun imap-starttls-open (name buffer server port)
703 (let* ((port (or port imap-default-port))
704 (coding-system-for-read imap-coding-system-for-read)
705 (coding-system-for-write imap-coding-system-for-write)
706 (process (starttls-open-stream name buffer server port))
708 (message "imap: Connecting with STARTTLS...")
710 (while (and (memq (process-status process) '(open run))
711 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
712 (goto-char (point-min))
713 (not (imap-parse-greeting)))
714 (accept-process-output process 1)
717 (with-current-buffer (get-buffer-create imap-log-buffer)
718 (buffer-disable-undo)
719 (goto-char (point-max))
720 (insert-buffer-substring buffer)))
721 (let ((imap-process process))
724 (set-process-filter imap-process 'imap-arrival-filter)
725 (when (and (eq imap-stream 'starttls)
726 (imap-ok-p (imap-send-command-wait "STARTTLS")))
727 (starttls-negotiate imap-process)))
728 (set-process-filter imap-process nil)))
729 (when (memq (process-status process) '(open run))
730 (setq done process)))
733 (message "imap: Connecting with STARTTLS...done")
735 (message "imap: Connecting with STARTTLS...failed")
738 ;; Server functions; authenticator stuff:
740 (defun imap-interactive-login (buffer loginfunc)
741 "Login to server in BUFFER.
742 LOGINFUNC is passed a username and a password, it should return t if
743 it where successful authenticating itself to the server, nil otherwise.
744 Returns t if login was successful, nil otherwise."
745 (with-current-buffer buffer
746 (make-local-variable 'imap-username)
747 (make-local-variable 'imap-password)
748 (let (user passwd ret)
749 ;; (condition-case ()
750 (while (or (not user) (not passwd))
751 (setq user (or imap-username
752 (read-from-minibuffer
753 (concat "IMAP username for " imap-server
754 " (using stream `" (symbol-name imap-stream)
756 (or user imap-default-user))))
757 (setq passwd (or imap-password
759 (concat "IMAP password for " user "@"
760 imap-server " (using authenticator `"
761 (symbol-name imap-auth) "'): "))))
762 (when (and user passwd)
763 (if (funcall loginfunc user passwd)
767 (if (and (not imap-password)
768 (y-or-n-p "Store password for this session? "))
769 (setq imap-password passwd)))
770 (message "Login failed...")
773 ;; (quit (with-current-buffer buffer
776 ;; (error (with-current-buffer buffer
781 (defun imap-gssapi-auth-p (buffer)
782 (and (imap-capability 'AUTH=GSSAPI buffer)
783 (eq imap-stream 'gssapi)))
785 (defun imap-gssapi-auth (buffer)
786 (message "imap: Authenticating using GSSAPI...%s"
787 (if (eq imap-stream 'gssapi) "done" "failed"))
788 (eq imap-stream 'gssapi))
790 (defun imap-kerberos4-auth-p (buffer)
791 (and (imap-capability 'AUTH=KERBEROS_V4 buffer)
792 (eq imap-stream 'kerberos4)))
794 (defun imap-kerberos4-auth (buffer)
795 (message "imap: Authenticating using Kerberos 4...%s"
796 (if (eq imap-stream 'kerberos4) "done" "failed"))
797 (eq imap-stream 'kerberos4))
799 (defun imap-cram-md5-p (buffer)
800 (imap-capability 'AUTH=CRAM-MD5 buffer))
802 (defun imap-cram-md5-auth (buffer)
803 "Login to server using the AUTH CRAM-MD5 method."
804 (message "imap: Authenticating using CRAM-MD5...")
805 (let ((done (imap-interactive-login
807 (lambda (user passwd)
809 (imap-send-command-wait
811 "AUTHENTICATE CRAM-MD5"
813 (let* ((decoded (base64-decode-string challenge))
814 (hash (rfc2104-hash 'md5 64 16 passwd decoded))
815 (response (concat user " " hash))
816 (encoded (base64-encode-string response)))
819 (message "imap: Authenticating using CRAM-MD5...done")
820 (message "imap: Authenticating using CRAM-MD5...failed"))))
822 (defun imap-login-p (buffer)
823 (and (not (imap-capability 'LOGINDISABLED buffer))
824 (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
826 (defun imap-login-auth (buffer)
827 "Login to server using the LOGIN command."
828 (message "imap: Plaintext authentication...")
829 (imap-interactive-login buffer
830 (lambda (user passwd)
831 (imap-ok-p (imap-send-command-wait
832 (concat "LOGIN \"" user "\" \""
835 (defun imap-anonymous-p (buffer)
838 (defun imap-anonymous-auth (buffer)
839 (message "imap: Logging in anonymously...")
840 (with-current-buffer buffer
841 (imap-ok-p (imap-send-command-wait
842 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
843 (system-name)) "\"")))))
845 (defun imap-digest-md5-p (buffer)
846 (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
848 (require 'digest-md5)
851 (defun imap-digest-md5-auth (buffer)
852 "Login to server using the AUTH DIGEST-MD5 method."
853 (message "imap: Authenticating using DIGEST-MD5...")
854 (imap-interactive-login
856 (lambda (user passwd)
860 "AUTHENTICATE DIGEST-MD5"
862 (digest-md5-parse-digest-challenge
863 (base64-decode-string challenge))
865 (digest-md5-digest-uri
866 "imap" (digest-md5-challenge 'realm)))
868 (digest-md5-digest-response
869 user passwd digest-uri)))
870 (base64-encode-string response 'no-line-break))))
872 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
874 (setq imap-continuation nil)
875 (imap-send-command-1 "")
876 (imap-ok-p (imap-wait-for-tag tag)))))))
880 (defun imap-open-1 (buffer)
881 (with-current-buffer buffer
883 (setq imap-current-mailbox nil
884 imap-current-message nil
886 imap-process (condition-case ()
887 (funcall (nth 2 (assq imap-stream
889 "imap" buffer imap-server imap-port)
892 (set-process-filter imap-process 'imap-arrival-filter)
893 (set-process-sentinel imap-process 'imap-sentinel)
894 (while (and (eq imap-state 'initial)
895 (memq (process-status imap-process) '(open run)))
896 (message "Waiting for response from %s..." imap-server)
897 (accept-process-output imap-process 1))
898 (message "Waiting for response from %s...done" imap-server)
899 (and (memq (process-status imap-process) '(open run))
902 (defun imap-open (server &optional port stream auth buffer)
903 "Open a IMAP connection to host SERVER at PORT returning a buffer.
904 If PORT is unspecified, a default value is used (143 except
905 for SSL which use 993).
906 STREAM indicates the stream to use, see `imap-streams' for available
907 streams. If nil, it choices the best stream the server is capable of.
908 AUTH indicates authenticator to use, see `imap-authenticators' for
909 available authenticators. If nil, it choices the best stream the
910 server is capable of.
911 BUFFER can be a buffer or a name of a buffer, which is created if
912 necessary. If nil, the buffer name is generated."
913 (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
914 (with-current-buffer (get-buffer-create buffer)
915 (if (imap-opened buffer)
917 (mapcar 'make-local-variable imap-local-variables)
918 (imap-disable-multibyte)
919 (buffer-disable-undo)
920 (setq imap-server (or server imap-server))
921 (setq imap-port (or port imap-port))
922 (setq imap-auth (or auth imap-auth))
923 (setq imap-stream (or stream imap-stream))
924 (message "imap: Connecting to %s..." imap-server)
925 (if (null (let ((imap-stream (or imap-stream imap-default-stream)))
926 (imap-open-1 buffer)))
928 (message "imap: Connecting to %s...failed" imap-server)
930 (when (null imap-stream)
931 ;; Need to choose stream.
932 (let ((streams imap-streams))
933 (while (setq stream (pop streams))
934 ;; OK to use this stream?
935 (when (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
937 (if (not (eq imap-default-stream stream))
938 (with-current-buffer (get-buffer-create
939 (generate-new-buffer-name " *temp*"))
940 (mapcar 'make-local-variable imap-local-variables)
941 (imap-disable-multibyte)
942 (buffer-disable-undo)
943 (setq imap-server (or server imap-server))
944 (setq imap-port (or port imap-port))
945 (setq imap-auth (or auth imap-auth))
946 (message "imap: Reconnecting with stream `%s'..." stream)
947 (if (null (let ((imap-stream stream))
948 (imap-open-1 (current-buffer))))
950 (kill-buffer (current-buffer))
952 "imap: Reconnecting with stream `%s'...failed"
954 ;; We're done, kill the first connection
957 (rename-buffer buffer)
958 (message "imap: Reconnecting with stream `%s'...done"
960 (setq imap-stream stream)
961 (setq imap-capability nil)
964 (message "imap: Connecting to %s...done" imap-server)
965 (setq imap-stream stream)
966 (setq imap-capability nil)
967 (setq streams nil))))))
968 (when (imap-opened buffer)
969 (setq imap-mailbox-data (make-vector imap-mailbox-prime 0)))
973 (defun imap-opened (&optional buffer)
974 "Return non-nil if connection to imap server in BUFFER is open.
975 If BUFFER is nil then the current buffer is used."
976 (and (setq buffer (get-buffer (or buffer (current-buffer))))
977 (buffer-live-p buffer)
978 (with-current-buffer buffer
980 (memq (process-status imap-process) '(open run))))))
982 (defun imap-authenticate (&optional user passwd buffer)
983 "Authenticate to server in BUFFER, using current buffer if nil.
984 It uses the authenticator specified when opening the server. If the
985 authenticator requires username/passwords, they are queried from the
986 user and optionally stored in the buffer. If USER and/or PASSWD is
987 specified, the user will not be questioned and the username and/or
988 password is remembered in the buffer."
989 (with-current-buffer (or buffer (current-buffer))
990 (if (not (eq imap-state 'nonauth))
991 (or (eq imap-state 'auth)
992 (eq imap-state 'select)
993 (eq imap-state 'examine))
994 (make-local-variable 'imap-username)
995 (make-local-variable 'imap-password)
996 (if user (setq imap-username user))
997 (if passwd (setq imap-password passwd))
999 (and (funcall (nth 2 (assq imap-auth
1000 imap-authenticator-alist)) buffer)
1001 (setq imap-state 'auth))
1002 ;; Choose authenticator.
1003 (let ((auths imap-authenticators)
1005 (while (setq auth (pop auths))
1006 ;; OK to use authenticator?
1007 (when (funcall (nth 1 (assq auth imap-authenticator-alist)) buffer)
1008 (message "imap: Authenticating to `%s' using `%s'..."
1010 (setq imap-auth auth)
1011 (if (funcall (nth 2 (assq auth imap-authenticator-alist)) buffer)
1013 (message "imap: Authenticating to `%s' using `%s'...done"
1016 (message "imap: Authenticating to `%s' using `%s'...failed"
1017 imap-server auth)))))
1020 (defun imap-close (&optional buffer)
1021 "Close connection to server in BUFFER.
1022 If BUFFER is nil, the current buffer is used."
1023 (with-current-buffer (or buffer (current-buffer))
1026 (imap-send-command-wait "LOGOUT")
1028 (when (and imap-process
1029 (memq (process-status imap-process) '(open run)))
1030 (delete-process imap-process))
1031 (setq imap-current-mailbox nil
1032 imap-current-message nil
1037 (defun imap-capability (&optional identifier buffer)
1038 "Return a list of identifiers which server in BUFFER support.
1039 If IDENTIFIER, return non-nil if it's among the servers capabilities.
1040 If BUFFER is nil, the current buffer is assumed."
1041 (with-current-buffer (or buffer (current-buffer))
1042 (unless imap-capability
1043 (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
1044 (setq imap-capability '(IMAP2))))
1046 (memq (intern (upcase (symbol-name identifier))) imap-capability)
1049 (defun imap-namespace (&optional buffer)
1050 "Return a namespace hierarchy at server in BUFFER.
1051 If BUFFER is nil, the current buffer is assumed."
1052 (with-current-buffer (or buffer (current-buffer))
1053 (unless imap-namespace
1054 (when (imap-capability 'NAMESPACE)
1055 (imap-send-command-wait "NAMESPACE")))
1058 (defun imap-send-command-wait (command &optional buffer)
1059 (imap-wait-for-tag (imap-send-command command buffer) buffer))
1062 ;; Mailbox functions:
1064 (defun imap-mailbox-put (propname value &optional mailbox buffer)
1065 (with-current-buffer (or buffer (current-buffer))
1066 (if imap-mailbox-data
1067 (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
1069 (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
1070 propname value mailbox (current-buffer)))
1073 (defsubst imap-mailbox-get-1 (propname &optional mailbox)
1074 (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
1077 (defun imap-mailbox-get (propname &optional mailbox buffer)
1078 (let ((mailbox (imap-utf7-encode mailbox)))
1079 (with-current-buffer (or buffer (current-buffer))
1080 (imap-mailbox-get-1 propname (or mailbox imap-current-mailbox)))))
1082 (defun imap-mailbox-map-1 (func &optional mailbox-decoder buffer)
1083 (with-current-buffer (or buffer (current-buffer))
1087 (push (funcall func (if mailbox-decoder
1088 (funcall mailbox-decoder (symbol-name s))
1089 (symbol-name s))) result))
1093 (defun imap-mailbox-map (func &optional buffer)
1094 "Map a function across each mailbox in `imap-mailbox-data', returning a list.
1095 Function should take a mailbox name (a string) as
1097 (imap-mailbox-map-1 func 'imap-utf7-decode buffer))
1099 (defun imap-current-mailbox (&optional buffer)
1100 (with-current-buffer (or buffer (current-buffer))
1101 (imap-utf7-decode imap-current-mailbox)))
1103 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
1104 (and (string= mailbox imap-current-mailbox)
1106 (eq imap-state 'examine))
1108 (eq imap-state 'selected)))))
1110 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
1111 (with-current-buffer (or buffer (current-buffer))
1112 (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
1114 (defun imap-mailbox-select-1 (mailbox &optional examine)
1115 "Select MAILBOX on server in BUFFER.
1116 If EXAMINE is non-nil, do a read-only select."
1117 (if (imap-current-mailbox-p-1 mailbox examine)
1118 imap-current-mailbox
1119 (setq imap-current-mailbox mailbox)
1120 (if (imap-ok-p (imap-send-command-wait
1121 (concat (if examine "EXAMINE" "SELECT") " \""
1124 (setq imap-message-data (make-vector imap-message-prime 0)
1125 imap-state (if examine 'examine 'selected))
1126 imap-current-mailbox)
1127 ;; Failed SELECT/EXAMINE unselects current mailbox
1128 (setq imap-current-mailbox nil))))
1130 (defun imap-mailbox-select (mailbox &optional examine buffer)
1131 (with-current-buffer (or buffer (current-buffer))
1133 (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
1135 (defun imap-mailbox-examine-1 (mailbox &optional buffer)
1136 (with-current-buffer (or buffer (current-buffer))
1137 (imap-mailbox-select-1 mailbox 'examine)))
1139 (defun imap-mailbox-examine (mailbox &optional buffer)
1140 "Examine MAILBOX on server in BUFFER."
1141 (imap-mailbox-select mailbox 'examine buffer))
1143 (defun imap-mailbox-unselect (&optional buffer)
1144 "Close current folder in BUFFER, without expunging articles."
1145 (with-current-buffer (or buffer (current-buffer))
1146 (when (or (eq imap-state 'auth)
1147 (and (imap-capability 'UNSELECT)
1148 (imap-ok-p (imap-send-command-wait "UNSELECT")))
1150 (imap-send-command-wait (concat "EXAMINE \""
1151 imap-current-mailbox
1153 (imap-ok-p (imap-send-command-wait "CLOSE"))))
1154 (setq imap-current-mailbox nil
1155 imap-message-data nil
1159 (defun imap-mailbox-expunge (&optional asynch buffer)
1160 "Expunge articles in current folder in BUFFER.
1161 If ASYNCH, do not wait for succesful completion of the command.
1162 If BUFFER is nil the current buffer is assumed."
1163 (with-current-buffer (or buffer (current-buffer))
1164 (when (and imap-current-mailbox (not (eq imap-state 'examine)))
1166 (imap-send-command "EXPUNGE")
1167 (imap-ok-p (imap-send-command-wait "EXPUNGE"))))))
1169 (defun imap-mailbox-close (&optional asynch buffer)
1170 "Expunge articles and close current folder in BUFFER.
1171 If ASYNCH, do not wait for succesful completion of the command.
1172 If BUFFER is nil the current buffer is assumed."
1173 (with-current-buffer (or buffer (current-buffer))
1174 (when imap-current-mailbox
1176 (imap-add-callback (imap-send-command "CLOSE")
1177 `(lambda (tag status)
1178 (message "IMAP mailbox `%s' closed... %s"
1179 imap-current-mailbox status)
1180 (when (eq ,imap-current-mailbox
1181 imap-current-mailbox)
1182 ;; Don't wipe out data if another mailbox
1184 (setq imap-current-mailbox nil
1185 imap-message-data nil
1186 imap-state 'auth))))
1187 (when (imap-ok-p (imap-send-command-wait "CLOSE"))
1188 (setq imap-current-mailbox nil
1189 imap-message-data nil
1193 (defun imap-mailbox-create-1 (mailbox)
1194 (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
1196 (defun imap-mailbox-create (mailbox &optional buffer)
1197 "Create MAILBOX on server in BUFFER.
1198 If BUFFER is nil the current buffer is assumed."
1199 (with-current-buffer (or buffer (current-buffer))
1200 (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
1202 (defun imap-mailbox-delete (mailbox &optional buffer)
1203 "Delete MAILBOX on server in BUFFER.
1204 If BUFFER is nil the current buffer is assumed."
1205 (let ((mailbox (imap-utf7-encode mailbox)))
1206 (with-current-buffer (or buffer (current-buffer))
1208 (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1210 (defun imap-mailbox-rename (oldname newname &optional buffer)
1211 "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1212 If BUFFER is nil the current buffer is assumed."
1213 (let ((oldname (imap-utf7-encode oldname))
1214 (newname (imap-utf7-encode newname)))
1215 (with-current-buffer (or buffer (current-buffer))
1217 (imap-send-command-wait (list "RENAME \"" oldname "\" "
1218 "\"" newname "\""))))))
1220 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1221 "Return a list of subscribed mailboxes on server in BUFFER.
1222 If ROOT is non-nil, only list matching mailboxes. If ADD-DELIMITER is
1223 non-nil, a hierarchy delimiter is added to root. REFERENCE is a
1224 implementation-specific string that has to be passed to lsub command."
1225 (with-current-buffer (or buffer (current-buffer))
1226 ;; Make sure we know the hierarchy separator for root's hierarchy
1227 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1228 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1229 (imap-utf7-encode root) "\"")))
1230 ;; clear list data (NB not delimiter and other stuff)
1231 (imap-mailbox-map-1 (lambda (mailbox)
1232 (imap-mailbox-put 'lsub nil mailbox)))
1234 (imap-send-command-wait
1235 (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1236 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1239 (imap-mailbox-map-1 (lambda (mailbox)
1240 (when (imap-mailbox-get-1 'lsub mailbox)
1241 (push (imap-utf7-decode mailbox) out))))
1244 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1245 "Return a list of mailboxes matching ROOT on server in BUFFER.
1246 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1247 root. REFERENCE is a implementation-specific string that has to be
1248 passed to list command."
1249 (with-current-buffer (or buffer (current-buffer))
1250 ;; Make sure we know the hierarchy separator for root's hierarchy
1251 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1252 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1253 (imap-utf7-encode root) "\"")))
1254 ;; clear list data (NB not delimiter and other stuff)
1255 (imap-mailbox-map-1 (lambda (mailbox)
1256 (imap-mailbox-put 'list nil mailbox)))
1258 (imap-send-command-wait
1259 (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1260 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1263 (imap-mailbox-map-1 (lambda (mailbox)
1264 (when (imap-mailbox-get-1 'list mailbox)
1265 (push (imap-utf7-decode mailbox) out))))
1268 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1269 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1270 Returns non-nil if successful."
1271 (with-current-buffer (or buffer (current-buffer))
1272 (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1273 (imap-utf7-encode mailbox)
1276 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1277 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1278 Returns non-nil if successful."
1279 (with-current-buffer (or buffer (current-buffer))
1280 (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1281 (imap-utf7-encode mailbox)
1284 (defun imap-mailbox-status (mailbox items &optional buffer)
1285 "Get status items ITEM in MAILBOX from server in BUFFER.
1286 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1287 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1288 or 'unseen. If ITEMS is a list of symbols, a list of values is
1289 returned, if ITEMS is a symbol only its value is returned."
1290 (with-current-buffer (or buffer (current-buffer))
1292 (imap-send-command-wait (list "STATUS \""
1293 (imap-utf7-encode mailbox)
1300 (mapcar (lambda (item)
1301 (imap-mailbox-get item mailbox))
1303 (imap-mailbox-get items mailbox)))))
1305 (defun imap-mailbox-status-asynch (mailbox items &optional buffer)
1306 "Send status item request ITEM on MAILBOX to server in BUFFER.
1307 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1308 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1309 or 'unseen. The IMAP command tag is returned."
1310 (with-current-buffer (or buffer (current-buffer))
1311 (imap-send-command (list "STATUS \""
1312 (imap-utf7-encode mailbox)
1319 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1320 "Get ACL on mailbox from server in BUFFER."
1321 (let ((mailbox (imap-utf7-encode mailbox)))
1322 (with-current-buffer (or buffer (current-buffer))
1324 (imap-send-command-wait (list "GETACL \""
1325 (or mailbox imap-current-mailbox)
1327 (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1329 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1330 "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
1331 (let ((mailbox (imap-utf7-encode mailbox)))
1332 (with-current-buffer (or buffer (current-buffer))
1334 (imap-send-command-wait (list "SETACL \""
1335 (or mailbox imap-current-mailbox)
1341 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1342 "Removes any <identifier,rights> pair for IDENTIFIER in MAILBOX from server in BUFFER."
1343 (let ((mailbox (imap-utf7-encode mailbox)))
1344 (with-current-buffer (or buffer (current-buffer))
1346 (imap-send-command-wait (list "DELETEACL \""
1347 (or mailbox imap-current-mailbox)
1352 ;; Message functions:
1354 (defun imap-current-message (&optional buffer)
1355 (with-current-buffer (or buffer (current-buffer))
1356 imap-current-message))
1358 (defun imap-list-to-message-set (list)
1359 (mapconcat (lambda (item)
1360 (number-to-string item))
1366 (defun imap-range-to-message-set (range)
1371 (car item) (cdr item))
1372 (format "%d" item)))
1373 (if (and (listp range) (not (listp (cdr range))))
1374 (list range) ;; make (1 . 2) into ((1 . 2))
1378 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1379 (with-current-buffer (or buffer (current-buffer))
1380 (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1382 (imap-list-to-message-set uids)
1386 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1387 "Fetch properties PROPS from message set UIDS from server in BUFFER.
1388 UIDS can be a string, number or a list of numbers. If RECEIVE
1389 is non-nil return theese properties."
1390 (with-current-buffer (or buffer (current-buffer))
1391 (when (imap-ok-p (imap-send-command-wait
1392 (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1394 (imap-list-to-message-set uids)
1397 (if (or (null receive) (stringp uids))
1400 (mapcar (lambda (uid)
1402 (mapcar (lambda (prop)
1403 (imap-message-get uid prop))
1405 (imap-message-get uid receive)))
1407 (imap-message-get uids receive))))))
1409 (defun imap-message-put (uid propname value &optional buffer)
1410 (with-current-buffer (or buffer (current-buffer))
1411 (if imap-message-data
1412 (put (intern (number-to-string uid) imap-message-data)
1414 (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1415 uid propname value (current-buffer)))
1418 (defun imap-message-get (uid propname &optional buffer)
1419 (with-current-buffer (or buffer (current-buffer))
1420 (get (intern-soft (number-to-string uid) imap-message-data)
1423 (defun imap-message-map (func propname &optional buffer)
1424 "Map a function across each mailbox in `imap-message-data', returning a list."
1425 (with-current-buffer (or buffer (current-buffer))
1429 (push (funcall func (get s 'UID) (get s propname)) result))
1433 (defmacro imap-message-envelope-date (uid &optional buffer)
1434 `(with-current-buffer (or ,buffer (current-buffer))
1435 (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1437 (defmacro imap-message-envelope-subject (uid &optional buffer)
1438 `(with-current-buffer (or ,buffer (current-buffer))
1439 (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1441 (defmacro imap-message-envelope-from (uid &optional buffer)
1442 `(with-current-buffer (or ,buffer (current-buffer))
1443 (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1445 (defmacro imap-message-envelope-sender (uid &optional buffer)
1446 `(with-current-buffer (or ,buffer (current-buffer))
1447 (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1449 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1450 `(with-current-buffer (or ,buffer (current-buffer))
1451 (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1453 (defmacro imap-message-envelope-to (uid &optional buffer)
1454 `(with-current-buffer (or ,buffer (current-buffer))
1455 (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1457 (defmacro imap-message-envelope-cc (uid &optional buffer)
1458 `(with-current-buffer (or ,buffer (current-buffer))
1459 (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1461 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1462 `(with-current-buffer (or ,buffer (current-buffer))
1463 (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1465 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1466 `(with-current-buffer (or ,buffer (current-buffer))
1467 (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1469 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1470 `(with-current-buffer (or ,buffer (current-buffer))
1471 (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1473 (defmacro imap-message-body (uid &optional buffer)
1474 `(with-current-buffer (or ,buffer (current-buffer))
1475 (imap-message-get ,uid 'BODY)))
1477 (defun imap-search (predicate &optional buffer)
1478 (with-current-buffer (or buffer (current-buffer))
1479 (imap-mailbox-put 'search 'dummy)
1480 (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1481 (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1483 (message "Missing SEARCH response to a SEARCH command (server not RFC compliant)...")
1485 (imap-mailbox-get-1 'search imap-current-mailbox)))))
1487 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1488 "Return t iff FLAG can be permanently (between IMAP sessions) saved on articles, in MAILBOX on server in BUFFER."
1489 (with-current-buffer (or buffer (current-buffer))
1490 (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1491 (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1493 (defun imap-message-flags-set (articles flags &optional silent buffer)
1494 (when (and articles flags)
1495 (with-current-buffer (or buffer (current-buffer))
1496 (imap-ok-p (imap-send-command-wait
1497 (concat "UID STORE " articles
1498 " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1500 (defun imap-message-flags-del (articles flags &optional silent buffer)
1501 (when (and articles flags)
1502 (with-current-buffer (or buffer (current-buffer))
1503 (imap-ok-p (imap-send-command-wait
1504 (concat "UID STORE " articles
1505 " -FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1507 (defun imap-message-flags-add (articles flags &optional silent buffer)
1508 (when (and articles flags)
1509 (with-current-buffer (or buffer (current-buffer))
1510 (imap-ok-p (imap-send-command-wait
1511 (concat "UID STORE " articles
1512 " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1514 (defun imap-message-copyuid-1 (mailbox)
1515 (if (imap-capability 'UIDPLUS)
1516 (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1517 (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1518 (let ((old-mailbox imap-current-mailbox)
1520 (imap-message-data (make-vector 2 0)))
1521 (when (imap-mailbox-examine-1 mailbox)
1523 (and (imap-fetch "*" "UID")
1524 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1525 (apply 'max (imap-message-map
1526 (lambda (uid prop) uid) 'UID))))
1528 (imap-mailbox-select old-mailbox (eq state 'examine))
1529 (imap-mailbox-unselect)))))))
1531 (defun imap-message-copyuid (mailbox &optional buffer)
1532 (with-current-buffer (or buffer (current-buffer))
1533 (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1535 (defun imap-message-copy (articles mailbox
1536 &optional dont-create no-copyuid buffer)
1537 "Copy ARTICLES (a string message set) to MAILBOX on server in
1538 BUFFER, creating mailbox if it doesn't exist. If dont-create is
1539 non-nil, it will not create a mailbox. On success, return a list with
1540 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1541 first element, rest of list contain the saved articles' UIDs."
1543 (with-current-buffer (or buffer (current-buffer))
1544 (let ((mailbox (imap-utf7-encode mailbox)))
1545 (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1546 (imap-current-target-mailbox mailbox))
1547 (if (imap-ok-p (imap-send-command-wait cmd))
1549 (when (and (not dont-create)
1550 ;; removed because of buggy Oracle server
1551 ;; that doesn't send TRYCREATE tags (which
1552 ;; is a MUST according to specifications):
1553 ;;(imap-mailbox-get-1 'trycreate mailbox)
1554 (imap-mailbox-create-1 mailbox))
1555 (imap-ok-p (imap-send-command-wait cmd)))))
1557 (imap-message-copyuid-1 mailbox)))))))
1559 (defun imap-message-appenduid-1 (mailbox)
1560 (if (imap-capability 'UIDPLUS)
1561 (imap-mailbox-get-1 'appenduid mailbox)
1562 (let ((old-mailbox imap-current-mailbox)
1564 (imap-message-data (make-vector 2 0)))
1565 (when (imap-mailbox-examine-1 mailbox)
1567 (and (imap-fetch "*" "UID")
1568 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1569 (apply 'max (imap-message-map
1570 (lambda (uid prop) uid) 'UID))))
1572 (imap-mailbox-select old-mailbox (eq state 'examine))
1573 (imap-mailbox-unselect)))))))
1575 (defun imap-message-appenduid (mailbox &optional buffer)
1576 (with-current-buffer (or buffer (current-buffer))
1577 (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1579 (defun imap-message-append (mailbox article &optional flags date-time buffer)
1580 "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1581 FLAGS and DATE-TIME is currently not used. Return a cons holding
1582 uidvalidity of MAILBOX and UID the newly created article got, or nil
1584 (let ((mailbox (imap-utf7-encode mailbox)))
1585 (with-current-buffer (or buffer (current-buffer))
1586 (and (let ((imap-current-target-mailbox mailbox))
1588 (imap-send-command-wait
1589 (list "APPEND \"" mailbox "\" " article))))
1590 (imap-message-appenduid-1 mailbox)))))
1592 (defun imap-body-lines (body)
1593 "Return number of lines in article by looking at the mime bodystructure BODY."
1595 (if (stringp (car body))
1596 (cond ((and (string= (upcase (car body)) "TEXT")
1597 (numberp (nth 7 body)))
1599 ((and (string= (upcase (car body)) "MESSAGE")
1600 (numberp (nth 9 body)))
1603 (apply '+ (mapcar 'imap-body-lines body)))
1606 (defun imap-envelope-from (from)
1607 "Return a from string line."
1609 (concat (aref from 0)
1610 (if (aref from 0) " <")
1614 (if (aref from 0) ">"))))
1617 ;; Internal functions.
1619 (defun imap-add-callback (tag func)
1620 (setq imap-callbacks (append (list (cons tag func)) imap-callbacks)))
1622 (defun imap-send-command-1 (cmdstr)
1623 (setq cmdstr (concat cmdstr imap-client-eol))
1625 (with-current-buffer (get-buffer-create imap-log-buffer)
1626 (imap-disable-multibyte)
1627 (buffer-disable-undo)
1628 (goto-char (point-max))
1630 (process-send-string imap-process cmdstr))
1632 (defun imap-send-command (command &optional buffer)
1633 (with-current-buffer (or buffer (current-buffer))
1634 (if (not (listp command)) (setq command (list command)))
1635 (let ((tag (setq imap-tag (1+ imap-tag)))
1637 (setq cmdstr (concat (number-to-string imap-tag) " "))
1638 (while (setq cmd (pop command))
1639 (cond ((stringp cmd)
1640 (setq cmdstr (concat cmdstr cmd)))
1642 (let ((eol imap-client-eol)
1643 (calcfirst imap-calculate-literal-size-first)
1645 (with-current-buffer cmd
1647 (setq size (buffer-size)))
1648 (when (not (equal eol "\r\n"))
1649 ;; XXX modifies buffer!
1650 (goto-char (point-min))
1651 (while (search-forward "\r\n" nil t)
1652 (replace-match eol)))
1654 (setq size (buffer-size))))
1656 (concat cmdstr (format "{%d}" size))))
1659 (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 (let ((process imap-process)
1664 (stream imap-stream)
1665 (eol imap-client-eol))
1666 (with-current-buffer cmd
1668 (with-current-buffer (get-buffer-create
1670 (imap-disable-multibyte)
1671 (buffer-disable-undo)
1672 (goto-char (point-max))
1673 (insert-buffer-substring cmd)))
1674 (process-send-region process (point-min)
1676 (process-send-string process imap-client-eol))))
1677 (setq imap-continuation nil)))
1679 (imap-send-command-1 cmdstr)
1682 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1683 (setq command nil) ;; abort command if no cont-req
1684 (setq command (cons (funcall cmd imap-continuation)
1686 (setq imap-continuation nil)))
1688 (error "Unknown command type"))))
1690 (imap-send-command-1 cmdstr))
1693 (defun imap-wait-for-tag (tag &optional buffer)
1694 (with-current-buffer (or buffer (current-buffer))
1695 (let (imap-have-messaged)
1696 (while (and (null imap-continuation)
1697 (memq (process-status imap-process) '(open run))
1698 (< imap-reached-tag tag))
1699 (let ((len (/ (point-max) 1024))
1702 (setq imap-have-messaged t)
1703 (message "imap read: %dk" len))
1704 (accept-process-output imap-process 1)))
1705 (when imap-have-messaged
1707 (and (memq (process-status imap-process) '(open run))
1708 (or (assq tag imap-failed-tags)
1709 (if imap-continuation
1713 (defun imap-sentinel (process string)
1714 (delete-process process))
1716 (defun imap-find-next-line ()
1717 "Return point at end of current line, taking into account literals.
1718 Return nil if no complete line has arrived."
1719 (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
1722 (if (match-string 1)
1723 (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1725 (goto-char (+ (point) (string-to-number (match-string 1))))
1726 (imap-find-next-line))
1729 (defun imap-arrival-filter (proc string)
1730 "IMAP process filter."
1731 (with-current-buffer (process-buffer proc)
1732 (goto-char (point-max))
1735 (with-current-buffer (get-buffer-create imap-log-buffer)
1736 (imap-disable-multibyte)
1737 (buffer-disable-undo)
1738 (goto-char (point-max))
1741 (goto-char (point-min))
1742 (while (setq end (imap-find-next-line))
1744 (narrow-to-region (point-min) end)
1745 (delete-backward-char (length imap-server-eol))
1746 (goto-char (point-min))
1748 (cond ((eq imap-state 'initial)
1749 (imap-parse-greeting))
1750 ((or (eq imap-state 'auth)
1751 (eq imap-state 'nonauth)
1752 (eq imap-state 'selected)
1753 (eq imap-state 'examine))
1754 (imap-parse-response))
1756 (message "Unknown state %s in arrival filter"
1758 (delete-region (point-min) (point-max))))))))
1763 (defsubst imap-forward ()
1764 (or (eobp) (forward-char)))
1767 ;; ; Unsigned 32-bit integer
1768 ;; ; (0 <= n < 4,294,967,296)
1770 (defsubst imap-parse-number ()
1771 (when (looking-at "[0-9]+")
1773 (string-to-number (match-string 0))
1774 (goto-char (match-end 0)))))
1776 ;; literal = "{" number "}" CRLF *CHAR8
1777 ;; ; Number represents the number of CHAR8s
1779 (defsubst imap-parse-literal ()
1780 (when (looking-at "{\\([0-9]+\\)}\r\n")
1781 (let ((pos (match-end 0))
1782 (len (string-to-number (match-string 1))))
1783 (if (< (point-max) (+ pos len))
1785 (goto-char (+ pos len))
1786 (buffer-substring pos (+ pos len))))))
1788 ;; string = quoted / literal
1790 ;; quoted = DQUOTE *QUOTED-CHAR DQUOTE
1792 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
1793 ;; "\" quoted-specials
1795 ;; quoted-specials = DQUOTE / "\"
1797 ;; TEXT-CHAR = <any CHAR except CR and LF>
1799 (defsubst imap-parse-string ()
1800 (cond ((eq (char-after) ?\")
1802 (let ((p (point)) (name ""))
1803 (skip-chars-forward "^\"\\\\")
1804 (setq name (buffer-substring p (point)))
1805 (while (eq (char-after) ?\\)
1806 (setq p (1+ (point)))
1808 (skip-chars-forward "^\"\\\\")
1809 (setq name (concat name (buffer-substring p (point)))))
1812 ((eq (char-after) ?{)
1813 (imap-parse-literal))))
1817 (defsubst imap-parse-nil ()
1818 (if (looking-at "NIL")
1819 (goto-char (match-end 0))))
1821 ;; nstring = string / nil
1823 (defsubst imap-parse-nstring ()
1824 (or (imap-parse-string)
1825 (and (imap-parse-nil)
1828 ;; astring = atom / string
1830 ;; atom = 1*ATOM-CHAR
1832 ;; ATOM-CHAR = <any CHAR except atom-specials>
1834 ;; atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards /
1837 ;; list-wildcards = "%" / "*"
1839 ;; quoted-specials = DQUOTE / "\"
1841 (defsubst imap-parse-astring ()
1842 (or (imap-parse-string)
1843 (buffer-substring (point)
1844 (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
1845 (goto-char (1- (match-end 0)))
1849 ;; address = "(" addr-name SP addr-adl SP addr-mailbox SP
1852 ;; addr-adl = nstring
1853 ;; ; Holds route from [RFC-822] route-addr if
1856 ;; addr-host = nstring
1857 ;; ; nil indicates [RFC-822] group syntax.
1858 ;; ; Otherwise, holds [RFC-822] domain name
1860 ;; addr-mailbox = nstring
1861 ;; ; nil indicates end of [RFC-822] group; if
1862 ;; ; non-nil and addr-host is nil, holds
1863 ;; ; [RFC-822] group name.
1864 ;; ; Otherwise, holds [RFC-822] local-part
1865 ;; ; after removing [RFC-822] quoting
1867 ;; addr-name = nstring
1868 ;; ; If non-nil, holds phrase from [RFC-822]
1869 ;; ; mailbox after removing [RFC-822] quoting
1872 (defsubst imap-parse-address ()
1874 (when (eq (char-after) ?\()
1876 (setq address (vector (prog1 (imap-parse-nstring)
1878 (prog1 (imap-parse-nstring)
1880 (prog1 (imap-parse-nstring)
1882 (imap-parse-nstring)))
1883 (when (eq (char-after) ?\))
1887 ;; address-list = "(" 1*address ")" / nil
1891 (defsubst imap-parse-address-list ()
1892 (if (eq (char-after) ?\()
1893 (let (address addresses)
1895 (while (and (not (eq (char-after) ?\)))
1896 ;; next line for MS Exchange bug
1897 (progn (and (eq (char-after) ? ) (imap-forward)) t)
1898 (setq address (imap-parse-address)))
1899 (setq addresses (cons address addresses)))
1900 (when (eq (char-after) ?\))
1902 (nreverse addresses)))
1903 (assert (imap-parse-nil) t "In imap-parse-address-list")))
1905 ;; mailbox = "INBOX" / astring
1906 ;; ; INBOX is case-insensitive. All case variants of
1907 ;; ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
1908 ;; ; not as an astring. An astring which consists of
1909 ;; ; the case-insensitive sequence "I" "N" "B" "O" "X"
1910 ;; ; is considered to be INBOX and not an astring.
1911 ;; ; Refer to section 5.1 for further
1912 ;; ; semantic details of mailbox names.
1914 (defsubst imap-parse-mailbox ()
1915 (let ((mailbox (imap-parse-astring)))
1916 (if (string-equal "INBOX" (upcase mailbox))
1920 ;; greeting = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
1922 ;; resp-cond-auth = ("OK" / "PREAUTH") SP resp-text
1923 ;; ; Authentication condition
1925 ;; resp-cond-bye = "BYE" SP resp-text
1927 (defun imap-parse-greeting ()
1928 "Parse a IMAP greeting."
1929 (cond ((looking-at "\\* OK ")
1930 (setq imap-state 'nonauth))
1931 ((looking-at "\\* PREAUTH ")
1932 (setq imap-state 'auth))
1933 ((looking-at "\\* BYE ")
1934 (setq imap-state 'closed))))
1936 ;; response = *(continue-req / response-data) response-done
1938 ;; continue-req = "+" SP (resp-text / base64) CRLF
1940 ;; response-data = "*" SP (resp-cond-state / resp-cond-bye /
1941 ;; mailbox-data / message-data / capability-data) CRLF
1943 ;; response-done = response-tagged / response-fatal
1945 ;; response-fatal = "*" SP resp-cond-bye CRLF
1946 ;; ; Server closes connection immediately
1948 ;; response-tagged = tag SP resp-cond-state CRLF
1950 ;; resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
1951 ;; ; Status condition
1953 ;; resp-cond-bye = "BYE" SP resp-text
1955 ;; mailbox-data = "FLAGS" SP flag-list /
1956 ;; "LIST" SP mailbox-list /
1957 ;; "LSUB" SP mailbox-list /
1958 ;; "SEARCH" *(SP nz-number) /
1959 ;; "STATUS" SP mailbox SP "("
1960 ;; [status-att SP number *(SP status-att SP number)] ")" /
1961 ;; number SP "EXISTS" /
1962 ;; number SP "RECENT"
1964 ;; message-data = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
1966 ;; capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
1968 ;; ; IMAP4rev1 servers which offer RFC 1730
1969 ;; ; compatibility MUST list "IMAP4" as the first
1972 (defun imap-parse-response ()
1973 "Parse a IMAP command response."
1975 (case (setq token (read (current-buffer)))
1976 (+ (setq imap-continuation
1977 (or (buffer-substring (min (point-max) (1+ (point)))
1980 (* (case (prog1 (setq token (read (current-buffer)))
1982 (OK (imap-parse-resp-text))
1983 (NO (imap-parse-resp-text))
1984 (BAD (imap-parse-resp-text))
1985 (BYE (imap-parse-resp-text))
1986 (FLAGS (imap-mailbox-put 'flags (imap-parse-flag-list)))
1987 (LIST (imap-parse-data-list 'list))
1988 (LSUB (imap-parse-data-list 'lsub))
1989 (SEARCH (imap-mailbox-put
1991 (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
1992 (STATUS (imap-parse-status))
1993 (CAPABILITY (setq imap-capability
1994 (read (concat "(" (upcase (buffer-substring
1995 (point) (point-max)))
1997 (ACL (imap-parse-acl))
1998 (t (case (prog1 (read (current-buffer))
2000 (EXISTS (imap-mailbox-put 'exists token))
2001 (RECENT (imap-mailbox-put 'recent token))
2003 (FETCH (imap-parse-fetch token))
2004 (t (message "Garbage: %s" (buffer-string)))))))
2006 (if (not (integerp token))
2007 (message "Garbage: %s" (buffer-string))
2008 (case (prog1 (setq status (read (current-buffer)))
2011 (setq imap-reached-tag (max imap-reached-tag token))
2012 (imap-parse-resp-text)))
2014 (setq imap-reached-tag (max imap-reached-tag token))
2016 (imap-parse-resp-text))
2018 (when (eq (char-after) ?\[)
2019 (setq code (buffer-substring (point)
2020 (search-forward "]")))
2022 (setq text (buffer-substring (point) (point-max)))
2023 (push (list token status code text)
2024 imap-failed-tags))))
2026 (setq imap-reached-tag (max imap-reached-tag token))
2028 (imap-parse-resp-text))
2030 (when (eq (char-after) ?\[)
2031 (setq code (buffer-substring (point)
2032 (search-forward "]")))
2034 (setq text (buffer-substring (point) (point-max)))
2035 (push (list token status code text) imap-failed-tags)
2036 (error "Internal error, tag %s status %s code %s text %s"
2037 token status code text))))
2038 (t (message "Garbage: %s" (buffer-string))))
2039 (when (assq token imap-callbacks)
2040 (funcall (cdr (assq token imap-callbacks)) token status)
2041 (setq imap-callbacks
2042 (imap-remassoc token imap-callbacks)))))))))
2044 ;; resp-text = ["[" resp-text-code "]" SP] text
2046 ;; text = 1*TEXT-CHAR
2048 ;; TEXT-CHAR = <any CHAR except CR and LF>
2050 (defun imap-parse-resp-text ()
2051 (imap-parse-resp-text-code))
2053 ;; resp-text-code = "ALERT" /
2054 ;; "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
2055 ;; "NEWNAME" SP string SP string /
2057 ;; "PERMANENTFLAGS" SP "("
2058 ;; [flag-perm *(SP flag-perm)] ")" /
2062 ;; "UIDNEXT" SP nz-number /
2063 ;; "UIDVALIDITY" SP nz-number /
2064 ;; "UNSEEN" SP nz-number /
2065 ;; resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
2067 ;; resp_code_apnd = "APPENDUID" SPACE nz_number SPACE uniqueid
2069 ;; resp_code_copy = "COPYUID" SPACE nz_number SPACE set SPACE set
2071 ;; set = sequence-num / (sequence-num ":" sequence-num) /
2073 ;; ; Identifies a set of messages. For message
2074 ;; ; sequence numbers, these are consecutive
2075 ;; ; numbers from 1 to the number of messages in
2077 ;; ; Comma delimits individual numbers, colon
2078 ;; ; delimits between two numbers inclusive.
2079 ;; ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
2080 ;; ; 14,15 for a mailbox with 15 messages.
2082 ;; sequence-num = nz-number / "*"
2083 ;; ; * is the largest number in use. For message
2084 ;; ; sequence numbers, it is the number of messages
2085 ;; ; in the mailbox. For unique identifiers, it is
2086 ;; ; the unique identifier of the last message in
2089 ;; flag-perm = flag / "\*"
2091 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2092 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2093 ;; ; Does not include "\Recent"
2095 ;; flag-extension = "\" atom
2096 ;; ; Future expansion. Client implementations
2097 ;; ; MUST accept flag-extension flags. Server
2098 ;; ; implementations MUST NOT generate
2099 ;; ; flag-extension flags except as defined by
2100 ;; ; future standard or standards-track
2101 ;; ; revisions of this specification.
2103 ;; flag-keyword = atom
2105 ;; resp-text-atom = 1*<any ATOM-CHAR except "]">
2107 (defun imap-parse-resp-text-code ()
2108 ;; xxx next line for stalker communigate pro 3.3.1 bug
2109 (when (looking-at " \\[")
2111 (when (eq (char-after) ?\[)
2113 (cond ((search-forward "PERMANENTFLAGS " nil t)
2114 (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2115 ((search-forward "UIDNEXT \\([0-9]+\\)" nil t)
2116 (imap-mailbox-put 'uidnext (match-string 1)))
2117 ((search-forward "UNSEEN " nil t)
2118 (imap-mailbox-put 'first-unseen (read (current-buffer))))
2119 ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2120 (imap-mailbox-put 'uidvalidity (match-string 1)))
2121 ((search-forward "READ-ONLY" nil t)
2122 (imap-mailbox-put 'read-only t))
2123 ((search-forward "NEWNAME " nil t)
2124 (let (oldname newname)
2125 (setq oldname (imap-parse-string))
2127 (setq newname (imap-parse-string))
2128 (imap-mailbox-put 'newname newname oldname)))
2129 ((search-forward "TRYCREATE" nil t)
2130 (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2131 ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2132 (imap-mailbox-put 'appenduid
2133 (list (match-string 1)
2134 (string-to-number (match-string 2)))
2135 imap-current-target-mailbox))
2136 ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2137 (imap-mailbox-put 'copyuid (list (match-string 1)
2140 imap-current-target-mailbox))
2141 ((search-forward "ALERT] " nil t)
2142 (message "Imap server %s information: %s" imap-server
2143 (buffer-substring (point) (point-max)))))))
2145 ;; mailbox-list = "(" [mbx-list-flags] ")" SP
2146 ;; (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2148 ;; mbx-list-flags = *(mbx-list-oflag SP) mbx-list-sflag
2149 ;; *(SP mbx-list-oflag) /
2150 ;; mbx-list-oflag *(SP mbx-list-oflag)
2152 ;; mbx-list-oflag = "\Noinferiors" / flag-extension
2153 ;; ; Other flags; multiple possible per LIST response
2155 ;; mbx-list-sflag = "\Noselect" / "\Marked" / "\Unmarked"
2156 ;; ; Selectability flags; only one per LIST response
2158 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2159 ;; "\" quoted-specials
2161 ;; quoted-specials = DQUOTE / "\"
2163 (defun imap-parse-data-list (type)
2164 (let (flags delimiter mailbox)
2165 (setq flags (imap-parse-flag-list))
2166 (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2167 (setq delimiter (match-string 1))
2168 (goto-char (1+ (match-end 0)))
2169 (when (setq mailbox (imap-parse-mailbox))
2170 (imap-mailbox-put type t mailbox)
2171 (imap-mailbox-put 'list-flags flags mailbox)
2172 (imap-mailbox-put 'delimiter delimiter mailbox)))))
2174 ;; msg_att ::= "(" 1#("ENVELOPE" SPACE envelope /
2175 ;; "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2176 ;; "INTERNALDATE" SPACE date_time /
2177 ;; "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2178 ;; "RFC822.SIZE" SPACE number /
2179 ;; "BODY" ["STRUCTURE"] SPACE body /
2180 ;; "BODY" section ["<" number ">"] SPACE nstring /
2181 ;; "UID" SPACE uniqueid) ")"
2183 ;; date_time ::= <"> date_day_fixed "-" date_month "-" date_year
2184 ;; SPACE time SPACE zone <">
2186 ;; section ::= "[" [section_text / (nz_number *["." nz_number]
2187 ;; ["." (section_text / "MIME")])] "]"
2189 ;; section_text ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2190 ;; SPACE header_list / "TEXT"
2192 ;; header_fld_name ::= astring
2194 ;; header_list ::= "(" 1#header_fld_name ")"
2196 (defsubst imap-parse-header-list ()
2197 (when (eq (char-after) ?\()
2199 (while (not (eq (char-after) ?\)))
2201 (push (imap-parse-astring) strlist))
2203 (nreverse strlist))))
2205 (defsubst imap-parse-fetch-body-section ()
2207 (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2208 (if (eq (char-before) ? )
2210 (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2211 (search-forward "]" nil t))
2214 (defun imap-parse-fetch (response)
2215 (when (eq (char-after) ?\()
2216 (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2217 rfc822size body bodydetail bodystructure flags-empty)
2218 (while (not (eq (char-after) ?\)))
2220 (let ((token (read (current-buffer))))
2222 (cond ((eq token 'UID)
2223 (setq uid (condition-case ()
2224 (read (current-buffer))
2227 (setq flags (imap-parse-flag-list))
2229 (setq flags-empty 't)))
2230 ((eq token 'ENVELOPE)
2231 (setq envelope (imap-parse-envelope)))
2232 ((eq token 'INTERNALDATE)
2233 (setq internaldate (imap-parse-string)))
2235 (setq rfc822 (imap-parse-nstring)))
2236 ((eq token 'RFC822.HEADER)
2237 (setq rfc822header (imap-parse-nstring)))
2238 ((eq token 'RFC822.TEXT)
2239 (setq rfc822text (imap-parse-nstring)))
2240 ((eq token 'RFC822.SIZE)
2241 (setq rfc822size (read (current-buffer))))
2243 (if (eq (char-before) ?\[)
2245 (upcase (imap-parse-fetch-body-section))
2246 (and (eq (char-after) ?<)
2247 (buffer-substring (1+ (point))
2248 (search-forward ">" nil t)))
2249 (progn (imap-forward)
2250 (imap-parse-nstring)))
2252 (setq body (imap-parse-body))))
2253 ((eq token 'BODYSTRUCTURE)
2254 (setq bodystructure (imap-parse-body))))))
2256 (setq imap-current-message uid)
2257 (imap-message-put uid 'UID uid)
2258 (and (or flags flags-empty) (imap-message-put uid 'FLAGS flags))
2259 (and envelope (imap-message-put uid 'ENVELOPE envelope))
2260 (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2261 (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2262 (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2263 (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2264 (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2265 (and body (imap-message-put uid 'BODY body))
2266 (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2267 (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2268 (run-hooks 'imap-fetch-data-hook)))))
2270 ;; mailbox-data = ...
2271 ;; "STATUS" SP mailbox SP "("
2272 ;; [status-att SP number
2273 ;; *(SP status-att SP number)] ")"
2276 ;; status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2279 (defun imap-parse-status ()
2280 (let ((mailbox (imap-parse-mailbox)))
2281 (if (eq (char-after) ? )
2283 (when (and mailbox (eq (char-after) ?\())
2284 (while (and (not (eq (char-after) ?\)))
2285 (or (forward-char) t)
2286 (looking-at "\\([A-Za-z]+\\) "))
2287 (let ((token (match-string 1)))
2288 (goto-char (match-end 0))
2289 (cond ((string= token "MESSAGES")
2290 (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2291 ((string= token "RECENT")
2292 (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2293 ((string= token "UIDNEXT")
2294 (and (looking-at "[0-9]+")
2295 (imap-mailbox-put 'uidnext (match-string 0) mailbox)
2296 (goto-char (match-end 0))))
2297 ((string= token "UIDVALIDITY")
2298 (and (looking-at "[0-9]+")
2299 (imap-mailbox-put 'uidvalidity (match-string 0) mailbox)
2300 (goto-char (match-end 0))))
2301 ((string= token "UNSEEN")
2302 (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2304 (message "Unknown status data %s in mailbox %s ignored"
2306 (read (current-buffer)))))))))
2308 ;; acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2311 ;; identifier ::= astring
2313 ;; rights ::= astring
2315 (defun imap-parse-acl ()
2316 (let ((mailbox (imap-parse-mailbox))
2317 identifier rights acl)
2318 (while (eq (char-after) ?\ )
2320 (setq identifier (imap-parse-astring))
2322 (setq rights (imap-parse-astring))
2323 (setq acl (append acl (list (cons identifier rights)))))
2324 (imap-mailbox-put 'acl acl mailbox)))
2326 ;; flag-list = "(" [flag *(SP flag)] ")"
2328 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2329 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2330 ;; ; Does not include "\Recent"
2332 ;; flag-keyword = atom
2334 ;; flag-extension = "\" atom
2335 ;; ; Future expansion. Client implementations
2336 ;; ; MUST accept flag-extension flags. Server
2337 ;; ; implementations MUST NOT generate
2338 ;; ; flag-extension flags except as defined by
2339 ;; ; future standard or standards-track
2340 ;; ; revisions of this specification.
2342 (defun imap-parse-flag-list ()
2343 (let (flag-list start)
2344 (assert (eq (char-after) ?\() t "In imap-parse-flag-list")
2345 (while (and (not (eq (char-after) ?\)))
2348 ;; next line for Courier IMAP bug.
2349 (skip-chars-forward " ")
2351 (> (skip-chars-forward "^ )" (imap-point-at-eol)) 0))
2352 (push (buffer-substring start (point)) flag-list))
2353 (assert (eq (char-after) ?\)) t "In imap-parse-flag-list")
2355 (nreverse flag-list)))
2357 ;; envelope = "(" env-date SP env-subject SP env-from SP env-sender SP
2358 ;; env-reply-to SP env-to SP env-cc SP env-bcc SP
2359 ;; env-in-reply-to SP env-message-id ")"
2361 ;; env-bcc = "(" 1*address ")" / nil
2363 ;; env-cc = "(" 1*address ")" / nil
2365 ;; env-date = nstring
2367 ;; env-from = "(" 1*address ")" / nil
2369 ;; env-in-reply-to = nstring
2371 ;; env-message-id = nstring
2373 ;; env-reply-to = "(" 1*address ")" / nil
2375 ;; env-sender = "(" 1*address ")" / nil
2377 ;; env-subject = nstring
2379 ;; env-to = "(" 1*address ")" / nil
2381 (defun imap-parse-envelope ()
2382 (when (eq (char-after) ?\()
2384 (vector (prog1 (imap-parse-nstring) ;; date
2386 (prog1 (imap-parse-nstring) ;; subject
2388 (prog1 (imap-parse-address-list) ;; from
2390 (prog1 (imap-parse-address-list) ;; sender
2392 (prog1 (imap-parse-address-list) ;; reply-to
2394 (prog1 (imap-parse-address-list) ;; to
2396 (prog1 (imap-parse-address-list) ;; cc
2398 (prog1 (imap-parse-address-list) ;; bcc
2400 (prog1 (imap-parse-nstring) ;; in-reply-to
2402 (prog1 (imap-parse-nstring) ;; message-id
2405 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2407 (defsubst imap-parse-string-list ()
2408 (cond ((eq (char-after) ?\() ;; body-fld-param
2411 (while (setq str (imap-parse-string))
2413 ;; buggy stalker communigate pro 3.0 doesn't print SPC
2414 ;; between body-fld-param's sometimes
2415 (or (eq (char-after) ?\")
2417 (nreverse strlist)))
2421 ;; body-extension = nstring / number /
2422 ;; "(" body-extension *(SP body-extension) ")"
2423 ;; ; Future expansion. Client implementations
2424 ;; ; MUST accept body-extension fields. Server
2425 ;; ; implementations MUST NOT generate
2426 ;; ; body-extension fields except as defined by
2427 ;; ; future standard or standards-track
2428 ;; ; revisions of this specification.
2430 (defun imap-parse-body-extension ()
2431 (if (eq (char-after) ?\()
2434 (push (imap-parse-body-extension) b-e)
2435 (while (eq (char-after) ?\ )
2437 (push (imap-parse-body-extension) b-e))
2438 (assert (eq (char-after) ?\)) t "In imap-parse-body-extension")
2441 (or (imap-parse-number)
2442 (imap-parse-nstring))))
2444 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2445 ;; *(SP body-extension)]]
2446 ;; ; MUST NOT be returned on non-extensible
2449 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2450 ;; *(SP body-extension)]]
2451 ;; ; MUST NOT be returned on non-extensible
2454 (defsubst imap-parse-body-ext ()
2456 (when (eq (char-after) ?\ ) ;; body-fld-dsp
2459 (if (eq (char-after) ?\()
2462 (push (imap-parse-string) dsp)
2464 (push (imap-parse-string-list) dsp)
2466 (assert (imap-parse-nil) t "In imap-parse-body-ext"))
2467 (push (nreverse dsp) ext))
2468 (when (eq (char-after) ?\ ) ;; body-fld-lang
2470 (if (eq (char-after) ?\()
2471 (push (imap-parse-string-list) ext)
2472 (push (imap-parse-nstring) ext))
2473 (while (eq (char-after) ?\ ) ;; body-extension
2475 (setq ext (append (imap-parse-body-extension) ext)))))
2478 ;; body = "(" body-type-1part / body-type-mpart ")"
2480 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2481 ;; *(SP body-extension)]]
2482 ;; ; MUST NOT be returned on non-extensible
2485 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2486 ;; *(SP body-extension)]]
2487 ;; ; MUST NOT be returned on non-extensible
2490 ;; body-fields = body-fld-param SP body-fld-id SP body-fld-desc SP
2491 ;; body-fld-enc SP body-fld-octets
2493 ;; body-fld-desc = nstring
2495 ;; body-fld-dsp = "(" string SP body-fld-param ")" / nil
2497 ;; body-fld-enc = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2498 ;; "QUOTED-PRINTABLE") DQUOTE) / string
2500 ;; body-fld-id = nstring
2502 ;; body-fld-lang = nstring / "(" string *(SP string) ")"
2504 ;; body-fld-lines = number
2506 ;; body-fld-md5 = nstring
2508 ;; body-fld-octets = number
2510 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2512 ;; body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2513 ;; [SP body-ext-1part]
2515 ;; body-type-basic = media-basic SP body-fields
2516 ;; ; MESSAGE subtype MUST NOT be "RFC822"
2518 ;; body-type-msg = media-message SP body-fields SP envelope
2519 ;; SP body SP body-fld-lines
2521 ;; body-type-text = media-text SP body-fields SP body-fld-lines
2523 ;; body-type-mpart = 1*body SP media-subtype
2524 ;; [SP body-ext-mpart]
2526 ;; media-basic = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2527 ;; "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2528 ;; ; Defined in [MIME-IMT]
2530 ;; media-message = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2531 ;; ; Defined in [MIME-IMT]
2533 ;; media-subtype = string
2534 ;; ; Defined in [MIME-IMT]
2536 ;; media-text = DQUOTE "TEXT" DQUOTE SP media-subtype
2537 ;; ; Defined in [MIME-IMT]
2539 (defun imap-parse-body ()
2541 (when (eq (char-after) ?\()
2543 (if (eq (char-after) ?\()
2545 (while (and (eq (char-after) ?\()
2546 (setq subbody (imap-parse-body)))
2547 ;; buggy stalker communigate pro 3.0 insert a SPC between
2548 ;; parts in multiparts
2549 (when (and (eq (char-after) ?\ )
2550 (eq (char-after (1+ (point))) ?\())
2552 (push subbody body))
2554 (push (imap-parse-string) body) ;; media-subtype
2555 (when (eq (char-after) ?\ ) ;; body-ext-mpart:
2557 (if (eq (char-after) ?\() ;; body-fld-param
2558 (push (imap-parse-string-list) body)
2559 (push (and (imap-parse-nil) nil) body))
2561 (append (imap-parse-body-ext) body))) ;; body-ext-...
2562 (assert (eq (char-after) ?\)) t "In imap-parse-body")
2566 (push (imap-parse-string) body) ;; media-type
2568 (push (imap-parse-string) body) ;; media-subtype
2570 ;; next line for Sun SIMS bug
2571 (and (eq (char-after) ? ) (imap-forward))
2572 (if (eq (char-after) ?\() ;; body-fld-param
2573 (push (imap-parse-string-list) body)
2574 (push (and (imap-parse-nil) nil) body))
2576 (push (imap-parse-nstring) body) ;; body-fld-id
2578 (push (imap-parse-nstring) body) ;; body-fld-desc
2580 ;; next `or' for Sun SIMS bug, it regard body-fld-enc as a
2581 ;; nstring and return nil instead of defaulting back to 7BIT
2582 ;; as the standard says.
2583 (push (or (imap-parse-nstring) "7BIT") body) ;; body-fld-enc
2585 (push (imap-parse-number) body) ;; body-fld-octets
2587 ;; ok, we're done parsing the required parts, what comes now is one
2590 ;; envelope (then we're parsing body-type-msg)
2591 ;; body-fld-lines (then we're parsing body-type-text)
2592 ;; body-ext-1part (then we're parsing body-type-basic)
2594 ;; the problem is that the two first are in turn optionally followed
2595 ;; by the third. So we parse the first two here (if there are any)...
2597 (when (eq (char-after) ?\ )
2600 (cond ((eq (char-after) ?\() ;; body-type-msg:
2601 (push (imap-parse-envelope) body) ;; envelope
2603 (push (imap-parse-body) body) ;; body
2604 ;; buggy stalker communigate pro 3.0 doesn't print
2605 ;; number of lines in message/rfc822 attachment
2606 (if (eq (char-after) ?\))
2609 (push (imap-parse-number) body))) ;; body-fld-lines
2610 ((setq lines (imap-parse-number)) ;; body-type-text:
2611 (push lines body)) ;; body-fld-lines
2613 (backward-char))))) ;; no match...
2615 ;; ...and then parse the third one here...
2617 (when (eq (char-after) ?\ ) ;; body-ext-1part:
2619 (push (imap-parse-nstring) body) ;; body-fld-md5
2620 (setq body (append (imap-parse-body-ext) body))) ;; body-ext-1part..
2622 (assert (eq (char-after) ?\)) t "In imap-parse-body 2")
2626 (when imap-debug ; (untrace-all)
2628 (buffer-disable-undo (get-buffer-create imap-debug-buffer))
2629 (mapcar (lambda (f) (trace-function-background f imap-debug-buffer))
2640 imap-interactive-login
2656 imap-send-command-wait
2661 imap-current-mailbox
2662 imap-current-mailbox-p-1
2663 imap-current-mailbox-p
2664 imap-mailbox-select-1
2666 imap-mailbox-examine-1
2667 imap-mailbox-examine
2668 imap-mailbox-unselect
2669 imap-mailbox-expunge
2671 imap-mailbox-create-1
2677 imap-mailbox-subscribe
2678 imap-mailbox-unsubscribe
2680 imap-mailbox-acl-get
2681 imap-mailbox-acl-set
2682 imap-mailbox-acl-delete
2683 imap-current-message
2684 imap-list-to-message-set
2691 imap-message-flag-permanent-p
2692 imap-message-flags-set
2693 imap-message-flags-del
2694 imap-message-flags-add
2695 imap-message-copyuid-1
2696 imap-message-copyuid
2698 imap-message-appenduid-1
2699 imap-message-appenduid
2711 imap-parse-resp-text
2712 imap-parse-resp-text-code
2713 imap-parse-data-list
2717 imap-parse-flag-list
2719 imap-parse-body-extension
2725 ;;; imap.el ends here