1 ;;; imap.el --- imap library
2 ;; Copyright (C) 1998,1999 Free Software Foundation, Inc.
4 ;; Author: Simon Josefsson <jas@pdc.kth.se>
7 ;; This file is part of GNU Emacs.
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING. If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
26 ;; imap.el is a elisp library providing an interface for talking to
29 ;; imap.el is roughly divided in two parts, one that parses IMAP
30 ;; responses from the server and storing data into buffer-local
31 ;; variables, and one for utility functions which send commands to
32 ;; server, waits for an answer, and return information. The latter
33 ;; part is layered on top of the previous.
35 ;; The imap.el API consist of the following functions, other functions
36 ;; in this file should not be called directly and the result of doing
37 ;; so are at best undefined.
41 ;; imap-open, imap-opened, imap-authenticate, imap-close,
42 ;; imap-capability, imap-namespace, imap-error-text
46 ;; imap-mailbox-get, imap-mailbox-map, imap-current-mailbox,
47 ;; imap-current-mailbox-p, imap-search, imap-mailbox-select,
48 ;; imap-mailbox-examine, imap-mailbox-unselect, imap-mailbox-expunge
49 ;; imap-mailbox-close, imap-mailbox-create, imap-mailbox-delete
50 ;; imap-mailbox-rename, imap-mailbox-lsub, imap-mailbox-list
51 ;; imap-mailbox-subscribe, imap-mailbox-unsubscribe, imap-mailbox-status
52 ;; imap-mailbox-acl-get, imap-mailbox-acl-set, imap-mailbox-acl-delete
56 ;; imap-fetch-asynch, imap-fetch,
57 ;; imap-current-message, imap-list-to-message-set,
58 ;; imap-message-get, imap-message-map
59 ;; imap-message-envelope-date, imap-message-envelope-subject,
60 ;; imap-message-envelope-from, imap-message-envelope-sender,
61 ;; imap-message-envelope-reply-to, imap-message-envelope-to,
62 ;; imap-message-envelope-cc, imap-message-envelope-bcc
63 ;; imap-message-envelope-in-reply-to, imap-message-envelope-message-id
64 ;; imap-message-body, imap-message-flag-permanent-p
65 ;; imap-message-flags-set, imap-message-flags-del
66 ;; imap-message-flags-add, imap-message-copyuid
67 ;; imap-message-copy, imap-message-appenduid
68 ;; imap-message-append, imap-envelope-from
71 ;; It is my hope that theese commands should be pretty self
72 ;; explanatory for someone that know IMAP. All functions have
73 ;; additional documentation on how to invoke them.
75 ;; imap.el support RFC1730/2060 (IMAP4/IMAP4rev1), implemented IMAP
76 ;; extensions are RFC2195 (CRAM-MD5), RFC2086 (ACL), RFC2342
77 ;; (NAMESPACE), RFC2359 (UIDPLUS), the IMAP-part of RFC2595 (STARTTLS)
78 ;; (with use of external library starttls.el and program starttls) and
79 ;; the GSSAPI / kerberos V4 sections of RFC1731 (with use of external
80 ;; program `imtest'). It also take advantage the UNSELECT extension
83 ;; Without the work of John McClary Prevost and Jim Radford this library
84 ;; would not have seen the light of day. Many thanks.
86 ;; This is a transcript of short interactive session for demonstration
89 ;; (imap-open "my.mail.server")
90 ;; => " *imap* my.mail.server:0"
92 ;; The rest are invoked with current buffer as the buffer returned by
93 ;; `imap-open'. It is possible to do all without this, but it would
94 ;; look ugly here since `buffer' is always the last argument for all
95 ;; imap.el API functions.
97 ;; (imap-authenticate "myusername" "mypassword")
100 ;; (imap-mailbox-lsub "*")
101 ;; => ("INBOX.sentmail" "INBOX.private" "INBOX.draft" "INBOX.spam")
103 ;; (imap-mailbox-list "INBOX.n%")
104 ;; => ("INBOX.namedroppers" "INBOX.nnimap" "INBOX.ntbugtraq")
106 ;; (imap-mailbox-select "INBOX.nnimap")
109 ;; (imap-mailbox-get 'exists)
112 ;; (imap-mailbox-get 'uidvalidity)
115 ;; (imap-search "FLAGGED SINCE 18-DEC-98")
118 ;; (imap-fetch 235 "RFC822.PEEK" 'RFC822)
119 ;; => "X-Sieve: cmu-sieve 1.3^M\nX-Username: <jas@pdc.kth.se>^M\r...."
123 ;; o Parse UIDs as strings? We need to overcome the 28 bit limit somehow.
124 ;; o Don't use `read' at all (important places already fixed)
125 ;; o Accept list of articles instead of message set string in most
126 ;; imap-message-* functions.
130 ;; - 19991218 added starttls/digest-md5 patch,
131 ;; by Daiki Ueno <ueno@ueda.info.waseda.ac.jp>
132 ;; NB! you need SLIM for starttls.el and digest-md5.el
133 ;; - 19991023 commited to pgnus
138 (eval-when-compile (require 'cl))
140 (autoload 'open-ssl-stream "ssl")
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"))
158 (defvar imap-kerberos4-program '("imtest -m kerberos_v4 -u %l -p %p %s"
160 "List of strings containing commands for Kerberos 4 authentication.
161 %s is replaced with server hostname, %p with port to connect to, and
162 %l with the value of `imap-default-user'. The program should accept
163 IMAP commands on stdin and return responses to stdout.")
165 (defvar imap-gssapi-program '("imtest -m gssapi -u %l -p %p %s")
166 "List of strings containing commands for GSSAPI (krb5) authentication.
167 %s is replaced with server hostname, %p with port to connect to, and
168 %l with the value of `imap-default-user'. The program should accept
169 IMAP commands on stdin and return responses to stdout.")
171 (defvar imap-ssl-program '("openssl s_client -ssl3 -connect %s:%p"
172 "openssl s_client -ssl2 -connect %s:%p"
173 "s_client -ssl3 -connect %s:%p"
174 "s_client -ssl2 -connect %s:%p")
175 "A string, or list of strings, containing commands for SSL connections.
176 Within a string, %s is replaced with the server address and %p with
177 port number on server. The program should accept IMAP commands on
178 stdin and return responses to stdout.")
180 (defvar imap-default-user (user-login-name)
181 "Default username to use.")
183 (defvar imap-error nil
184 "Error codes from the last command.")
186 ;; Various variables.
188 (defvar imap-fetch-data-hook nil
189 "Hooks called after receiving each FETCH response.")
191 (defvar imap-streams '(gssapi kerberos4 starttls ssl network)
192 "Priority of streams to consider when opening connection to server.")
194 (defvar imap-stream-alist
195 '((gssapi imap-gssapi-stream-p imap-gssapi-open)
196 (kerberos4 imap-kerberos4-stream-p imap-kerberos4-open)
197 (ssl imap-ssl-p imap-ssl-open)
198 (network imap-network-p imap-network-open)
199 (starttls imap-starttls-p imap-starttls-open))
200 "Definition of network streams.
204 NAME names the stream, CHECK is a function returning non-nil if the
205 server support the stream and OPEN is a function for opening the
208 (defvar imap-authenticators '(gssapi
214 "Priority of authenticators to consider when authenticating to server.")
216 (defvar imap-authenticator-alist
217 '((gssapi imap-gssapi-auth-p imap-gssapia-auth)
218 (kerberos4 imap-kerberos4-auth-p imap-kerberos4-auth)
219 (cram-md5 imap-cram-md5-p imap-cram-md5-auth)
220 (login imap-login-p imap-login-auth)
221 (anonymous imap-anonymous-p imap-anonymous-auth)
222 (digest-md5 imap-digest-md5-p imap-digest-md5-auth))
223 "Definition of authenticators.
225 (NAME CHECK AUTHENTICATE)
227 NAME names the authenticator. CHECK is a function returning non-nil if
228 the server support the authenticator and AUTHENTICATE is a function
229 for doing the actuall authentification.")
231 (defvar imap-use-utf7 t
232 "If non-nil, do utf7 encoding/decoding of mailbox names.
233 Since the UTF7 decoding currently only decodes into ISO-8859-1
234 characters, you may disable this decoding if you need to access UTF7
235 encoded mailboxes which doesn't translate into ISO-8859-1.")
237 ;; Internal constants. Change theese and die.
239 (defconst imap-default-port 143)
240 (defconst imap-default-ssl-port 993)
241 (defconst imap-default-stream 'network)
242 (defconst imap-coding-system-for-read 'binary)
243 (defconst imap-coding-system-for-write 'binary)
244 (defconst imap-local-variables '(imap-server
253 imap-current-target-mailbox
264 ;; Internal variables.
266 (defvar imap-stream nil)
267 (defvar imap-auth nil)
268 (defvar imap-server nil)
269 (defvar imap-port nil)
270 (defvar imap-username nil)
271 (defvar imap-password nil)
272 (defvar imap-state 'closed
274 Valid states are `closed', `initial', `nonauth', `auth', `selected'
277 (defvar imap-server-eol "\r\n"
278 "The EOL string sent from the server.")
280 (defvar imap-client-eol "\r\n"
281 "The EOL string we send to the server.")
283 (defvar imap-current-mailbox nil
284 "Current mailbox name.")
286 (defvar imap-current-target-mailbox nil
287 "Current target mailbox for COPY and APPEND commands.")
289 (defvar imap-mailbox-data nil
290 "Obarray with mailbox data.")
292 (defvar imap-mailbox-prime 997
293 "Length of imap-mailbox-data.")
295 (defvar imap-current-message nil
296 "Current message number.")
298 (defvar imap-message-data nil
299 "Obarray with message data.")
301 (defvar imap-message-prime 997
302 "Length of imap-message-data.")
304 (defvar imap-capability nil
305 "Capability for server.")
307 (defvar imap-namespace nil
308 "Namespace for current server.")
310 (defvar imap-reached-tag 0
311 "Lower limit on command tags that have been parsed.")
313 (defvar imap-failed-tags nil
314 "Alist of tags that failed.
315 Each element is a list with four elements; tag (a integer), response
316 state (a symbol, `OK', `NO' or `BAD'), response code (a string), and
317 human readable response text (a string).")
320 "Command tag number.")
322 (defvar imap-process nil
325 (defvar imap-continuation nil
326 "Non-nil indicates that the server emitted a continuation request.
327 The actually value is really the text on the continuation line.")
330 "Imap session trace.")
332 (defvar imap-debug nil ;"*imap-debug*"
333 "Random debug spew.")
336 ;; Utility functions:
338 (defsubst imap-disable-multibyte ()
339 "Enable multibyte in the current buffer."
340 (when (fboundp 'set-buffer-multibyte)
341 (set-buffer-multibyte nil)))
343 (defun imap-read-passwd (prompt &rest args)
344 "Read a password using PROMPT.
345 If ARGS, PROMPT is used as an argument to `format'."
346 (let ((prompt (if args
347 (apply 'format prompt args)
349 (funcall (if (or (fboundp 'read-passwd)
351 (fboundp 'read-passwd))
352 (and (load "passwd" t)
353 (fboundp 'read-passwd)))
355 (autoload 'ange-ftp-read-passwd "ange-ftp")
356 'ange-ftp-read-passwd)
359 (defsubst imap-utf7-encode (string)
363 (utf7-encode string t)
365 "imap: Could not UTF7 encode `%s', using it unencoded..."
370 (defsubst imap-utf7-decode (string)
374 (utf7-decode string t)
376 "imap: Could not UTF7 decode `%s', using it undecoded..."
381 (defsubst imap-ok-p (status)
384 (setq imap-error status)
387 (defun imap-error-text (&optional buffer)
388 (with-current-buffer (or buffer (current-buffer))
389 (nth 3 (car imap-failed-tags))))
392 ;; Server functions; stream stuff:
394 (defun imap-kerberos4-stream-p (buffer)
395 (imap-capability 'AUTH=KERBEROS_V4 buffer))
397 (defun imap-kerberos4-open (name buffer server port)
398 (let ((cmds imap-kerberos4-program)
400 (while (and (not done) (setq cmd (pop cmds)))
401 (message "Opening Kerberos 4 IMAP connection with `%s'..." cmd)
402 (let* ((port (or port imap-default-port))
403 (coding-system-for-read imap-coding-system-for-read)
404 (coding-system-for-write imap-coding-system-for-write)
405 (process (start-process
406 name buffer shell-file-name shell-command-switch
411 ?p (number-to-string port)
412 ?l imap-default-user))))
415 (with-current-buffer buffer
416 (setq imap-client-eol "\n")
417 (while (and (memq (process-status process) '(open run))
418 (goto-char (point-min))
419 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
420 (or (while (looking-at "^C:")
423 ;; cyrus 1.6 imtest print "S: " before server greeting
424 (or (not (looking-at "S: "))
427 (not (and (imap-parse-greeting)
428 ;; success in imtest < 1.6:
429 (or (re-search-forward
430 "^__\\(.*\\)__\n" nil t)
431 ;; success in imtest 1.6:
433 "^\\(Authenticat.*\\)" nil t))
434 (setq response (match-string 1)))))
435 (accept-process-output process 1)
438 (with-current-buffer (get-buffer-create imap-log)
439 (imap-disable-multibyte)
440 (buffer-disable-undo)
441 (goto-char (point-max))
442 (insert-buffer-substring buffer)))
444 (message "Kerberos 4 IMAP connection: %s" (or response "failed"))
445 (if (and response (let ((case-fold-search nil))
446 (not (string-match "failed" response))))
448 (if (memq (process-status process) '(open run))
449 (imap-send-command-wait "LOGOUT"))
450 (delete-process process)
454 (defun imap-gssapi-stream-p (buffer)
455 (imap-capability 'AUTH=GSSAPI buffer))
457 (defun imap-gssapi-open (name buffer server port)
458 (let ((cmds imap-gssapi-program)
460 (while (and (not done) (setq cmd (pop cmds)))
461 (message "Opening GSSAPI IMAP connection with `%s'..." cmd)
462 (let* ((port (or port imap-default-port))
463 (coding-system-for-read imap-coding-system-for-read)
464 (coding-system-for-write imap-coding-system-for-write)
465 (process (start-process
466 name buffer shell-file-name shell-command-switch
471 ?p (number-to-string port)
472 ?l imap-default-user))))
475 (with-current-buffer buffer
476 (setq imap-client-eol "\n")
477 (while (and (memq (process-status process) '(open run))
478 (goto-char (point-min))
479 ;; cyrus 1.6 imtest print "S: " before server greeting
480 (or (not (looking-at "S: "))
483 (not (and (imap-parse-greeting)
484 ;; success in imtest 1.6:
486 "^\\(Authenticat.*\\)" nil t)
487 (setq response (match-string 1)))))
488 (accept-process-output process 1)
491 (with-current-buffer (get-buffer-create imap-log)
492 (imap-disable-multibyte)
493 (buffer-disable-undo)
494 (goto-char (point-max))
495 (insert-buffer-substring buffer)))
497 (message "GSSAPI IMAP connection: %s" (or response "failed"))
498 (if (and response (let ((case-fold-search nil))
499 (not (string-match "failed" response))))
501 (if (memq (process-status process) '(open run))
502 (imap-send-command-wait "LOGOUT"))
503 (delete-process process)
507 (defun imap-ssl-p (buffer)
510 (defun imap-ssl-open (name buffer server port)
511 "Open a SSL connection to server."
512 (let ((cmds (if (listp imap-ssl-program) imap-ssl-program
513 (list imap-ssl-program)))
515 (while (and (not done) (setq cmd (pop cmds)))
516 (message "imap: Opening SSL connection with `%s'..." cmd)
517 (let* ((port (or port imap-default-ssl-port))
518 (coding-system-for-read imap-coding-system-for-read)
519 (coding-system-for-write imap-coding-system-for-write)
520 (ssl-program-name shell-file-name)
521 (ssl-program-arguments
522 (list shell-command-switch
523 (format-spec cmd (format-spec-make
525 ?p (number-to-string port)))))
527 (when (setq process (ignore-errors (open-ssl-stream
528 name buffer server port)))
529 (with-current-buffer buffer
530 (goto-char (point-min))
531 (while (and (memq (process-status process) '(open run))
532 (goto-char (point-max))
534 (not (imap-parse-greeting)))
535 (accept-process-output process 1)
538 (with-current-buffer (get-buffer-create imap-log)
539 (imap-disable-multibyte)
540 (buffer-disable-undo)
541 (goto-char (point-max))
542 (insert-buffer-substring buffer)))
544 (when (memq (process-status process) '(open run))
545 (setq done process))))))
548 (message "imap: Opening SSL connection with `%s'...done" cmd)
550 (message "imap: Failed opening SSL connection")
553 (defun imap-network-p (buffer)
556 (defun imap-network-open (name buffer server port)
557 (let* ((port (or port imap-default-port))
558 (coding-system-for-read imap-coding-system-for-read)
559 (coding-system-for-write imap-coding-system-for-write)
560 (process (open-network-stream name buffer server port)))
562 (while (and (memq (process-status process) '(open run))
563 (goto-char (point-min))
564 (not (imap-parse-greeting)))
565 (accept-process-output process 1)
568 (with-current-buffer (get-buffer-create imap-log)
569 (imap-disable-multibyte)
570 (buffer-disable-undo)
571 (goto-char (point-max))
572 (insert-buffer-substring buffer)))
573 (when (memq (process-status process) '(open run))
576 (defun imap-starttls-p (buffer)
577 (and (condition-case ()
580 (imap-capability 'STARTTLS buffer)))
582 (defun imap-starttls-open (name buffer server port)
583 (let* ((port (or port imap-default-port))
584 (coding-system-for-read imap-coding-system-for-read)
585 (coding-system-for-write imap-coding-system-for-write)
586 (process (starttls-open-stream name buffer server port)))
588 (while (and (memq (process-status process) '(open run))
589 (goto-char (point-min))
590 (not (imap-parse-greeting)))
591 (accept-process-output process 1)
594 (with-current-buffer (get-buffer-create imap-log)
595 (buffer-disable-undo)
596 (goto-char (point-max))
597 (insert-buffer-substring buffer)))
598 (let ((imap-process process))
601 (set-process-filter imap-process 'imap-arrival-filter)
602 (when (and (eq imap-stream 'starttls)
603 (imap-ok-p (imap-send-command-wait "STARTTLS")))
604 (starttls-negotiate imap-process)))
605 (set-process-filter imap-process nil)))
606 (when (memq (process-status process) '(open run))
609 ;; Server functions; authenticator stuff:
611 (defun imap-interactive-login (buffer loginfunc)
612 "Login to server in BUFFER.
613 LOGINFUNC is passed a username and a password, it should return t if
614 it where sucessful authenticating itself to the server, nil otherwise.
615 Returns t if login was successful, nil otherwise."
616 (with-current-buffer buffer
617 (make-variable-buffer-local 'imap-username)
618 (make-variable-buffer-local 'imap-password)
619 (let (user passwd ret)
620 ;; (condition-case ()
621 (while (or (not user) (not passwd))
622 (setq user (or imap-username
623 (read-from-minibuffer
624 (concat "IMAP username for " imap-server ": ")
625 (or user imap-default-user))))
626 (setq passwd (or imap-password
628 (concat "IMAP password for " user "@"
630 (when (and user passwd)
631 (if (funcall loginfunc user passwd)
635 (if (and (not imap-password)
636 (y-or-n-p "Store password for this session? "))
637 (setq imap-password passwd)))
638 (message "Login failed...")
641 ;; (quit (with-current-buffer buffer
644 ;; (error (with-current-buffer buffer
649 (defun imap-gssapi-auth-p (buffer)
650 (imap-capability 'AUTH=GSSAPI buffer))
652 (defun imap-gssapi-auth (buffer)
653 (eq imap-stream 'gssapi))
655 (defun imap-kerberos4-auth-p (buffer)
656 (imap-capability 'AUTH=KERBEROS_V4 buffer))
658 (defun imap-kerberos4-auth (buffer)
659 (eq imap-stream 'kerberos4))
661 (defun imap-cram-md5-p (buffer)
662 (imap-capability 'AUTH=CRAM-MD5 buffer))
664 (defun imap-cram-md5-auth (buffer)
665 "Login to server using the AUTH CRAM-MD5 method."
666 (imap-interactive-login
668 (lambda (user passwd)
670 (imap-send-command-wait
672 "AUTHENTICATE CRAM-MD5"
674 (let* ((decoded (base64-decode-string challenge))
675 (hash (rfc2104-hash 'md5 64 16 passwd decoded))
676 (response (concat user " " hash))
677 (encoded (base64-encode-string response)))
680 (defun imap-login-p (buffer)
681 (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer)))
683 (defun imap-login-auth (buffer)
684 "Login to server using the LOGIN command."
685 (imap-interactive-login buffer
686 (lambda (user passwd)
687 (imap-ok-p (imap-send-command-wait
688 (concat "LOGIN \"" user "\" \""
691 (defun imap-anonymous-p (buffer)
694 (defun imap-anonymous-auth (buffer)
695 (with-current-buffer buffer
696 (imap-ok-p (imap-send-command-wait
697 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
698 (system-name)) "\"")))))
700 (defun imap-digest-md5-p (buffer)
701 (and (condition-case ()
702 (require 'digest-md5)
704 (imap-capability 'AUTH=DIGEST-MD5 buffer)))
706 (defun imap-digest-md5-auth (buffer)
707 "Login to server using the AUTH DIGEST-MD5 method."
708 (imap-interactive-login
710 (lambda (user passwd)
714 "AUTHENTICATE DIGEST-MD5"
716 (digest-md5-parse-digest-challenge
717 (base64-decode-string challenge))
719 (digest-md5-digest-uri
720 "imap" (digest-md5-challenge 'realm)))
722 (digest-md5-digest-response
723 user passwd digest-uri)))
724 (base64-encode-string response 'no-line-break))))
726 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
728 (setq imap-continuation nil)
729 (imap-send-command-1 "")
730 (imap-ok-p (imap-wait-for-tag tag)))))))
734 (defun imap-open-1 (buffer)
735 (with-current-buffer buffer
737 (setq imap-current-mailbox nil
738 imap-current-message nil
740 imap-process (condition-case ()
741 (funcall (nth 2 (assq imap-stream
743 "imap" buffer imap-server imap-port)
746 (set-process-filter imap-process 'imap-arrival-filter)
747 (set-process-sentinel imap-process 'imap-sentinel)
748 (while (and (eq imap-state 'initial)
749 (memq (process-status imap-process) '(open run)))
750 (message "Waiting for response from %s..." imap-server)
751 (accept-process-output imap-process 1))
752 (message "Waiting for response from %s...done" imap-server)
753 (and (memq (process-status imap-process) '(open run))
756 (defun imap-open (server &optional port stream auth buffer)
757 "Open a IMAP connection to host SERVER at PORT returning a buffer.
758 If PORT is unspecified, a default value is used (143 except
759 for SSL which use 993).
760 STREAM indicates the stream to use, see `imap-streams' for available
761 streams. If nil, it choices the best stream the server is capable of.
762 AUTH indicates authenticator to use, see `imap-authenticators' for
763 available authenticators. If nil, it choices the best stream the
764 server is capable of.
765 BUFFER can be a buffer or a name of a buffer, which is created if
766 necessery. If nil, the buffer name is generated."
767 (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
768 (with-current-buffer (get-buffer-create buffer)
769 (if (imap-opened buffer)
771 (mapcar 'make-variable-buffer-local imap-local-variables)
772 (imap-disable-multibyte)
773 (buffer-disable-undo)
774 (setq imap-server (or server imap-server))
775 (setq imap-port (or port imap-port))
776 (setq imap-auth (or auth imap-auth))
777 (setq imap-stream (or stream imap-stream))
778 (when (let ((imap-stream (or imap-stream imap-default-stream)))
779 (imap-open-1 buffer))
781 (let (stream-changed)
782 (when (null imap-stream)
783 (let ((streams imap-streams))
784 (while (setq stream (pop streams))
785 (if (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
786 (setq stream-changed (not (eq (or imap-stream
792 (error "Couldn't figure out a stream for server"))))
794 (message "Reconnecting with %s..." imap-stream)
797 (setq imap-capability nil)))
798 (if (imap-opened buffer)
799 ;; Choose authenticator
800 (when (null imap-auth)
801 (let ((auths imap-authenticators))
802 (while (setq auth (pop auths))
803 (if (funcall (nth 1 (assq auth imap-authenticator-alist))
808 (error "Couldn't figure out authenticator for server"))))))
809 (when (imap-opened buffer)
810 (setq imap-mailbox-data (make-vector imap-mailbox-prime 0))
813 (defun imap-opened (&optional buffer)
814 "Return non-nil if connection to imap server in BUFFER is open.
815 If BUFFER is nil then the current buffer is used."
816 (and (setq buffer (get-buffer (or buffer (current-buffer))))
817 (buffer-live-p buffer)
818 (with-current-buffer buffer
820 (memq (process-status imap-process) '(open run))))))
822 (defun imap-authenticate (&optional user passwd buffer)
823 "Authenticate to server in BUFFER, using current buffer if nil.
824 It uses the authenticator specified when opening the server. If the
825 authenticator requires username/passwords, they are queried from the
826 user and optionally stored in the buffer. If USER and/or PASSWD is
827 specified, the user will not be questioned and the username and/or
828 password is remembered in the buffer."
829 (with-current-buffer (or buffer (current-buffer))
830 (when (eq imap-state 'nonauth)
831 (make-variable-buffer-local 'imap-username)
832 (make-variable-buffer-local 'imap-password)
833 (if user (setq imap-username user))
834 (if passwd (setq imap-password passwd))
835 (if (funcall (nth 2 (assq imap-auth imap-authenticator-alist)) buffer)
836 (setq imap-state 'auth)))))
838 (defun imap-close (&optional buffer)
839 "Close connection to server in BUFFER.
840 If BUFFER is nil, the current buffer is used."
841 (with-current-buffer (or buffer (current-buffer))
843 (not (imap-ok-p (imap-send-command-wait "LOGOUT")))
844 (message "Server %s didn't let me log out" imap-server))
845 (when (and imap-process
846 (memq (process-status imap-process) '(open run)))
847 (delete-process imap-process))
848 (setq imap-current-mailbox nil
849 imap-current-message nil
854 (defun imap-capability (&optional identifier buffer)
855 "Return a list of identifiers which server in BUFFER support.
856 If IDENTIFIER, return non-nil if it's among the servers capabilities.
857 If BUFFER is nil, the current buffer is assumed."
858 (with-current-buffer (or buffer (current-buffer))
859 (unless imap-capability
860 (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
861 (setq imap-capability '(IMAP2))))
863 (memq (intern (upcase (symbol-name identifier))) imap-capability)
866 (defun imap-namespace (&optional buffer)
867 "Return a namespace hierarchy at server in BUFFER.
868 If BUFFER is nil, the current buffer is assumed."
869 (with-current-buffer (or buffer (current-buffer))
870 (unless imap-namespace
871 (when (imap-capability 'NAMESPACE)
872 (imap-send-command-wait "NAMESPACE")))
875 (defun imap-send-command-wait (command &optional buffer)
876 (imap-wait-for-tag (imap-send-command command buffer) buffer))
879 ;; Mailbox functions:
881 (defun imap-mailbox-put (propname value &optional mailbox buffer)
882 (with-current-buffer (or buffer (current-buffer))
883 (if imap-mailbox-data
884 (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
886 (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
887 propname value mailbox (current-buffer)))
890 (defsubst imap-mailbox-get-1 (propname &optional mailbox)
891 (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
894 (defun imap-mailbox-get (propname &optional mailbox buffer)
895 (let ((mailbox (imap-utf7-encode mailbox)))
896 (with-current-buffer (or buffer (current-buffer))
897 (imap-mailbox-get-1 propname (or mailbox imap-current-mailbox)))))
899 (defun imap-mailbox-map-1 (func &optional mailbox-decoder buffer)
900 (with-current-buffer (or buffer (current-buffer))
904 (push (funcall func (if mailbox-decoder
905 (funcall mailbox-decoder (symbol-name s))
906 (symbol-name s))) result))
910 (defun imap-mailbox-map (func &optional buffer)
911 "Map a function across each mailbox in `imap-mailbox-data', returning a list.
912 Function should take a mailbox name (a string) as
914 (imap-mailbox-map-1 func 'imap-utf7-decode buffer))
916 (defun imap-current-mailbox (&optional buffer)
917 (with-current-buffer (or buffer (current-buffer))
918 (imap-utf7-decode imap-current-mailbox)))
920 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
921 (and (string= mailbox imap-current-mailbox)
923 (eq imap-state 'examine))
925 (eq imap-state 'selected)))))
927 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
928 (with-current-buffer (or buffer (current-buffer))
929 (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
931 (defun imap-mailbox-select-1 (mailbox &optional examine)
932 "Select MAILBOX on server in BUFFER.
933 If EXAMINE is non-nil, do a read-only select."
934 (if (imap-current-mailbox-p-1 mailbox examine)
936 (setq imap-current-mailbox mailbox)
937 (if (imap-ok-p (imap-send-command-wait
938 (concat (if examine "EXAMINE" "SELECT") " \""
941 (setq imap-message-data (make-vector imap-message-prime 0)
942 imap-state (if examine 'examine 'selected))
943 imap-current-mailbox)
944 ;; Failed SELECT/EXAMINE unselects current mailbox
945 (setq imap-current-mailbox nil))))
947 (defun imap-mailbox-select (mailbox &optional examine buffer)
948 (with-current-buffer (or buffer (current-buffer))
950 (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
952 (defun imap-mailbox-examine (mailbox &optional buffer)
953 "Examine MAILBOX on server in BUFFER."
954 (imap-mailbox-select mailbox 'exmine buffer))
956 (defun imap-mailbox-unselect (&optional buffer)
957 "Close current folder in BUFFER, without expunging articles."
958 (with-current-buffer (or buffer (current-buffer))
959 (when (or (eq imap-state 'auth)
960 (and (imap-capability 'UNSELECT)
961 (imap-ok-p (imap-send-command-wait "UNSELECT")))
963 (imap-send-command-wait (concat "EXAMINE \""
966 (imap-ok-p (imap-send-command-wait "CLOSE"))))
967 (setq imap-current-mailbox nil
968 imap-message-data nil
972 (defun imap-mailbox-expunge (&optional buffer)
973 "Expunge articles in current folder in BUFFER.
974 If BUFFER is nil the current buffer is assumed."
975 (with-current-buffer (or buffer (current-buffer))
976 (when (and imap-current-mailbox (not (eq imap-state 'examine)))
977 (imap-ok-p (imap-send-command-wait "EXPUNGE")))))
979 (defun imap-mailbox-close (&optional buffer)
980 "Expunge articles and close current folder in BUFFER.
981 If BUFFER is nil the current buffer is assumed."
982 (with-current-buffer (or buffer (current-buffer))
983 (when (and imap-current-mailbox
984 (imap-ok-p (imap-send-command-wait "CLOSE")))
985 (setq imap-current-mailbox nil
986 imap-message-data nil
990 (defun imap-mailbox-create-1 (mailbox)
991 (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
993 (defun imap-mailbox-create (mailbox &optional buffer)
994 "Create MAILBOX on server in BUFFER.
995 If BUFFER is nil the current buffer is assumed."
996 (with-current-buffer (or buffer (current-buffer))
997 (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
999 (defun imap-mailbox-delete (mailbox &optional buffer)
1000 "Delete MAILBOX on server in BUFFER.
1001 If BUFFER is nil the current buffer is assumed."
1002 (let ((mailbox (imap-utf7-encode mailbox)))
1003 (with-current-buffer (or buffer (current-buffer))
1005 (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1007 (defun imap-mailbox-rename (oldname newname &optional buffer)
1008 "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1009 If BUFFER is nil the current buffer is assumed."
1010 (let ((oldname (imap-utf7-encode oldname))
1011 (newname (imap-utf7-encode newname)))
1012 (with-current-buffer (or buffer (current-buffer))
1014 (imap-send-command-wait (list "RENAME \"" oldname "\" "
1015 "\"" newname "\""))))))
1017 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1018 "Return a list of subscribed mailboxes on server in BUFFER.
1019 If ROOT is non-nil, only list matching mailboxes. If ADD-DELIMITER is
1020 non-nil, a hierarchy delimiter is added to root. REFERENCE is a
1021 implementation-specific string that has to be passed to lsub command."
1022 (with-current-buffer (or buffer (current-buffer))
1023 ;; Make sure we know the hierarchy separator for root's hierarchy
1024 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1025 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1026 (imap-utf7-encode root) "\"")))
1027 ;; clear list data (NB not delimiter and other stuff)
1028 (imap-mailbox-map-1 (lambda (mailbox)
1029 (imap-mailbox-put 'lsub nil mailbox)))
1031 (imap-send-command-wait
1032 (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1033 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1036 (imap-mailbox-map-1 (lambda (mailbox)
1037 (when (imap-mailbox-get-1 'lsub mailbox)
1038 (push (imap-utf7-decode mailbox) out))))
1041 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1042 "Return a list of mailboxes matching ROOT on server in BUFFER.
1043 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1044 root. REFERENCE is a implementation-specific string that has to be
1045 passed to list command."
1046 (with-current-buffer (or buffer (current-buffer))
1047 ;; Make sure we know the hierarchy separator for root's hierarchy
1048 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1049 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1050 (imap-utf7-encode root) "\"")))
1051 ;; clear list data (NB not delimiter and other stuff)
1052 (imap-mailbox-map-1 (lambda (mailbox)
1053 (imap-mailbox-put 'list nil mailbox)))
1055 (imap-send-command-wait
1056 (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1057 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1060 (imap-mailbox-map-1 (lambda (mailbox)
1061 (when (imap-mailbox-get-1 'list mailbox)
1062 (push (imap-utf7-decode mailbox) out))))
1065 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1066 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1067 Returns non-nil if successful."
1068 (with-current-buffer (or buffer (current-buffer))
1069 (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1070 (imap-utf7-encode mailbox)
1073 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1074 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1075 Returns non-nil if successful."
1076 (with-current-buffer (or buffer (current-buffer))
1077 (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1078 (imap-utf7-encode mailbox)
1081 (defun imap-mailbox-status (mailbox items &optional buffer)
1082 "Get status items ITEM in MAILBOX from server in BUFFER.
1083 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1084 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1085 or 'unseen. If ITEMS is a list of symbols, a list of values is
1086 returned, if ITEMS is a symbol only it's value is returned."
1087 (with-current-buffer (or buffer (current-buffer))
1089 (imap-send-command-wait (list "STATUS \""
1090 (imap-utf7-encode mailbox)
1097 (mapcar (lambda (item)
1098 (imap-mailbox-get item mailbox))
1100 (imap-mailbox-get items mailbox)))))
1102 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1103 "Get ACL on mailbox from server in BUFFER."
1104 (let ((mailbox (imap-utf7-encode mailbox)))
1105 (with-current-buffer (or buffer (current-buffer))
1107 (imap-send-command-wait (list "GETACL \""
1108 (or mailbox imap-current-mailbox)
1110 (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1112 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1113 "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
1114 (let ((mailbox (imap-utf7-encode mailbox)))
1115 (with-current-buffer (or buffer (current-buffer))
1117 (imap-send-command-wait (list "SETACL \""
1118 (or mailbox imap-current-mailbox)
1124 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1125 "Removes any <identifier,rights> pair for IDENTIFIER in MAILBOX from server in BUFFER."
1126 (let ((mailbox (imap-utf7-encode mailbox)))
1127 (with-current-buffer (or buffer (current-buffer))
1129 (imap-send-command-wait (list "DELETEACL \""
1130 (or mailbox imap-current-mailbox)
1135 ;; Message functions:
1137 (defun imap-current-message (&optional buffer)
1138 (with-current-buffer (or buffer (current-buffer))
1139 imap-current-message))
1141 (defun imap-list-to-message-set (list)
1142 (mapconcat (lambda (item)
1143 (number-to-string item))
1149 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1150 (with-current-buffer (or buffer (current-buffer))
1151 (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1153 (imap-list-to-message-set uids)
1157 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1158 "Fetch properties PROPS from message set UIDS from server in BUFFER.
1159 UIDS can be a string, number or a list of numbers. If RECEIVE
1160 is non-nil return theese properties."
1161 (with-current-buffer (or buffer (current-buffer))
1162 (when (imap-ok-p (imap-send-command-wait
1163 (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1165 (imap-list-to-message-set uids)
1168 (if (or (null receive) (stringp uids))
1171 (mapcar (lambda (uid)
1173 (mapcar (lambda (prop)
1174 (imap-message-get uid prop))
1176 (imap-message-get uid receive)))
1178 (imap-message-get uids receive))))))
1180 (defun imap-message-put (uid propname value &optional buffer)
1181 (with-current-buffer (or buffer (current-buffer))
1182 (if imap-message-data
1183 (put (intern (number-to-string uid) imap-message-data)
1185 (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1186 uid propname value (current-buffer)))
1189 (defun imap-message-get (uid propname &optional buffer)
1190 (with-current-buffer (or buffer (current-buffer))
1191 (get (intern-soft (number-to-string uid) imap-message-data)
1194 (defun imap-message-map (func propname &optional buffer)
1195 "Map a function across each mailbox in `imap-message-data', returning a list."
1196 (with-current-buffer (or buffer (current-buffer))
1200 (push (funcall func (get s 'UID) (get s propname)) result))
1204 (defmacro imap-message-envelope-date (uid &optional buffer)
1205 `(with-current-buffer (or ,buffer (current-buffer))
1206 (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1208 (defmacro imap-message-envelope-subject (uid &optional buffer)
1209 `(with-current-buffer (or ,buffer (current-buffer))
1210 (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1212 (defmacro imap-message-envelope-from (uid &optional buffer)
1213 `(with-current-buffer (or ,buffer (current-buffer))
1214 (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1216 (defmacro imap-message-envelope-sender (uid &optional buffer)
1217 `(with-current-buffer (or ,buffer (current-buffer))
1218 (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1220 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1221 `(with-current-buffer (or ,buffer (current-buffer))
1222 (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1224 (defmacro imap-message-envelope-to (uid &optional buffer)
1225 `(with-current-buffer (or ,buffer (current-buffer))
1226 (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1228 (defmacro imap-message-envelope-cc (uid &optional buffer)
1229 `(with-current-buffer (or ,buffer (current-buffer))
1230 (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1232 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1233 `(with-current-buffer (or ,buffer (current-buffer))
1234 (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1236 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1237 `(with-current-buffer (or ,buffer (current-buffer))
1238 (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1240 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1241 `(with-current-buffer (or ,buffer (current-buffer))
1242 (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1244 (defmacro imap-message-body (uid &optional buffer)
1245 `(with-current-buffer (or ,buffer (current-buffer))
1246 (imap-message-get ,uid 'BODY)))
1248 (defun imap-search (predicate &optional buffer)
1249 (with-current-buffer (or buffer (current-buffer))
1250 (imap-mailbox-put 'search 'dummy)
1251 (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1252 (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1253 (error "Missing SEARCH response to a SEARCH command")
1254 (imap-mailbox-get-1 'search imap-current-mailbox)))))
1256 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1257 "Return t iff FLAG can be permanently (between IMAP sessions) saved on articles, in MAILBOX on server in BUFFER."
1258 (with-current-buffer (or buffer (current-buffer))
1259 (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1260 (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1262 (defun imap-message-flags-set (articles flags &optional silent buffer)
1263 (when (and articles flags)
1264 (with-current-buffer (or buffer (current-buffer))
1265 (imap-ok-p (imap-send-command-wait
1266 (concat "UID STORE " articles
1267 " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1269 (defun imap-message-flags-del (articles flags &optional silent buffer)
1270 (when (and articles flags)
1271 (with-current-buffer (or buffer (current-buffer))
1272 (imap-ok-p (imap-send-command-wait
1273 (concat "UID STORE " articles
1274 " -FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1276 (defun imap-message-flags-add (articles flags &optional silent buffer)
1277 (when (and articles flags)
1278 (with-current-buffer (or buffer (current-buffer))
1279 (imap-ok-p (imap-send-command-wait
1280 (concat "UID STORE " articles
1281 " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1283 (defun imap-message-copyuid-1 (mailbox)
1284 (if (imap-capability 'UIDPLUS)
1285 (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1286 (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1287 (let ((old-mailbox imap-current-mailbox)
1289 (imap-message-data (make-vector 2 0)))
1290 (when (imap-mailbox-examine mailbox)
1292 (and (imap-fetch "*" "UID")
1293 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1294 (apply 'max (imap-message-map
1295 (lambda (uid prop) uid) 'UID))))
1297 (imap-mailbox-select old-mailbox (eq state 'examine))
1298 (imap-mailbox-unselect)))))))
1300 (defun imap-message-copyuid (mailbox &optional buffer)
1301 (with-current-buffer (or buffer (current-buffer))
1302 (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1304 (defun imap-message-copy (articles mailbox
1305 &optional dont-create no-copyuid buffer)
1306 "Copy ARTICLES (a string message set) to MAILBOX on server in
1307 BUFFER, creating mailbox if it doesn't exist. If dont-create is
1308 non-nil, it will not create a mailbox. On success, return a list with
1309 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1310 first element, rest of list contain the saved articles' UIDs."
1312 (with-current-buffer (or buffer (current-buffer))
1313 (let ((mailbox (imap-utf7-encode mailbox)))
1314 (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1315 (imap-current-target-mailbox mailbox))
1316 (if (imap-ok-p (imap-send-command-wait cmd))
1318 (when (and (not dont-create)
1319 (imap-mailbox-get-1 'trycreate mailbox))
1320 (imap-mailbox-create-1 mailbox)
1321 (imap-ok-p (imap-send-command-wait cmd)))))
1323 (imap-message-copyuid-1 mailbox)))))))
1325 (defun imap-message-appenduid-1 (mailbox)
1326 (if (imap-capability 'UIDPLUS)
1327 (imap-mailbox-get-1 'appenduid mailbox)
1328 (let ((old-mailbox imap-current-mailbox)
1330 (imap-message-data (make-vector 2 0)))
1331 (when (imap-mailbox-examine mailbox)
1333 (and (imap-fetch "*" "UID")
1334 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1335 (apply 'max (imap-message-map
1336 (lambda (uid prop) uid) 'UID))))
1338 (imap-mailbox-select old-mailbox (eq state 'examine))
1339 (imap-mailbox-unselect)))))))
1341 (defun imap-message-appenduid (mailbox &optional buffer)
1342 (with-current-buffer (or buffer (current-buffer))
1343 (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1345 (defun imap-message-append (mailbox article &optional flags date-time buffer)
1346 "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1347 FLAGS and DATE-TIME is currently not used. Return a cons holding
1348 uidvalidity of MAILBOX and UID the newly created article got, or nil
1350 (let ((mailbox (imap-utf7-encode mailbox)))
1351 (with-current-buffer (or buffer (current-buffer))
1352 (and (let ((imap-current-target-mailbox mailbox))
1354 (imap-send-command-wait
1355 (list "APPEND \"" mailbox "\" " article))))
1356 (imap-message-appenduid-1 mailbox)))))
1358 (defun imap-body-lines (body)
1359 "Return number of lines in article by looking at the mime bodystructure BODY."
1361 (if (stringp (car body))
1362 ;; upcase for bug in courier imap server
1363 (cond ((and (string= (upcase (car body)) "TEXT")
1364 (numberp (nth 7 body)))
1366 ((and (string= (upcase (car body)) "MESSAGE")
1367 (numberp (nth 9 body)))
1370 (apply '+ (mapcar 'imap-body-lines body)))
1373 (defun imap-envelope-from (from)
1374 "Return a from string line."
1376 (concat (aref from 0)
1377 (if (aref from 0) " <")
1381 (if (aref from 0) ">"))))
1384 ;; Internal functions.
1386 (defun imap-send-command-1 (cmdstr)
1387 (setq cmdstr (concat cmdstr imap-client-eol))
1389 (with-current-buffer (get-buffer-create imap-log)
1390 (imap-disable-multibyte)
1391 (buffer-disable-undo)
1392 (goto-char (point-max))
1394 (process-send-string imap-process cmdstr))
1396 (defun imap-send-command (command &optional buffer)
1397 (with-current-buffer (or buffer (current-buffer))
1398 (if (not (listp command)) (setq command (list command)))
1399 (let ((tag (setq imap-tag (1+ imap-tag)))
1401 (setq cmdstr (concat (number-to-string imap-tag) " "))
1402 (while (setq cmd (pop command))
1403 (cond ((stringp cmd)
1404 (setq cmdstr (concat cmdstr cmd)))
1407 (concat cmdstr (format "{%d}" (with-current-buffer cmd
1411 (imap-send-command-1 cmdstr)
1413 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1414 (setq command nil);; abort command if no cont-req
1415 (let ((process imap-process)
1416 (stream imap-stream)
1417 (eol imap-client-eol))
1418 (with-current-buffer cmd
1419 (when (not (equal eol "\r\n"))
1420 ;; XXX modifies buffer!
1421 (goto-char (point-min))
1422 (while (search-forward "\r\n" nil t)
1423 (replace-match eol)))
1425 (with-current-buffer (get-buffer-create
1427 (imap-disable-multibyte)
1428 (buffer-disable-undo)
1429 (goto-char (point-max))
1430 (insert-buffer-substring cmd)))
1431 (process-send-region process (point-min)
1433 (process-send-string process imap-client-eol))))
1434 (setq imap-continuation nil)))
1436 (imap-send-command-1 cmdstr)
1439 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1440 (setq command nil);; abort command if no cont-req
1441 (setq command (cons (funcall cmd imap-continuation)
1443 (setq imap-continuation nil)))
1445 (error "Unknown command type"))))
1447 (imap-send-command-1 cmdstr))
1450 (defun imap-wait-for-tag (tag &optional buffer)
1451 (with-current-buffer (or buffer (current-buffer))
1452 (while (and (null imap-continuation)
1453 (< imap-reached-tag tag))
1454 (or (and (not (memq (process-status imap-process) '(open run)))
1456 (accept-process-output imap-process 1)))
1457 (or (assq tag imap-failed-tags)
1458 (if imap-continuation
1462 (defun imap-sentinel (process string)
1463 (delete-process process))
1465 (defun imap-find-next-line ()
1466 "Return point at end of current line, taking into account literals.
1467 Return nil if no complete line has arrived."
1468 (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
1471 (if (match-string 1)
1472 (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1474 (goto-char (+ (point) (string-to-number (match-string 1))))
1475 (imap-find-next-line))
1478 (defun imap-arrival-filter (proc string)
1479 "IMAP process filter."
1480 (with-current-buffer (process-buffer proc)
1481 (goto-char (point-max))
1484 (with-current-buffer (get-buffer-create imap-log)
1485 (imap-disable-multibyte)
1486 (buffer-disable-undo)
1487 (goto-char (point-max))
1490 (goto-char (point-min))
1491 (while (setq end (imap-find-next-line))
1493 (narrow-to-region (point-min) end)
1494 (delete-backward-char (length imap-server-eol))
1495 (goto-char (point-min))
1497 (cond ((eq imap-state 'initial)
1498 (imap-parse-greeting))
1499 ((or (eq imap-state 'auth)
1500 (eq imap-state 'nonauth)
1501 (eq imap-state 'selected)
1502 (eq imap-state 'examine))
1503 (imap-parse-response))
1505 (message "Unknown state %s in arrival filter"
1507 (delete-region (point-min) (point-max))))))))
1512 (defsubst imap-forward ()
1513 (or (eobp) (forward-char)))
1516 ;; ; Unsigned 32-bit integer
1517 ;; ; (0 <= n < 4,294,967,296)
1519 (defsubst imap-parse-number ()
1520 (when (looking-at "[0-9]+")
1522 (string-to-number (match-string 0))
1523 (goto-char (match-end 0)))))
1525 ;; literal = "{" number "}" CRLF *CHAR8
1526 ;; ; Number represents the number of CHAR8s
1528 (defsubst imap-parse-literal ()
1529 (when (looking-at "{\\([0-9]+\\)}\r\n")
1530 (let ((pos (match-end 0))
1531 (len (string-to-number (match-string 1))))
1532 (if (< (point-max) (+ pos len))
1534 (goto-char (+ pos len))
1535 (buffer-substring pos (+ pos len))))))
1537 ;; string = quoted / literal
1539 ;; quoted = DQUOTE *QUOTED-CHAR DQUOTE
1541 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
1542 ;; "\" quoted-specials
1544 ;; quoted-specials = DQUOTE / "\"
1546 ;; TEXT-CHAR = <any CHAR except CR and LF>
1548 (defsubst imap-parse-string ()
1549 (cond ((eq (char-after) ?\")
1551 (let ((p (point)) (name ""))
1552 (skip-chars-forward "^\"\\\\")
1553 (setq name (buffer-substring p (point)))
1554 (while (eq (char-after) ?\\)
1555 (setq p (1+ (point)))
1557 (skip-chars-forward "^\"\\\\")
1558 (setq name (concat name (buffer-substring p (point)))))
1561 ((eq (char-after) ?{)
1562 (imap-parse-literal))))
1566 (defsubst imap-parse-nil ()
1567 (if (looking-at "NIL")
1568 (goto-char (match-end 0))))
1570 ;; nstring = string / nil
1572 (defsubst imap-parse-nstring ()
1573 (or (imap-parse-string)
1574 (and (imap-parse-nil)
1577 ;; astring = atom / string
1579 ;; atom = 1*ATOM-CHAR
1581 ;; ATOM-CHAR = <any CHAR except atom-specials>
1583 ;; atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards /
1586 ;; list-wildcards = "%" / "*"
1588 ;; quoted-specials = DQUOTE / "\"
1590 (defsubst imap-parse-astring ()
1591 (or (imap-parse-string)
1592 (buffer-substring (point)
1593 (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
1594 (goto-char (1- (match-end 0)))
1598 ;; address = "(" addr-name SP addr-adl SP addr-mailbox SP
1601 ;; addr-adl = nstring
1602 ;; ; Holds route from [RFC-822] route-addr if
1605 ;; addr-host = nstring
1606 ;; ; NIL indicates [RFC-822] group syntax.
1607 ;; ; Otherwise, holds [RFC-822] domain name
1609 ;; addr-mailbox = nstring
1610 ;; ; NIL indicates end of [RFC-822] group; if
1611 ;; ; non-NIL and addr-host is NIL, holds
1612 ;; ; [RFC-822] group name.
1613 ;; ; Otherwise, holds [RFC-822] local-part
1614 ;; ; after removing [RFC-822] quoting
1616 ;; addr-name = nstring
1617 ;; ; If non-NIL, holds phrase from [RFC-822]
1618 ;; ; mailbox after removing [RFC-822] quoting
1621 (defsubst imap-parse-address ()
1623 (when (eq (char-after) ?\()
1625 (setq address (vector (prog1 (imap-parse-nstring)
1627 (prog1 (imap-parse-nstring)
1629 (prog1 (imap-parse-nstring)
1631 (imap-parse-nstring)))
1632 (when (eq (char-after) ?\))
1636 ;; address-list = "(" 1*address ")" / nil
1640 (defsubst imap-parse-address-list ()
1641 (if (eq (char-after) ?\()
1642 (let (address addresses)
1644 (while (and (not (eq (char-after) ?\)))
1645 ;; next line for MS Exchange bug
1646 (progn (and (eq (char-after) ? ) (imap-forward)) t)
1647 (setq address (imap-parse-address)))
1648 (setq addresses (cons address addresses)))
1649 (when (eq (char-after) ?\))
1651 (nreverse addresses)))
1652 (assert (imap-parse-nil))))
1654 ;; mailbox = "INBOX" / astring
1655 ;; ; INBOX is case-insensitive. All case variants of
1656 ;; ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
1657 ;; ; not as an astring. An astring which consists of
1658 ;; ; the case-insensitive sequence "I" "N" "B" "O" "X"
1659 ;; ; is considered to be INBOX and not an astring.
1660 ;; ; Refer to section 5.1 for further
1661 ;; ; semantic details of mailbox names.
1663 (defsubst imap-parse-mailbox ()
1664 (let ((mailbox (imap-parse-astring)))
1665 (if (string-equal "INBOX" (upcase mailbox))
1669 ;; greeting = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
1671 ;; resp-cond-auth = ("OK" / "PREAUTH") SP resp-text
1672 ;; ; Authentication condition
1674 ;; resp-cond-bye = "BYE" SP resp-text
1676 (defun imap-parse-greeting ()
1677 "Parse a IMAP greeting."
1678 (cond ((looking-at "\\* OK ")
1679 (setq imap-state 'nonauth))
1680 ((looking-at "\\* PREAUTH ")
1681 (setq imap-state 'auth))
1682 ((looking-at "\\* BYE ")
1683 (setq imap-state 'closed))))
1685 ;; response = *(continue-req / response-data) response-done
1687 ;; continue-req = "+" SP (resp-text / base64) CRLF
1689 ;; response-data = "*" SP (resp-cond-state / resp-cond-bye /
1690 ;; mailbox-data / message-data / capability-data) CRLF
1692 ;; response-done = response-tagged / response-fatal
1694 ;; response-fatal = "*" SP resp-cond-bye CRLF
1695 ;; ; Server closes connection immediately
1697 ;; response-tagged = tag SP resp-cond-state CRLF
1699 ;; resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
1700 ;; ; Status condition
1702 ;; resp-cond-bye = "BYE" SP resp-text
1704 ;; mailbox-data = "FLAGS" SP flag-list /
1705 ;; "LIST" SP mailbox-list /
1706 ;; "LSUB" SP mailbox-list /
1707 ;; "SEARCH" *(SP nz-number) /
1708 ;; "STATUS" SP mailbox SP "("
1709 ;; [status-att SP number *(SP status-att SP number)] ")" /
1710 ;; number SP "EXISTS" /
1711 ;; number SP "RECENT"
1713 ;; message-data = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
1715 ;; capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
1717 ;; ; IMAP4rev1 servers which offer RFC 1730
1718 ;; ; compatibility MUST list "IMAP4" as the first
1721 (defun imap-parse-response ()
1722 "Parse a IMAP command response."
1724 (case (setq token (read (current-buffer)))
1725 (+ (setq imap-continuation
1726 (or (buffer-substring (min (point-max) (1+ (point)))
1729 (* (case (prog1 (setq token (read (current-buffer)))
1731 (OK (imap-parse-resp-text))
1732 (NO (imap-parse-resp-text))
1733 (BAD (imap-parse-resp-text))
1734 (BYE (imap-parse-resp-text))
1735 (FLAGS (imap-mailbox-put 'flags (imap-parse-flag-list)))
1736 (LIST (imap-parse-data-list 'list))
1737 (LSUB (imap-parse-data-list 'lsub))
1738 (SEARCH (imap-mailbox-put
1740 (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
1741 (STATUS (imap-parse-status))
1742 (CAPABILITY (setq imap-capability
1743 (read (concat "(" (upcase (buffer-substring
1744 (point) (point-max)))
1746 (ACL (imap-parse-acl))
1747 (t (case (prog1 (read (current-buffer))
1749 (EXISTS (imap-mailbox-put 'exists token))
1750 (RECENT (imap-mailbox-put 'recent token))
1752 (FETCH (imap-parse-fetch token))
1753 (t (message "Garbage: %s" (buffer-string)))))))
1755 (if (not (integerp token))
1756 (message "Garbage: %s" (buffer-string))
1757 (case (prog1 (setq status (read (current-buffer)))
1760 (setq imap-reached-tag (max imap-reached-tag token))
1761 (imap-parse-resp-text)))
1763 (setq imap-reached-tag (max imap-reached-tag token))
1765 (imap-parse-resp-text))
1767 (when (eq (char-after) ?\[)
1768 (setq code (buffer-substring (point)
1769 (search-forward "]")))
1771 (setq text (buffer-substring (point) (point-max)))
1772 (push (list token status code text)
1773 imap-failed-tags))))
1775 (setq imap-reached-tag (max imap-reached-tag token))
1777 (imap-parse-resp-text))
1779 (when (eq (char-after) ?\[)
1780 (setq code (buffer-substring (point)
1781 (search-forward "]")))
1783 (setq text (buffer-substring (point) (point-max)))
1784 (push (list token status code text) imap-failed-tags)
1785 (error "Internal error, tag %s status %s code %s text %s"
1786 token status code text))))
1787 (t (message "Garbage: %s" (buffer-string))))))))))
1789 ;; resp-text = ["[" resp-text-code "]" SP] text
1791 ;; text = 1*TEXT-CHAR
1793 ;; TEXT-CHAR = <any CHAR except CR and LF>
1795 (defun imap-parse-resp-text ()
1796 (imap-parse-resp-text-code))
1798 ;; resp-text-code = "ALERT" /
1799 ;; "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
1800 ;; "NEWNAME" SP string SP string /
1802 ;; "PERMANENTFLAGS" SP "("
1803 ;; [flag-perm *(SP flag-perm)] ")" /
1807 ;; "UIDNEXT" SP nz-number /
1808 ;; "UIDVALIDITY" SP nz-number /
1809 ;; "UNSEEN" SP nz-number /
1810 ;; resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
1812 ;; resp_code_apnd = "APPENDUID" SPACE nz_number SPACE uniqueid
1814 ;; resp_code_copy = "COPYUID" SPACE nz_number SPACE set SPACE set
1816 ;; set = sequence-num / (sequence-num ":" sequence-num) /
1818 ;; ; Identifies a set of messages. For message
1819 ;; ; sequence numbers, these are consecutive
1820 ;; ; numbers from 1 to the number of messages in
1822 ;; ; Comma delimits individual numbers, colon
1823 ;; ; delimits between two numbers inclusive.
1824 ;; ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
1825 ;; ; 14,15 for a mailbox with 15 messages.
1827 ;; sequence-num = nz-number / "*"
1828 ;; ; * is the largest number in use. For message
1829 ;; ; sequence numbers, it is the number of messages
1830 ;; ; in the mailbox. For unique identifiers, it is
1831 ;; ; the unique identifier of the last message in
1834 ;; flag-perm = flag / "\*"
1836 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
1837 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
1838 ;; ; Does not include "\Recent"
1840 ;; flag-extension = "\" atom
1841 ;; ; Future expansion. Client implementations
1842 ;; ; MUST accept flag-extension flags. Server
1843 ;; ; implementations MUST NOT generate
1844 ;; ; flag-extension flags except as defined by
1845 ;; ; future standard or standards-track
1846 ;; ; revisions of this specification.
1848 ;; flag-keyword = atom
1850 ;; resp-text-atom = 1*<any ATOM-CHAR except "]">
1852 (defun imap-parse-resp-text-code ()
1853 (when (eq (char-after) ?\[)
1855 (cond ((search-forward "PERMANENTFLAGS " nil t)
1856 (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
1857 ((search-forward "UIDNEXT " nil t)
1858 (imap-mailbox-put 'uidnext (read (current-buffer))))
1859 ((search-forward "UNSEEN " nil t)
1860 (imap-mailbox-put 'unseen (read (current-buffer))))
1861 ((looking-at "UIDVALIDITY \\([0-9]+\\)")
1862 (imap-mailbox-put 'uidvalidity (match-string 1)))
1863 ((search-forward "READ-ONLY" nil t)
1864 (imap-mailbox-put 'read-only t))
1865 ((search-forward "NEWNAME " nil t)
1866 (let (oldname newname)
1867 (setq oldname (imap-parse-string))
1869 (setq newname (imap-parse-string))
1870 (imap-mailbox-put 'newname newname oldname)))
1871 ((search-forward "TRYCREATE" nil t)
1872 (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
1873 ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
1874 (imap-mailbox-put 'appenduid
1875 (list (match-string 1)
1876 (string-to-number (match-string 2)))
1877 imap-current-target-mailbox))
1878 ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
1879 (imap-mailbox-put 'copyuid (list (match-string 1)
1882 imap-current-target-mailbox))
1883 ((search-forward "ALERT] " nil t)
1884 (message "Imap server %s information: %s" imap-server
1885 (buffer-substring (point) (point-max)))))))
1887 ;; mailbox-list = "(" [mbx-list-flags] ")" SP
1888 ;; (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
1890 ;; mbx-list-flags = *(mbx-list-oflag SP) mbx-list-sflag
1891 ;; *(SP mbx-list-oflag) /
1892 ;; mbx-list-oflag *(SP mbx-list-oflag)
1894 ;; mbx-list-oflag = "\Noinferiors" / flag-extension
1895 ;; ; Other flags; multiple possible per LIST response
1897 ;; mbx-list-sflag = "\Noselect" / "\Marked" / "\Unmarked"
1898 ;; ; Selectability flags; only one per LIST response
1900 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
1901 ;; "\" quoted-specials
1903 ;; quoted-specials = DQUOTE / "\"
1905 (defun imap-parse-data-list (type)
1906 (let (flags delimiter mailbox)
1907 (setq flags (imap-parse-flag-list))
1908 (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
1909 (setq delimiter (match-string 1))
1910 (goto-char (1+ (match-end 0)))
1911 (when (setq mailbox (imap-parse-mailbox))
1912 (imap-mailbox-put type t mailbox)
1913 (imap-mailbox-put 'list-flags flags mailbox)
1914 (imap-mailbox-put 'delimiter delimiter mailbox)))))
1916 ;; msg_att ::= "(" 1#("ENVELOPE" SPACE envelope /
1917 ;; "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
1918 ;; "INTERNALDATE" SPACE date_time /
1919 ;; "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
1920 ;; "RFC822.SIZE" SPACE number /
1921 ;; "BODY" ["STRUCTURE"] SPACE body /
1922 ;; "BODY" section ["<" number ">"] SPACE nstring /
1923 ;; "UID" SPACE uniqueid) ")"
1925 ;; date_time ::= <"> date_day_fixed "-" date_month "-" date_year
1926 ;; SPACE time SPACE zone <">
1928 ;; section ::= "[" [section_text / (nz_number *["." nz_number]
1929 ;; ["." (section_text / "MIME")])] "]"
1931 ;; section_text ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
1932 ;; SPACE header_list / "TEXT"
1934 ;; header_fld_name ::= astring
1936 ;; header_list ::= "(" 1#header_fld_name ")"
1938 (defsubst imap-parse-header-list ()
1939 (when (eq (char-after) ?\()
1941 (while (not (eq (char-after) ?\)))
1943 (push (imap-parse-astring) strlist))
1945 (nreverse strlist))))
1947 (defsubst imap-parse-fetch-body-section ()
1949 (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
1950 (if (eq (char-before) ? )
1952 (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
1953 (search-forward "]" nil t))
1956 (defun imap-parse-fetch (response)
1957 (when (eq (char-after) ?\()
1958 (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
1959 rfc822size body bodydetail bodystructure)
1960 (while (not (eq (char-after) ?\)))
1962 (let ((token (read (current-buffer))))
1964 (cond ((eq token 'UID)
1965 (setq uid (ignore-errors (read (current-buffer)))))
1967 (setq flags (imap-parse-flag-list)))
1968 ((eq token 'ENVELOPE)
1969 (setq envelope (imap-parse-envelope)))
1970 ((eq token 'INTERNALDATE)
1971 (setq internaldate (imap-parse-string)))
1973 (setq rfc822 (imap-parse-nstring)))
1974 ((eq token 'RFC822.HEADER)
1975 (setq rfc822header (imap-parse-nstring)))
1976 ((eq token 'RFC822.TEXT)
1977 (setq rfc822text (imap-parse-nstring)))
1978 ((eq token 'RFC822.SIZE)
1979 (setq rfc822size (read (current-buffer))))
1981 (if (eq (char-before) ?\[)
1983 (upcase (imap-parse-fetch-body-section))
1984 (and (eq (char-after) ?<)
1985 (buffer-substring (1+ (point))
1986 (search-forward ">" nil t)))
1987 (progn (imap-forward)
1988 (imap-parse-nstring)))
1990 (setq body (imap-parse-body))))
1991 ((eq token 'BODYSTRUCTURE)
1992 (setq bodystructure (imap-parse-body))))))
1994 (setq imap-current-message uid)
1995 (imap-message-put uid 'UID uid)
1996 (and flags (imap-message-put uid 'FLAGS flags))
1997 (and envelope (imap-message-put uid 'ENVELOPE envelope))
1998 (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
1999 (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2000 (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2001 (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2002 (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2003 (and body (imap-message-put uid 'BODY body))
2004 (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2005 (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2006 (run-hooks 'imap-fetch-data-hook)))))
2008 ;; mailbox-data = ...
2009 ;; "STATUS" SP mailbox SP "("
2010 ;; [status-att SP number
2011 ;; *(SP status-att SP number)] ")"
2014 ;; status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2017 (defun imap-parse-status ()
2018 (let ((mailbox (imap-parse-mailbox)))
2019 (when (and mailbox (search-forward "(" nil t))
2020 (while (not (eq (char-after) ?\)))
2021 (let ((token (read (current-buffer))))
2022 (cond ((eq token 'MESSAGES)
2023 (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2025 (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2026 ((eq token 'UIDNEXT)
2027 (imap-mailbox-put 'uidnext (read (current-buffer)) mailbox))
2028 ((eq token 'UIDVALIDITY)
2029 (and (looking-at " \\([0-9]+\\)")
2030 (imap-mailbox-put 'uidvalidity (match-string 1) mailbox)
2031 (goto-char (match-end 1))))
2033 (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2035 (message "Unknown status data %s in mailbox %s ignored"
2036 token mailbox))))))))
2038 ;; acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2041 ;; identifier ::= astring
2043 ;; rights ::= astring
2045 (defun imap-parse-acl ()
2046 (let ((mailbox (imap-parse-mailbox))
2047 identifier rights acl)
2048 (while (eq (char-after) ?\ )
2050 (setq identifier (imap-parse-astring))
2052 (setq rights (imap-parse-astring))
2053 (setq acl (append acl (list (cons identifier rights)))))
2054 (imap-mailbox-put 'acl acl mailbox)))
2056 ;; flag-list = "(" [flag *(SP flag)] ")"
2058 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2059 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2060 ;; ; Does not include "\Recent"
2062 ;; flag-keyword = atom
2064 ;; flag-extension = "\" atom
2065 ;; ; Future expansion. Client implementations
2066 ;; ; MUST accept flag-extension flags. Server
2067 ;; ; implementations MUST NOT generate
2068 ;; ; flag-extension flags except as defined by
2069 ;; ; future standard or standards-track
2070 ;; ; revisions of this specification.
2072 (defun imap-parse-flag-list ()
2073 (let ((str (buffer-substring (point) (search-forward ")" nil t)))
2075 (while (setq pos (string-match "\\\\" str (and pos (+ 2 pos))))
2076 (setq str (replace-match "\\\\" nil t str)))
2077 (mapcar 'symbol-name (read str))))
2079 ;; envelope = "(" env-date SP env-subject SP env-from SP env-sender SP
2080 ;; env-reply-to SP env-to SP env-cc SP env-bcc SP
2081 ;; env-in-reply-to SP env-message-id ")"
2083 ;; env-bcc = "(" 1*address ")" / nil
2085 ;; env-cc = "(" 1*address ")" / nil
2087 ;; env-date = nstring
2089 ;; env-from = "(" 1*address ")" / nil
2091 ;; env-in-reply-to = nstring
2093 ;; env-message-id = nstring
2095 ;; env-reply-to = "(" 1*address ")" / nil
2097 ;; env-sender = "(" 1*address ")" / nil
2099 ;; env-subject = nstring
2101 ;; env-to = "(" 1*address ")" / nil
2103 (defun imap-parse-envelope ()
2104 (when (eq (char-after) ?\()
2106 (vector (prog1 (imap-parse-nstring);; date
2108 (prog1 (imap-parse-nstring);; subject
2110 (prog1 (imap-parse-address-list);; from
2112 (prog1 (imap-parse-address-list);; sender
2114 (prog1 (imap-parse-address-list);; reply-to
2116 (prog1 (imap-parse-address-list);; to
2118 (prog1 (imap-parse-address-list);; cc
2120 (prog1 (imap-parse-address-list);; bcc
2122 (prog1 (imap-parse-nstring);; in-reply-to
2124 (prog1 (imap-parse-nstring);; message-id
2127 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2129 (defsubst imap-parse-string-list ()
2130 (cond ((eq (char-after) ?\();; body-fld-param
2133 (while (setq str (imap-parse-string))
2136 (nreverse strlist)))
2140 ;; body-extension = nstring / number /
2141 ;; "(" body-extension *(SP body-extension) ")"
2142 ;; ; Future expansion. Client implementations
2143 ;; ; MUST accept body-extension fields. Server
2144 ;; ; implementations MUST NOT generate
2145 ;; ; body-extension fields except as defined by
2146 ;; ; future standard or standards-track
2147 ;; ; revisions of this specification.
2149 (defun imap-parse-body-extension ()
2150 (if (eq (char-after) ?\()
2153 (push (imap-parse-body-extension) b-e)
2154 (while (eq (char-after) ?\ )
2156 (push (imap-parse-body-extension) b-e))
2157 (assert (eq (char-after) ?\)))
2160 (or (imap-parse-number)
2161 (imap-parse-nstring))))
2163 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2164 ;; *(SP body-extension)]]
2165 ;; ; MUST NOT be returned on non-extensible
2168 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2169 ;; *(SP body-extension)]]
2170 ;; ; MUST NOT be returned on non-extensible
2173 (defsubst imap-parse-body-ext ()
2175 (when (eq (char-after) ?\ );; body-fld-dsp
2178 (if (eq (char-after) ?\()
2181 (push (imap-parse-string) dsp)
2183 (push (imap-parse-string-list) dsp)
2185 (assert (imap-parse-nil)))
2186 (push (nreverse dsp) ext))
2187 (when (eq (char-after) ?\ );; body-fld-lang
2189 (if (eq (char-after) ?\()
2190 (push (imap-parse-string-list) ext)
2191 (push (imap-parse-nstring) ext))
2192 (while (eq (char-after) ?\ );; body-extension
2194 (setq ext (append (imap-parse-body-extension) ext)))))
2197 ;; body = "(" body-type-1part / body-type-mpart ")"
2199 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2200 ;; *(SP body-extension)]]
2201 ;; ; MUST NOT be returned on non-extensible
2204 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2205 ;; *(SP body-extension)]]
2206 ;; ; MUST NOT be returned on non-extensible
2209 ;; body-fields = body-fld-param SP body-fld-id SP body-fld-desc SP
2210 ;; body-fld-enc SP body-fld-octets
2212 ;; body-fld-desc = nstring
2214 ;; body-fld-dsp = "(" string SP body-fld-param ")" / nil
2216 ;; body-fld-enc = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2217 ;; "QUOTED-PRINTABLE") DQUOTE) / string
2219 ;; body-fld-id = nstring
2221 ;; body-fld-lang = nstring / "(" string *(SP string) ")"
2223 ;; body-fld-lines = number
2225 ;; body-fld-md5 = nstring
2227 ;; body-fld-octets = number
2229 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2231 ;; body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2232 ;; [SP body-ext-1part]
2234 ;; body-type-basic = media-basic SP body-fields
2235 ;; ; MESSAGE subtype MUST NOT be "RFC822"
2237 ;; body-type-msg = media-message SP body-fields SP envelope
2238 ;; SP body SP body-fld-lines
2240 ;; body-type-text = media-text SP body-fields SP body-fld-lines
2242 ;; body-type-mpart = 1*body SP media-subtype
2243 ;; [SP body-ext-mpart]
2245 ;; media-basic = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2246 ;; "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2247 ;; ; Defined in [MIME-IMT]
2249 ;; media-message = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2250 ;; ; Defined in [MIME-IMT]
2252 ;; media-subtype = string
2253 ;; ; Defined in [MIME-IMT]
2255 ;; media-text = DQUOTE "TEXT" DQUOTE SP media-subtype
2256 ;; ; Defined in [MIME-IMT]
2258 (defun imap-parse-body ()
2260 (when (eq (char-after) ?\()
2262 (if (eq (char-after) ?\()
2264 (while (and (eq (char-after) ?\()
2265 (setq subbody (imap-parse-body)))
2266 (push subbody body))
2268 (push (imap-parse-string) body);; media-subtype
2269 (when (eq (char-after) ?\ );; body-ext-mpart:
2271 (if (eq (char-after) ?\();; body-fld-param
2272 (push (imap-parse-string-list) body)
2273 (push (and (imap-parse-nil) nil) body))
2275 (append (imap-parse-body-ext) body)));; body-ext-...
2276 (assert (eq (char-after) ?\)))
2280 (push (imap-parse-string) body);; media-type
2282 (push (imap-parse-string) body);; media-subtype
2284 ;; next line for Sun SIMS bug
2285 (and (eq (char-after) ? ) (imap-forward))
2286 (if (eq (char-after) ?\();; body-fld-param
2287 (push (imap-parse-string-list) body)
2288 (push (and (imap-parse-nil) nil) body))
2290 (push (imap-parse-nstring) body);; body-fld-id
2292 (push (imap-parse-nstring) body);; body-fld-desc
2294 (push (imap-parse-string) body);; body-fld-enc
2296 (push (imap-parse-number) body);; body-fld-octets
2298 ;; ok, we're done parsing the required parts, what comes now is one
2301 ;; envelope (then we're parsing body-type-msg)
2302 ;; body-fld-lines (then we're parsing body-type-text)
2303 ;; body-ext-1part (then we're parsing body-type-basic)
2305 ;; the problem is that the two first are in turn optionally followed
2306 ;; by the third. So we parse the first two here (if there are any)...
2308 (when (eq (char-after) ?\ )
2311 (cond ((eq (char-after) ?\();; body-type-msg:
2312 (push (imap-parse-envelope) body);; envelope
2314 (push (imap-parse-body) body);; body
2316 (push (imap-parse-number) body));; body-fld-lines
2317 ((setq lines (imap-parse-number));; body-type-text:
2318 (push lines body));; body-fld-lines
2320 (backward-char)))));; no match...
2322 ;; ...and then parse the third one here...
2324 (when (eq (char-after) ?\ );; body-ext-1part:
2326 (push (imap-parse-nstring) body);; body-fld-md5
2327 (setq body (append (imap-parse-body-ext) body)));; body-ext-1part..
2329 (assert (eq (char-after) ?\)))
2333 (when imap-debug ; (untrace-all)
2335 (buffer-disable-undo (get-buffer-create imap-debug))
2336 (mapcar (lambda (f) (trace-function-background f imap-debug))
2348 imap-interactive-login
2364 imap-send-command-wait
2369 imap-current-mailbox
2370 imap-current-mailbox-p-1
2371 imap-current-mailbox-p
2372 imap-mailbox-select-1
2374 imap-mailbox-examine
2375 imap-mailbox-unselect
2376 imap-mailbox-expunge
2378 imap-mailbox-create-1
2384 imap-mailbox-subscribe
2385 imap-mailbox-unsubscribe
2387 imap-mailbox-acl-get
2388 imap-mailbox-acl-set
2389 imap-mailbox-acl-delete
2390 imap-current-message
2391 imap-list-to-message-set
2398 imap-message-flag-permanent-p
2399 imap-message-flags-set
2400 imap-message-flags-del
2401 imap-message-flags-add
2402 imap-message-copyuid-1
2403 imap-message-copyuid
2405 imap-message-appenduid-1
2406 imap-message-appenduid
2418 imap-parse-resp-text
2419 imap-parse-resp-text-code
2420 imap-parse-data-list
2424 imap-parse-flag-list
2426 imap-parse-body-extension
2432 ;;; imap.el ends here