1 ;;; imap.el --- imap library
2 ;; Copyright (C) 1998, 1999, 2000
3 ;; Free Software Foundation, Inc.
5 ;; Author: Simon Josefsson <jas@pdc.kth.se>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
27 ;; imap.el is a elisp library providing an interface for talking to
30 ;; imap.el is roughly divided in two parts, one that parses IMAP
31 ;; responses from the server and storing data into buffer-local
32 ;; variables, and one for utility functions which send commands to
33 ;; server, waits for an answer, and return information. The latter
34 ;; part is layered on top of the previous.
36 ;; The imap.el API consist of the following functions, other functions
37 ;; in this file should not be called directly and the result of doing
38 ;; so are at best undefined.
42 ;; imap-open, imap-opened, imap-authenticate, imap-close,
43 ;; imap-capability, imap-namespace, imap-error-text
47 ;; imap-mailbox-get, imap-mailbox-map, imap-current-mailbox,
48 ;; imap-current-mailbox-p, imap-search, imap-mailbox-select,
49 ;; imap-mailbox-examine, imap-mailbox-unselect, imap-mailbox-expunge
50 ;; imap-mailbox-close, imap-mailbox-create, imap-mailbox-delete
51 ;; imap-mailbox-rename, imap-mailbox-lsub, imap-mailbox-list
52 ;; imap-mailbox-subscribe, imap-mailbox-unsubscribe, imap-mailbox-status
53 ;; imap-mailbox-acl-get, imap-mailbox-acl-set, imap-mailbox-acl-delete
57 ;; imap-fetch-asynch, imap-fetch,
58 ;; imap-current-message, imap-list-to-message-set,
59 ;; imap-message-get, imap-message-map
60 ;; imap-message-envelope-date, imap-message-envelope-subject,
61 ;; imap-message-envelope-from, imap-message-envelope-sender,
62 ;; imap-message-envelope-reply-to, imap-message-envelope-to,
63 ;; imap-message-envelope-cc, imap-message-envelope-bcc
64 ;; imap-message-envelope-in-reply-to, imap-message-envelope-message-id
65 ;; imap-message-body, imap-message-flag-permanent-p
66 ;; imap-message-flags-set, imap-message-flags-del
67 ;; imap-message-flags-add, imap-message-copyuid
68 ;; imap-message-copy, imap-message-appenduid
69 ;; imap-message-append, imap-envelope-from
72 ;; It is my hope that theese commands should be pretty self
73 ;; explanatory for someone that know IMAP. All functions have
74 ;; additional documentation on how to invoke them.
76 ;; imap.el support RFC1730/2060 (IMAP4/IMAP4rev1), implemented IMAP
77 ;; extensions are RFC2195 (CRAM-MD5), RFC2086 (ACL), RFC2342
78 ;; (NAMESPACE), RFC2359 (UIDPLUS), the IMAP-part of RFC2595 (STARTTLS,
79 ;; LOGINDISABLED) (with use of external library starttls.el and
80 ;; program starttls) and the GSSAPI / kerberos V4 sections of RFC1731
81 ;; (with use of external program `imtest'). It also take advantage
82 ;; the UNSELECT extension in Cyrus IMAPD.
84 ;; Without the work of John McClary Prevost and Jim Radford this library
85 ;; would not have seen the light of day. Many thanks.
87 ;; This is a transcript of short interactive session for demonstration
90 ;; (imap-open "my.mail.server")
91 ;; => " *imap* my.mail.server:0"
93 ;; The rest are invoked with current buffer as the buffer returned by
94 ;; `imap-open'. It is possible to do all without this, but it would
95 ;; look ugly here since `buffer' is always the last argument for all
96 ;; imap.el API functions.
98 ;; (imap-authenticate "myusername" "mypassword")
101 ;; (imap-mailbox-lsub "*")
102 ;; => ("INBOX.sentmail" "INBOX.private" "INBOX.draft" "INBOX.spam")
104 ;; (imap-mailbox-list "INBOX.n%")
105 ;; => ("INBOX.namedroppers" "INBOX.nnimap" "INBOX.ntbugtraq")
107 ;; (imap-mailbox-select "INBOX.nnimap")
110 ;; (imap-mailbox-get 'exists)
113 ;; (imap-mailbox-get 'uidvalidity)
116 ;; (imap-search "FLAGGED SINCE 18-DEC-98")
119 ;; (imap-fetch 235 "RFC822.PEEK" 'RFC822)
120 ;; => "X-Sieve: cmu-sieve 1.3^M\nX-Username: <jas@pdc.kth.se>^M\r...."
124 ;; o Parse UIDs as strings? We need to overcome the 28 bit limit somehow.
125 ;; o Don't use `read' at all (important places already fixed)
126 ;; o Accept list of articles instead of message set string in most
127 ;; imap-message-* functions.
131 ;; - 19991218 added starttls/digest-md5 patch,
132 ;; by Daiki Ueno <ueno@ueda.info.waseda.ac.jp>
133 ;; NB! you need SLIM for starttls.el and digest-md5.el
134 ;; - 19991023 commited to pgnus
139 (eval-when-compile (require 'cl))
141 (autoload 'open-ssl-stream "ssl")
142 (autoload 'base64-decode-string "base64")
143 (autoload 'base64-encode-string "base64")
144 (autoload 'starttls-open-stream "starttls")
145 (autoload 'starttls-negotiate "starttls")
146 (autoload 'digest-md5-parse-digest-challenge "digest-md5")
147 (autoload 'digest-md5-digest-response "digest-md5")
148 (autoload 'digest-md5-digest-uri "digest-md5")
149 (autoload 'digest-md5-challenge "digest-md5")
150 (autoload 'rfc2104-hash "rfc2104")
151 (autoload 'md5 "md5")
152 (autoload 'utf7-encode "utf7")
153 (autoload 'utf7-decode "utf7")
154 (autoload 'format-spec "format-spec")
155 (autoload 'format-spec-make "format-spec")
156 ;; Avoid use gnus-point-at-eol so we're independent of Gnus. These
157 ;; days we have point-at-eol anyhow.
158 (if (fboundp 'point-at-eol)
159 (defalias 'imap-point-at-eol 'point-at-eol)
160 (defun imap-point-at-eol ()
168 "Low-level IMAP issues."
172 (defcustom imap-kerberos4-program '("imtest -m kerberos_v4 -u %l -p %p %s"
174 "List of strings containing commands for Kerberos 4 authentication.
175 %s is replaced with server hostname, %p with port to connect to, and
176 %l with the value of `imap-default-user'. The program should accept
177 IMAP commands on stdin and return responses to stdout. Each entry in
178 the list is tried until a successful connection is made."
180 :type '(repeat string))
182 (defcustom imap-gssapi-program '("imtest -m gssapi -u %l -p %p %s")
183 "List of strings containing commands for GSSAPI (krb5) authentication.
184 %s is replaced with server hostname, %p with port to connect to, and
185 %l with the value of `imap-default-user'. The program should accept
186 IMAP commands on stdin and return responses to stdout. Each entry in
187 the list is tried until a successful connection is made."
189 :type '(repeat string))
191 (defcustom imap-ssl-program '("openssl s_client -quiet -ssl3 -connect %s:%p"
192 "openssl s_client -quiet -ssl2 -connect %s:%p"
193 "s_client -quiet -ssl3 -connect %s:%p"
194 "s_client -quiet -ssl2 -connect %s:%p")
195 "A string, or list of strings, containing commands for SSL connections.
196 Within a string, %s is replaced with the server address and %p with
197 port number on server. The program should accept IMAP commands on
198 stdin and return responses to stdout. Each entry in the list is tried
199 until a successful connection is made."
201 :type '(choice string
204 (defcustom imap-shell-program '("ssh %s imapd"
206 "ssh %g ssh %s imapd"
207 "rsh %g rsh %s imapd")
208 "A list of strings, containing commands for IMAP connection.
209 Within a string, %s is replaced with the server address, %p with port
210 number on server, %g with `imap-shell-host', and %l with
211 `imap-default-user'. The program should read IMAP commands from stdin
212 and write IMAP response to stdout. Each entry in the list is tried
213 until a successful connection is made."
215 :type '(repeat string))
217 (defcustom imap-process-connection-type nil
218 "*Value for `process-connection-type' to use for Kerberos4 and GSSAPI."
222 (defvar imap-shell-host "gateway"
223 "Hostname of rlogin proxy.")
225 (defvar imap-default-user (user-login-name)
226 "Default username to use.")
228 (defvar imap-error nil
229 "Error codes from the last command.")
231 ;; Various variables.
233 (defvar imap-fetch-data-hook nil
234 "Hooks called after receiving each FETCH response.")
236 (defvar imap-streams '(gssapi kerberos4 starttls ssl network shell)
237 "Priority of streams to consider when opening connection to server.")
239 (defvar imap-stream-alist
240 '((gssapi imap-gssapi-stream-p imap-gssapi-open)
241 (kerberos4 imap-kerberos4-stream-p imap-kerberos4-open)
242 (ssl imap-ssl-p imap-ssl-open)
243 (network imap-network-p imap-network-open)
244 (shell imap-shell-p imap-shell-open)
245 (starttls imap-starttls-p imap-starttls-open))
246 "Definition of network streams.
250 NAME names the stream, CHECK is a function returning non-nil if the
251 server support the stream and OPEN is a function for opening the
254 (defvar imap-authenticators '(gssapi
260 "Priority of authenticators to consider when authenticating to server.")
262 (defvar imap-authenticator-alist
263 '((gssapi imap-gssapi-auth-p imap-gssapi-auth)
264 (kerberos4 imap-kerberos4-auth-p imap-kerberos4-auth)
265 (cram-md5 imap-cram-md5-p imap-cram-md5-auth)
266 (login imap-login-p imap-login-auth)
267 (anonymous imap-anonymous-p imap-anonymous-auth)
268 (digest-md5 imap-digest-md5-p imap-digest-md5-auth))
269 "Definition of authenticators.
271 (NAME CHECK AUTHENTICATE)
273 NAME names the authenticator. CHECK is a function returning non-nil if
274 the server support the authenticator and AUTHENTICATE is a function
275 for doing the actuall authentification.")
277 (defvar imap-use-utf7 t
278 "If non-nil, do utf7 encoding/decoding of mailbox names.
279 Since the UTF7 decoding currently only decodes into ISO-8859-1
280 characters, you may disable this decoding if you need to access UTF7
281 encoded mailboxes which doesn't translate into ISO-8859-1.")
283 ;; Internal constants. Change theese and die.
285 (defconst imap-default-port 143)
286 (defconst imap-default-ssl-port 993)
287 (defconst imap-default-stream 'network)
288 (defconst imap-coding-system-for-read 'binary)
289 (defconst imap-coding-system-for-write 'binary)
290 (defconst imap-local-variables '(imap-server
299 imap-current-target-mailbox
308 imap-calculate-literal-size-first
311 ;; Internal variables.
313 (defvar imap-stream nil)
314 (defvar imap-auth nil)
315 (defvar imap-server nil)
316 (defvar imap-port nil)
317 (defvar imap-username nil)
318 (defvar imap-password nil)
319 (defvar imap-calculate-literal-size-first nil)
320 (defvar imap-state 'closed
322 Valid states are `closed', `initial', `nonauth', `auth', `selected'
325 (defvar imap-server-eol "\r\n"
326 "The EOL string sent from the server.")
328 (defvar imap-client-eol "\r\n"
329 "The EOL string we send to the server.")
331 (defvar imap-current-mailbox nil
332 "Current mailbox name.")
334 (defvar imap-current-target-mailbox nil
335 "Current target mailbox for COPY and APPEND commands.")
337 (defvar imap-mailbox-data nil
338 "Obarray with mailbox data.")
340 (defvar imap-mailbox-prime 997
341 "Length of imap-mailbox-data.")
343 (defvar imap-current-message nil
344 "Current message number.")
346 (defvar imap-message-data nil
347 "Obarray with message data.")
349 (defvar imap-message-prime 997
350 "Length of imap-message-data.")
352 (defvar imap-capability nil
353 "Capability for server.")
355 (defvar imap-namespace nil
356 "Namespace for current server.")
358 (defvar imap-reached-tag 0
359 "Lower limit on command tags that have been parsed.")
361 (defvar imap-failed-tags nil
362 "Alist of tags that failed.
363 Each element is a list with four elements; tag (a integer), response
364 state (a symbol, `OK', `NO' or `BAD'), response code (a string), and
365 human readable response text (a string).")
368 "Command tag number.")
370 (defvar imap-process nil
373 (defvar imap-continuation nil
374 "Non-nil indicates that the server emitted a continuation request.
375 The actually value is really the text on the continuation line.")
378 "Name of buffer for imap session trace.
379 For example: (setq imap-log \"*imap-log*\")")
381 (defvar imap-debug nil ;"*imap-debug*"
382 "Name of buffer for random debug spew.
383 For example: (setq imap-debug \"*imap-debug*\")")
386 ;; Utility functions:
388 (defsubst imap-disable-multibyte ()
389 "Enable multibyte in the current buffer."
390 (when (fboundp 'set-buffer-multibyte)
391 (set-buffer-multibyte nil)))
393 (defun imap-read-passwd (prompt &rest args)
394 "Read a password using PROMPT.
395 If ARGS, PROMPT is used as an argument to `format'."
396 (let ((prompt (if args
397 (apply 'format prompt args)
399 (funcall (if (or (fboundp 'read-passwd)
401 (fboundp 'read-passwd))
402 (and (load "passwd" t)
403 (fboundp 'read-passwd)))
405 (autoload 'ange-ftp-read-passwd "ange-ftp")
406 'ange-ftp-read-passwd)
409 (defsubst imap-utf7-encode (string)
413 (utf7-encode string t)
415 "imap: Could not UTF7 encode `%s', using it unencoded..."
420 (defsubst imap-utf7-decode (string)
424 (utf7-decode string t)
426 "imap: Could not UTF7 decode `%s', using it undecoded..."
431 (defsubst imap-ok-p (status)
434 (setq imap-error status)
437 (defun imap-error-text (&optional buffer)
438 (with-current-buffer (or buffer (current-buffer))
439 (nth 3 (car imap-failed-tags))))
442 ;; Server functions; stream stuff:
444 (defun imap-kerberos4-stream-p (buffer)
445 (imap-capability 'AUTH=KERBEROS_V4 buffer))
447 (defun imap-kerberos4-open (name buffer server port)
448 (let ((cmds imap-kerberos4-program)
450 (while (and (not done) (setq cmd (pop cmds)))
451 (message "Opening Kerberos 4 IMAP connection with `%s'..." cmd)
453 (let* ((port (or port imap-default-port))
454 (coding-system-for-read imap-coding-system-for-read)
455 (coding-system-for-write imap-coding-system-for-write)
456 (process-connection-type imap-process-connection-type)
457 (process (start-process
458 name buffer shell-file-name shell-command-switch
463 ?p (number-to-string port)
464 ?l imap-default-user))))
467 (with-current-buffer buffer
468 (setq imap-client-eol "\n"
469 imap-calculate-literal-size-first t)
470 (while (and (memq (process-status process) '(open run))
471 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
472 (goto-char (point-min))
473 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
474 (or (while (looking-at "^C:")
477 ;; cyrus 1.6 imtest print "S: " before server greeting
478 (or (not (looking-at "S: "))
481 (not (and (imap-parse-greeting)
482 ;; success in imtest < 1.6:
483 (or (re-search-forward
484 "^__\\(.*\\)__\n" nil t)
485 ;; success in imtest 1.6:
487 "^\\(Authenticat.*\\)" nil t))
488 (setq response (match-string 1)))))
489 (accept-process-output process 1)
492 (with-current-buffer (get-buffer-create imap-log)
493 (imap-disable-multibyte)
494 (buffer-disable-undo)
495 (goto-char (point-max))
496 (insert-buffer-substring buffer)))
498 (message "Opening Kerberos 4 IMAP connection with `%s'...%s" cmd
499 (if response (concat "done, " response) "failed"))
500 (if (and response (let ((case-fold-search nil))
501 (not (string-match "failed" response))))
503 (if (memq (process-status process) '(open run))
504 (imap-send-command-wait "LOGOUT"))
505 (delete-process process)
509 (defun imap-gssapi-stream-p (buffer)
510 (imap-capability 'AUTH=GSSAPI buffer))
512 (defun imap-gssapi-open (name buffer server port)
513 (let ((cmds imap-gssapi-program)
515 (while (and (not done) (setq cmd (pop cmds)))
516 (message "Opening GSSAPI IMAP connection with `%s'..." cmd)
517 (let* ((port (or port imap-default-port))
518 (coding-system-for-read imap-coding-system-for-read)
519 (coding-system-for-write imap-coding-system-for-write)
520 (process-connection-type imap-process-connection-type)
521 (process (start-process
522 name buffer shell-file-name shell-command-switch
527 ?p (number-to-string port)
528 ?l imap-default-user))))
531 (with-current-buffer buffer
532 (setq imap-client-eol "\n"
533 imap-calculate-literal-size-first t)
534 (while (and (memq (process-status process) '(open run))
535 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
536 (goto-char (point-min))
537 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
538 (or (while (looking-at "^C:")
541 ;; cyrus 1.6 imtest print "S: " before server greeting
542 (or (not (looking-at "S: "))
545 (not (and (imap-parse-greeting)
546 ;; success in imtest 1.6:
548 "^\\(Authenticat.*\\)" nil t)
549 (setq response (match-string 1)))))
550 (accept-process-output process 1)
553 (with-current-buffer (get-buffer-create imap-log)
554 (imap-disable-multibyte)
555 (buffer-disable-undo)
556 (goto-char (point-max))
557 (insert-buffer-substring buffer)))
559 (message "GSSAPI IMAP connection: %s" (or response "failed"))
560 (if (and response (let ((case-fold-search nil))
561 (not (string-match "failed" response))))
563 (if (memq (process-status process) '(open run))
564 (imap-send-command-wait "LOGOUT"))
565 (delete-process process)
569 (defun imap-ssl-p (buffer)
572 (defun imap-ssl-open (name buffer server port)
573 "Open a SSL connection to server."
574 (let ((cmds (if (listp imap-ssl-program) imap-ssl-program
575 (list imap-ssl-program)))
577 (ignore-errors (require 'ssl))
578 (while (and (not done) (setq cmd (pop cmds)))
579 (message "imap: Opening SSL connection with `%s'..." cmd)
580 (let* ((port (or port imap-default-ssl-port))
581 (coding-system-for-read imap-coding-system-for-read)
582 (coding-system-for-write imap-coding-system-for-write)
583 (ssl-program-name shell-file-name)
584 (ssl-program-arguments
585 (list shell-command-switch
586 (format-spec cmd (format-spec-make
588 ?p (number-to-string port)))))
590 (when (setq process (ignore-errors (open-ssl-stream
591 name buffer server port)))
592 (with-current-buffer buffer
593 (goto-char (point-min))
594 (while (and (memq (process-status process) '(open run))
595 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
596 (goto-char (point-max))
598 (not (imap-parse-greeting)))
599 (accept-process-output process 1)
602 (with-current-buffer (get-buffer-create imap-log)
603 (imap-disable-multibyte)
604 (buffer-disable-undo)
605 (goto-char (point-max))
606 (insert-buffer-substring buffer)))
608 (when (memq (process-status process) '(open run))
609 (setq done process))))))
612 (message "imap: Opening SSL connection with `%s'...done" cmd)
614 (message "imap: Opening SSL connection with `%s'...failed" cmd)
617 (defun imap-network-p (buffer)
620 (defun imap-network-open (name buffer server port)
621 (let* ((port (or port imap-default-port))
622 (coding-system-for-read imap-coding-system-for-read)
623 (coding-system-for-write imap-coding-system-for-write)
624 (process (open-network-stream name buffer server port)))
626 (while (and (memq (process-status process) '(open run))
627 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
628 (goto-char (point-min))
629 (not (imap-parse-greeting)))
630 (accept-process-output process 1)
633 (with-current-buffer (get-buffer-create imap-log)
634 (imap-disable-multibyte)
635 (buffer-disable-undo)
636 (goto-char (point-max))
637 (insert-buffer-substring buffer)))
638 (when (memq (process-status process) '(open run))
641 (defun imap-shell-p (buffer)
644 (defun imap-shell-open (name buffer server port)
645 (let ((cmds imap-shell-program)
647 (while (and (not done) (setq cmd (pop cmds)))
648 (message "imap: Opening IMAP connection with `%s'..." cmd)
649 (setq imap-client-eol "\n")
650 (let* ((port (or port imap-default-port))
651 (coding-system-for-read imap-coding-system-for-read)
652 (coding-system-for-write imap-coding-system-for-write)
653 (process (start-process
654 name buffer shell-file-name shell-command-switch
660 ?p (number-to-string port)
661 ?l imap-default-user)))))
663 (while (and (memq (process-status process) '(open run))
664 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
665 (goto-char (point-min))
666 (not (imap-parse-greeting)))
667 (accept-process-output process 1)
670 (with-current-buffer (get-buffer-create imap-log)
671 (imap-disable-multibyte)
672 (buffer-disable-undo)
673 (goto-char (point-max))
674 (insert-buffer-substring buffer)))
676 (when (memq (process-status process) '(open run))
677 (setq done process)))))
680 (message "imap: Opening IMAP connection with `%s'...done" cmd)
682 (message "imap: Opening IMAP connection with `%s'...failed" cmd)
685 (defun imap-starttls-p (buffer)
686 (and (imap-capability 'STARTTLS buffer)
690 (call-process "starttls"))
693 (defun imap-starttls-open (name buffer server port)
694 (let* ((port (or port imap-default-port))
695 (coding-system-for-read imap-coding-system-for-read)
696 (coding-system-for-write imap-coding-system-for-write)
697 (process (starttls-open-stream name buffer server port))
699 (message "imap: Connecting with STARTTLS...")
701 (while (and (memq (process-status process) '(open run))
702 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
703 (goto-char (point-min))
704 (not (imap-parse-greeting)))
705 (accept-process-output process 1)
708 (with-current-buffer (get-buffer-create imap-log)
709 (buffer-disable-undo)
710 (goto-char (point-max))
711 (insert-buffer-substring buffer)))
712 (let ((imap-process process))
715 (set-process-filter imap-process 'imap-arrival-filter)
716 (when (and (eq imap-stream 'starttls)
717 (imap-ok-p (imap-send-command-wait "STARTTLS")))
718 (starttls-negotiate imap-process)))
719 (set-process-filter imap-process nil)))
720 (when (memq (process-status process) '(open run))
721 (setq done process)))
724 (message "imap: Connecting with STARTTLS...done")
726 (message "imap: Connecting with STARTTLS...failed")
729 ;; Server functions; authenticator stuff:
731 (defun imap-interactive-login (buffer loginfunc)
732 "Login to server in BUFFER.
733 LOGINFUNC is passed a username and a password, it should return t if
734 it where sucessful authenticating itself to the server, nil otherwise.
735 Returns t if login was successful, nil otherwise."
736 (with-current-buffer buffer
737 (make-local-variable 'imap-username)
738 (make-local-variable 'imap-password)
739 (let (user passwd ret)
740 ;; (condition-case ()
741 (while (or (not user) (not passwd))
742 (setq user (or imap-username
743 (read-from-minibuffer
744 (concat "IMAP username for " imap-server ": ")
745 (or user imap-default-user))))
746 (setq passwd (or imap-password
748 (concat "IMAP password for " user "@"
750 (when (and user passwd)
751 (if (funcall loginfunc user passwd)
755 (if (and (not imap-password)
756 (y-or-n-p "Store password for this session? "))
757 (setq imap-password passwd)))
758 (message "Login failed...")
761 ;; (quit (with-current-buffer buffer
764 ;; (error (with-current-buffer buffer
769 (defun imap-gssapi-auth-p (buffer)
770 (imap-capability 'AUTH=GSSAPI buffer))
772 (defun imap-gssapi-auth (buffer)
773 (message "imap: Authenticating using GSSAPI...%s"
774 (if (eq imap-stream 'gssapi) "done" "failed"))
775 (eq imap-stream 'gssapi))
777 (defun imap-kerberos4-auth-p (buffer)
778 (imap-capability 'AUTH=KERBEROS_V4 buffer))
780 (defun imap-kerberos4-auth (buffer)
781 (message "imap: Authenticating using Kerberos 4...%s"
782 (if (eq imap-stream 'kerberos4) "done" "failed"))
783 (eq imap-stream 'kerberos4))
785 (defun imap-cram-md5-p (buffer)
786 (imap-capability 'AUTH=CRAM-MD5 buffer))
788 (defun imap-cram-md5-auth (buffer)
789 "Login to server using the AUTH CRAM-MD5 method."
790 (message "imap: Authenticating using CRAM-MD5...")
791 (let ((done (imap-interactive-login
793 (lambda (user passwd)
795 (imap-send-command-wait
797 "AUTHENTICATE CRAM-MD5"
799 (let* ((decoded (base64-decode-string challenge))
800 (hash (rfc2104-hash 'md5 64 16 passwd decoded))
801 (response (concat user " " hash))
802 (encoded (base64-encode-string response)))
805 (message "imap: Authenticating using CRAM-MD5...done")
806 (message "imap: Authenticating using CRAM-MD5...failed"))))
808 (defun imap-login-p (buffer)
809 (and (not (imap-capability 'LOGINDISABLED buffer))
810 (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
812 (defun imap-login-auth (buffer)
813 "Login to server using the LOGIN command."
814 (message "imap: Plaintext authentication...")
815 (imap-interactive-login buffer
816 (lambda (user passwd)
817 (imap-ok-p (imap-send-command-wait
818 (concat "LOGIN \"" user "\" \""
821 (defun imap-anonymous-p (buffer)
824 (defun imap-anonymous-auth (buffer)
825 (message "imap: Loging in anonymously...")
826 (with-current-buffer buffer
827 (imap-ok-p (imap-send-command-wait
828 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
829 (system-name)) "\"")))))
831 (defun imap-digest-md5-p (buffer)
832 (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
834 (require 'digest-md5)
837 (defun imap-digest-md5-auth (buffer)
838 "Login to server using the AUTH DIGEST-MD5 method."
839 (message "imap: Authenticating using DIGEST-MD5...")
840 (imap-interactive-login
842 (lambda (user passwd)
846 "AUTHENTICATE DIGEST-MD5"
848 (digest-md5-parse-digest-challenge
849 (base64-decode-string challenge))
851 (digest-md5-digest-uri
852 "imap" (digest-md5-challenge 'realm)))
854 (digest-md5-digest-response
855 user passwd digest-uri)))
856 (base64-encode-string response 'no-line-break))))
858 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
860 (setq imap-continuation nil)
861 (imap-send-command-1 "")
862 (imap-ok-p (imap-wait-for-tag tag)))))))
866 (defun imap-open-1 (buffer)
867 (with-current-buffer buffer
869 (setq imap-current-mailbox nil
870 imap-current-message nil
872 imap-process (condition-case ()
873 (funcall (nth 2 (assq imap-stream
875 "imap" buffer imap-server imap-port)
878 (set-process-filter imap-process 'imap-arrival-filter)
879 (set-process-sentinel imap-process 'imap-sentinel)
880 (while (and (eq imap-state 'initial)
881 (memq (process-status imap-process) '(open run)))
882 (message "Waiting for response from %s..." imap-server)
883 (accept-process-output imap-process 1))
884 (message "Waiting for response from %s...done" imap-server)
885 (and (memq (process-status imap-process) '(open run))
888 (defun imap-open (server &optional port stream auth buffer)
889 "Open a IMAP connection to host SERVER at PORT returning a buffer.
890 If PORT is unspecified, a default value is used (143 except
891 for SSL which use 993).
892 STREAM indicates the stream to use, see `imap-streams' for available
893 streams. If nil, it choices the best stream the server is capable of.
894 AUTH indicates authenticator to use, see `imap-authenticators' for
895 available authenticators. If nil, it choices the best stream the
896 server is capable of.
897 BUFFER can be a buffer or a name of a buffer, which is created if
898 necessery. If nil, the buffer name is generated."
899 (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
900 (with-current-buffer (get-buffer-create buffer)
901 (if (imap-opened buffer)
903 (mapcar 'make-local-variable imap-local-variables)
904 (imap-disable-multibyte)
905 (buffer-disable-undo)
906 (setq imap-server (or server imap-server))
907 (setq imap-port (or port imap-port))
908 (setq imap-auth (or auth imap-auth))
909 (setq imap-stream (or stream imap-stream))
910 (message "imap: Connecting to %s..." imap-server)
911 (if (let ((imap-stream (or imap-stream imap-default-stream)))
912 (imap-open-1 buffer))
914 (let (stream-changed)
915 (message "imap: Connecting to %s...done" imap-server)
916 (when (null imap-stream)
917 (let ((streams imap-streams))
918 (while (setq stream (pop streams))
919 (if (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
920 (setq stream-changed (not (eq (or imap-stream
926 (error "Couldn't figure out a stream for server"))))
928 (message "imap: Reconnecting with stream `%s'..." imap-stream)
930 (if (imap-open-1 buffer)
931 (message "imap: Reconnecting with stream `%s'...done"
933 (message "imap: Reconnecting with stream `%s'...failed"
935 (setq imap-capability nil))
936 (if (imap-opened buffer)
937 ;; Choose authenticator
938 (when (and (null imap-auth) (not (eq imap-state 'auth)))
939 (let ((auths imap-authenticators))
940 (while (setq auth (pop auths))
941 (if (funcall (nth 1 (assq auth imap-authenticator-alist))
946 (error "Couldn't figure out authenticator for server"))))))
947 (message "imap: Connecting to %s...failed" imap-server))
948 (when (imap-opened buffer)
949 (setq imap-mailbox-data (make-vector imap-mailbox-prime 0))
952 (defun imap-opened (&optional buffer)
953 "Return non-nil if connection to imap server in BUFFER is open.
954 If BUFFER is nil then the current buffer is used."
955 (and (setq buffer (get-buffer (or buffer (current-buffer))))
956 (buffer-live-p buffer)
957 (with-current-buffer buffer
959 (memq (process-status imap-process) '(open run))))))
961 (defun imap-authenticate (&optional user passwd buffer)
962 "Authenticate to server in BUFFER, using current buffer if nil.
963 It uses the authenticator specified when opening the server. If the
964 authenticator requires username/passwords, they are queried from the
965 user and optionally stored in the buffer. If USER and/or PASSWD is
966 specified, the user will not be questioned and the username and/or
967 password is remembered in the buffer."
968 (with-current-buffer (or buffer (current-buffer))
969 (if (not (eq imap-state 'nonauth))
970 (or (eq imap-state 'auth)
971 (eq imap-state 'select)
972 (eq imap-state 'examine))
973 (make-local-variable 'imap-username)
974 (make-local-variable 'imap-password)
975 (if user (setq imap-username user))
976 (if passwd (setq imap-password passwd))
977 (if (funcall (nth 2 (assq imap-auth imap-authenticator-alist)) buffer)
978 (setq imap-state 'auth)))))
980 (defun imap-close (&optional buffer)
981 "Close connection to server in BUFFER.
982 If BUFFER is nil, the current buffer is used."
983 (with-current-buffer (or buffer (current-buffer))
985 (not (imap-ok-p (imap-send-command-wait "LOGOUT")))
986 (message "Server %s didn't let me log out" imap-server))
987 (when (and imap-process
988 (memq (process-status imap-process) '(open run)))
989 (delete-process imap-process))
990 (setq imap-current-mailbox nil
991 imap-current-message nil
996 (defun imap-capability (&optional identifier buffer)
997 "Return a list of identifiers which server in BUFFER support.
998 If IDENTIFIER, return non-nil if it's among the servers capabilities.
999 If BUFFER is nil, the current buffer is assumed."
1000 (with-current-buffer (or buffer (current-buffer))
1001 (unless imap-capability
1002 (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
1003 (setq imap-capability '(IMAP2))))
1005 (memq (intern (upcase (symbol-name identifier))) imap-capability)
1008 (defun imap-namespace (&optional buffer)
1009 "Return a namespace hierarchy at server in BUFFER.
1010 If BUFFER is nil, the current buffer is assumed."
1011 (with-current-buffer (or buffer (current-buffer))
1012 (unless imap-namespace
1013 (when (imap-capability 'NAMESPACE)
1014 (imap-send-command-wait "NAMESPACE")))
1017 (defun imap-send-command-wait (command &optional buffer)
1018 (imap-wait-for-tag (imap-send-command command buffer) buffer))
1021 ;; Mailbox functions:
1023 (defun imap-mailbox-put (propname value &optional mailbox buffer)
1024 (with-current-buffer (or buffer (current-buffer))
1025 (if imap-mailbox-data
1026 (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
1028 (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
1029 propname value mailbox (current-buffer)))
1032 (defsubst imap-mailbox-get-1 (propname &optional mailbox)
1033 (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
1036 (defun imap-mailbox-get (propname &optional mailbox buffer)
1037 (let ((mailbox (imap-utf7-encode mailbox)))
1038 (with-current-buffer (or buffer (current-buffer))
1039 (imap-mailbox-get-1 propname (or mailbox imap-current-mailbox)))))
1041 (defun imap-mailbox-map-1 (func &optional mailbox-decoder buffer)
1042 (with-current-buffer (or buffer (current-buffer))
1046 (push (funcall func (if mailbox-decoder
1047 (funcall mailbox-decoder (symbol-name s))
1048 (symbol-name s))) result))
1052 (defun imap-mailbox-map (func &optional buffer)
1053 "Map a function across each mailbox in `imap-mailbox-data', returning a list.
1054 Function should take a mailbox name (a string) as
1056 (imap-mailbox-map-1 func 'imap-utf7-decode buffer))
1058 (defun imap-current-mailbox (&optional buffer)
1059 (with-current-buffer (or buffer (current-buffer))
1060 (imap-utf7-decode imap-current-mailbox)))
1062 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
1063 (and (string= mailbox imap-current-mailbox)
1065 (eq imap-state 'examine))
1067 (eq imap-state 'selected)))))
1069 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
1070 (with-current-buffer (or buffer (current-buffer))
1071 (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
1073 (defun imap-mailbox-select-1 (mailbox &optional examine)
1074 "Select MAILBOX on server in BUFFER.
1075 If EXAMINE is non-nil, do a read-only select."
1076 (if (imap-current-mailbox-p-1 mailbox examine)
1077 imap-current-mailbox
1078 (setq imap-current-mailbox mailbox)
1079 (if (imap-ok-p (imap-send-command-wait
1080 (concat (if examine "EXAMINE" "SELECT") " \""
1083 (setq imap-message-data (make-vector imap-message-prime 0)
1084 imap-state (if examine 'examine 'selected))
1085 imap-current-mailbox)
1086 ;; Failed SELECT/EXAMINE unselects current mailbox
1087 (setq imap-current-mailbox nil))))
1089 (defun imap-mailbox-select (mailbox &optional examine buffer)
1090 (with-current-buffer (or buffer (current-buffer))
1092 (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
1094 (defun imap-mailbox-examine-1 (mailbox &optional buffer)
1095 (with-current-buffer (or buffer (current-buffer))
1096 (imap-mailbox-select-1 mailbox 'exmine)))
1098 (defun imap-mailbox-examine (mailbox &optional buffer)
1099 "Examine MAILBOX on server in BUFFER."
1100 (imap-mailbox-select mailbox 'exmine buffer))
1102 (defun imap-mailbox-unselect (&optional buffer)
1103 "Close current folder in BUFFER, without expunging articles."
1104 (with-current-buffer (or buffer (current-buffer))
1105 (when (or (eq imap-state 'auth)
1106 (and (imap-capability 'UNSELECT)
1107 (imap-ok-p (imap-send-command-wait "UNSELECT")))
1109 (imap-send-command-wait (concat "EXAMINE \""
1110 imap-current-mailbox
1112 (imap-ok-p (imap-send-command-wait "CLOSE"))))
1113 (setq imap-current-mailbox nil
1114 imap-message-data nil
1118 (defun imap-mailbox-expunge (&optional buffer)
1119 "Expunge articles in current folder in BUFFER.
1120 If BUFFER is nil the current buffer is assumed."
1121 (with-current-buffer (or buffer (current-buffer))
1122 (when (and imap-current-mailbox (not (eq imap-state 'examine)))
1123 (imap-ok-p (imap-send-command-wait "EXPUNGE")))))
1125 (defun imap-mailbox-close (&optional buffer)
1126 "Expunge articles and close current folder in BUFFER.
1127 If BUFFER is nil the current buffer is assumed."
1128 (with-current-buffer (or buffer (current-buffer))
1129 (when (and imap-current-mailbox
1130 (imap-ok-p (imap-send-command-wait "CLOSE")))
1131 (setq imap-current-mailbox nil
1132 imap-message-data nil
1136 (defun imap-mailbox-create-1 (mailbox)
1137 (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
1139 (defun imap-mailbox-create (mailbox &optional buffer)
1140 "Create MAILBOX on server in BUFFER.
1141 If BUFFER is nil the current buffer is assumed."
1142 (with-current-buffer (or buffer (current-buffer))
1143 (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
1145 (defun imap-mailbox-delete (mailbox &optional buffer)
1146 "Delete MAILBOX on server in BUFFER.
1147 If BUFFER is nil the current buffer is assumed."
1148 (let ((mailbox (imap-utf7-encode mailbox)))
1149 (with-current-buffer (or buffer (current-buffer))
1151 (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1153 (defun imap-mailbox-rename (oldname newname &optional buffer)
1154 "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1155 If BUFFER is nil the current buffer is assumed."
1156 (let ((oldname (imap-utf7-encode oldname))
1157 (newname (imap-utf7-encode newname)))
1158 (with-current-buffer (or buffer (current-buffer))
1160 (imap-send-command-wait (list "RENAME \"" oldname "\" "
1161 "\"" newname "\""))))))
1163 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1164 "Return a list of subscribed mailboxes on server in BUFFER.
1165 If ROOT is non-nil, only list matching mailboxes. If ADD-DELIMITER is
1166 non-nil, a hierarchy delimiter is added to root. REFERENCE is a
1167 implementation-specific string that has to be passed to lsub command."
1168 (with-current-buffer (or buffer (current-buffer))
1169 ;; Make sure we know the hierarchy separator for root's hierarchy
1170 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1171 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1172 (imap-utf7-encode root) "\"")))
1173 ;; clear list data (NB not delimiter and other stuff)
1174 (imap-mailbox-map-1 (lambda (mailbox)
1175 (imap-mailbox-put 'lsub nil mailbox)))
1177 (imap-send-command-wait
1178 (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1179 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1182 (imap-mailbox-map-1 (lambda (mailbox)
1183 (when (imap-mailbox-get-1 'lsub mailbox)
1184 (push (imap-utf7-decode mailbox) out))))
1187 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1188 "Return a list of mailboxes matching ROOT on server in BUFFER.
1189 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1190 root. REFERENCE is a implementation-specific string that has to be
1191 passed to list command."
1192 (with-current-buffer (or buffer (current-buffer))
1193 ;; Make sure we know the hierarchy separator for root's hierarchy
1194 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1195 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1196 (imap-utf7-encode root) "\"")))
1197 ;; clear list data (NB not delimiter and other stuff)
1198 (imap-mailbox-map-1 (lambda (mailbox)
1199 (imap-mailbox-put 'list nil mailbox)))
1201 (imap-send-command-wait
1202 (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1203 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1206 (imap-mailbox-map-1 (lambda (mailbox)
1207 (when (imap-mailbox-get-1 'list mailbox)
1208 (push (imap-utf7-decode mailbox) out))))
1211 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1212 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1213 Returns non-nil if successful."
1214 (with-current-buffer (or buffer (current-buffer))
1215 (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1216 (imap-utf7-encode mailbox)
1219 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1220 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1221 Returns non-nil if successful."
1222 (with-current-buffer (or buffer (current-buffer))
1223 (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1224 (imap-utf7-encode mailbox)
1227 (defun imap-mailbox-status (mailbox items &optional buffer)
1228 "Get status items ITEM in MAILBOX from server in BUFFER.
1229 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1230 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1231 or 'unseen. If ITEMS is a list of symbols, a list of values is
1232 returned, if ITEMS is a symbol only it's value is returned."
1233 (with-current-buffer (or buffer (current-buffer))
1235 (imap-send-command-wait (list "STATUS \""
1236 (imap-utf7-encode mailbox)
1243 (mapcar (lambda (item)
1244 (imap-mailbox-get item mailbox))
1246 (imap-mailbox-get items mailbox)))))
1248 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1249 "Get ACL on mailbox from server in BUFFER."
1250 (let ((mailbox (imap-utf7-encode mailbox)))
1251 (with-current-buffer (or buffer (current-buffer))
1253 (imap-send-command-wait (list "GETACL \""
1254 (or mailbox imap-current-mailbox)
1256 (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1258 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1259 "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
1260 (let ((mailbox (imap-utf7-encode mailbox)))
1261 (with-current-buffer (or buffer (current-buffer))
1263 (imap-send-command-wait (list "SETACL \""
1264 (or mailbox imap-current-mailbox)
1270 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1271 "Removes any <identifier,rights> pair for IDENTIFIER in MAILBOX from server in BUFFER."
1272 (let ((mailbox (imap-utf7-encode mailbox)))
1273 (with-current-buffer (or buffer (current-buffer))
1275 (imap-send-command-wait (list "DELETEACL \""
1276 (or mailbox imap-current-mailbox)
1281 ;; Message functions:
1283 (defun imap-current-message (&optional buffer)
1284 (with-current-buffer (or buffer (current-buffer))
1285 imap-current-message))
1287 (defun imap-list-to-message-set (list)
1288 (mapconcat (lambda (item)
1289 (number-to-string item))
1295 (defun imap-range-to-message-set (range)
1300 (car item) (cdr item))
1301 (format "%d" item)))
1302 (if (and (listp range) (not (listp (cdr range))))
1303 (list range) ;; make (1 . 2) into ((1 . 2))
1307 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1308 (with-current-buffer (or buffer (current-buffer))
1309 (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1311 (imap-list-to-message-set uids)
1315 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1316 "Fetch properties PROPS from message set UIDS from server in BUFFER.
1317 UIDS can be a string, number or a list of numbers. If RECEIVE
1318 is non-nil return theese properties."
1319 (with-current-buffer (or buffer (current-buffer))
1320 (when (imap-ok-p (imap-send-command-wait
1321 (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1323 (imap-list-to-message-set uids)
1326 (if (or (null receive) (stringp uids))
1329 (mapcar (lambda (uid)
1331 (mapcar (lambda (prop)
1332 (imap-message-get uid prop))
1334 (imap-message-get uid receive)))
1336 (imap-message-get uids receive))))))
1338 (defun imap-message-put (uid propname value &optional buffer)
1339 (with-current-buffer (or buffer (current-buffer))
1340 (if imap-message-data
1341 (put (intern (number-to-string uid) imap-message-data)
1343 (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1344 uid propname value (current-buffer)))
1347 (defun imap-message-get (uid propname &optional buffer)
1348 (with-current-buffer (or buffer (current-buffer))
1349 (get (intern-soft (number-to-string uid) imap-message-data)
1352 (defun imap-message-map (func propname &optional buffer)
1353 "Map a function across each mailbox in `imap-message-data', returning a list."
1354 (with-current-buffer (or buffer (current-buffer))
1358 (push (funcall func (get s 'UID) (get s propname)) result))
1362 (defmacro imap-message-envelope-date (uid &optional buffer)
1363 `(with-current-buffer (or ,buffer (current-buffer))
1364 (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1366 (defmacro imap-message-envelope-subject (uid &optional buffer)
1367 `(with-current-buffer (or ,buffer (current-buffer))
1368 (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1370 (defmacro imap-message-envelope-from (uid &optional buffer)
1371 `(with-current-buffer (or ,buffer (current-buffer))
1372 (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1374 (defmacro imap-message-envelope-sender (uid &optional buffer)
1375 `(with-current-buffer (or ,buffer (current-buffer))
1376 (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1378 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1379 `(with-current-buffer (or ,buffer (current-buffer))
1380 (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1382 (defmacro imap-message-envelope-to (uid &optional buffer)
1383 `(with-current-buffer (or ,buffer (current-buffer))
1384 (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1386 (defmacro imap-message-envelope-cc (uid &optional buffer)
1387 `(with-current-buffer (or ,buffer (current-buffer))
1388 (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1390 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1391 `(with-current-buffer (or ,buffer (current-buffer))
1392 (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1394 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1395 `(with-current-buffer (or ,buffer (current-buffer))
1396 (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1398 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1399 `(with-current-buffer (or ,buffer (current-buffer))
1400 (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1402 (defmacro imap-message-body (uid &optional buffer)
1403 `(with-current-buffer (or ,buffer (current-buffer))
1404 (imap-message-get ,uid 'BODY)))
1406 (defun imap-search (predicate &optional buffer)
1407 (with-current-buffer (or buffer (current-buffer))
1408 (imap-mailbox-put 'search 'dummy)
1409 (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1410 (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1411 (error "Missing SEARCH response to a SEARCH command")
1412 (imap-mailbox-get-1 'search imap-current-mailbox)))))
1414 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1415 "Return t iff FLAG can be permanently (between IMAP sessions) saved on articles, in MAILBOX on server in BUFFER."
1416 (with-current-buffer (or buffer (current-buffer))
1417 (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1418 (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1420 (defun imap-message-flags-set (articles flags &optional silent buffer)
1421 (when (and articles flags)
1422 (with-current-buffer (or buffer (current-buffer))
1423 (imap-ok-p (imap-send-command-wait
1424 (concat "UID STORE " articles
1425 " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1427 (defun imap-message-flags-del (articles flags &optional silent buffer)
1428 (when (and articles flags)
1429 (with-current-buffer (or buffer (current-buffer))
1430 (imap-ok-p (imap-send-command-wait
1431 (concat "UID STORE " articles
1432 " -FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1434 (defun imap-message-flags-add (articles flags &optional silent buffer)
1435 (when (and articles flags)
1436 (with-current-buffer (or buffer (current-buffer))
1437 (imap-ok-p (imap-send-command-wait
1438 (concat "UID STORE " articles
1439 " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1441 (defun imap-message-copyuid-1 (mailbox)
1442 (if (imap-capability 'UIDPLUS)
1443 (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1444 (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1445 (let ((old-mailbox imap-current-mailbox)
1447 (imap-message-data (make-vector 2 0)))
1448 (when (imap-mailbox-examine-1 mailbox)
1450 (and (imap-fetch "*" "UID")
1451 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1452 (apply 'max (imap-message-map
1453 (lambda (uid prop) uid) 'UID))))
1455 (imap-mailbox-select old-mailbox (eq state 'examine))
1456 (imap-mailbox-unselect)))))))
1458 (defun imap-message-copyuid (mailbox &optional buffer)
1459 (with-current-buffer (or buffer (current-buffer))
1460 (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1462 (defun imap-message-copy (articles mailbox
1463 &optional dont-create no-copyuid buffer)
1464 "Copy ARTICLES (a string message set) to MAILBOX on server in
1465 BUFFER, creating mailbox if it doesn't exist. If dont-create is
1466 non-nil, it will not create a mailbox. On success, return a list with
1467 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1468 first element, rest of list contain the saved articles' UIDs."
1470 (with-current-buffer (or buffer (current-buffer))
1471 (let ((mailbox (imap-utf7-encode mailbox)))
1472 (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1473 (imap-current-target-mailbox mailbox))
1474 (if (imap-ok-p (imap-send-command-wait cmd))
1476 (when (and (not dont-create)
1477 ;; removed because of buggy Oracle server
1478 ;; that doesn't send TRYCREATE tags (which
1479 ;; is a MUST according to specifications):
1480 ;;(imap-mailbox-get-1 'trycreate mailbox)
1481 (imap-mailbox-create-1 mailbox))
1482 (imap-ok-p (imap-send-command-wait cmd)))))
1484 (imap-message-copyuid-1 mailbox)))))))
1486 (defun imap-message-appenduid-1 (mailbox)
1487 (if (imap-capability 'UIDPLUS)
1488 (imap-mailbox-get-1 'appenduid mailbox)
1489 (let ((old-mailbox imap-current-mailbox)
1491 (imap-message-data (make-vector 2 0)))
1492 (when (imap-mailbox-examine-1 mailbox)
1494 (and (imap-fetch "*" "UID")
1495 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1496 (apply 'max (imap-message-map
1497 (lambda (uid prop) uid) 'UID))))
1499 (imap-mailbox-select old-mailbox (eq state 'examine))
1500 (imap-mailbox-unselect)))))))
1502 (defun imap-message-appenduid (mailbox &optional buffer)
1503 (with-current-buffer (or buffer (current-buffer))
1504 (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1506 (defun imap-message-append (mailbox article &optional flags date-time buffer)
1507 "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1508 FLAGS and DATE-TIME is currently not used. Return a cons holding
1509 uidvalidity of MAILBOX and UID the newly created article got, or nil
1511 (let ((mailbox (imap-utf7-encode mailbox)))
1512 (with-current-buffer (or buffer (current-buffer))
1513 (and (let ((imap-current-target-mailbox mailbox))
1515 (imap-send-command-wait
1516 (list "APPEND \"" mailbox "\" " article))))
1517 (imap-message-appenduid-1 mailbox)))))
1519 (defun imap-body-lines (body)
1520 "Return number of lines in article by looking at the mime bodystructure BODY."
1522 (if (stringp (car body))
1523 (cond ((and (string= (upcase (car body)) "TEXT")
1524 (numberp (nth 7 body)))
1526 ((and (string= (upcase (car body)) "MESSAGE")
1527 (numberp (nth 9 body)))
1530 (apply '+ (mapcar 'imap-body-lines body)))
1533 (defun imap-envelope-from (from)
1534 "Return a from string line."
1536 (concat (aref from 0)
1537 (if (aref from 0) " <")
1541 (if (aref from 0) ">"))))
1544 ;; Internal functions.
1546 (defun imap-send-command-1 (cmdstr)
1547 (setq cmdstr (concat cmdstr imap-client-eol))
1549 (with-current-buffer (get-buffer-create imap-log)
1550 (imap-disable-multibyte)
1551 (buffer-disable-undo)
1552 (goto-char (point-max))
1554 (process-send-string imap-process cmdstr))
1556 (defun imap-send-command (command &optional buffer)
1557 (with-current-buffer (or buffer (current-buffer))
1558 (if (not (listp command)) (setq command (list command)))
1559 (let ((tag (setq imap-tag (1+ imap-tag)))
1561 (setq cmdstr (concat (number-to-string imap-tag) " "))
1562 (while (setq cmd (pop command))
1563 (cond ((stringp cmd)
1564 (setq cmdstr (concat cmdstr cmd)))
1566 (let ((eol imap-client-eol)
1567 (calcfirst imap-calculate-literal-size-first)
1569 (with-current-buffer cmd
1571 (setq size (buffer-size)))
1572 (when (not (equal eol "\r\n"))
1573 ;; XXX modifies buffer!
1574 (goto-char (point-min))
1575 (while (search-forward "\r\n" nil t)
1576 (replace-match eol)))
1578 (setq size (buffer-size))))
1580 (concat cmdstr (format "{%d}" size))))
1583 (imap-send-command-1 cmdstr)
1585 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1586 (setq command nil) ;; abort command if no cont-req
1587 (let ((process imap-process)
1588 (stream imap-stream)
1589 (eol imap-client-eol))
1590 (with-current-buffer cmd
1592 (with-current-buffer (get-buffer-create
1594 (imap-disable-multibyte)
1595 (buffer-disable-undo)
1596 (goto-char (point-max))
1597 (insert-buffer-substring cmd)))
1598 (process-send-region process (point-min)
1600 (process-send-string process imap-client-eol))))
1601 (setq imap-continuation nil)))
1603 (imap-send-command-1 cmdstr)
1606 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1607 (setq command nil) ;; abort command if no cont-req
1608 (setq command (cons (funcall cmd imap-continuation)
1610 (setq imap-continuation nil)))
1612 (error "Unknown command type"))))
1614 (imap-send-command-1 cmdstr))
1617 (defun imap-wait-for-tag (tag &optional buffer)
1618 (with-current-buffer (or buffer (current-buffer))
1619 (while (and (null imap-continuation)
1620 (< imap-reached-tag tag))
1621 (or (and (not (memq (process-status imap-process) '(open run)))
1623 (let ((len (/ (point-max) 1024))
1626 (message "imap read: %dk" len))
1627 (accept-process-output imap-process 1))))
1629 (or (assq tag imap-failed-tags)
1630 (if imap-continuation
1634 (defun imap-sentinel (process string)
1635 (delete-process process))
1637 (defun imap-find-next-line ()
1638 "Return point at end of current line, taking into account literals.
1639 Return nil if no complete line has arrived."
1640 (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
1643 (if (match-string 1)
1644 (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1646 (goto-char (+ (point) (string-to-number (match-string 1))))
1647 (imap-find-next-line))
1650 (defun imap-arrival-filter (proc string)
1651 "IMAP process filter."
1652 (with-current-buffer (process-buffer proc)
1653 (goto-char (point-max))
1656 (with-current-buffer (get-buffer-create imap-log)
1657 (imap-disable-multibyte)
1658 (buffer-disable-undo)
1659 (goto-char (point-max))
1662 (goto-char (point-min))
1663 (while (setq end (imap-find-next-line))
1665 (narrow-to-region (point-min) end)
1666 (delete-backward-char (length imap-server-eol))
1667 (goto-char (point-min))
1669 (cond ((eq imap-state 'initial)
1670 (imap-parse-greeting))
1671 ((or (eq imap-state 'auth)
1672 (eq imap-state 'nonauth)
1673 (eq imap-state 'selected)
1674 (eq imap-state 'examine))
1675 (imap-parse-response))
1677 (message "Unknown state %s in arrival filter"
1679 (delete-region (point-min) (point-max))))))))
1684 (defsubst imap-forward ()
1685 (or (eobp) (forward-char)))
1688 ;; ; Unsigned 32-bit integer
1689 ;; ; (0 <= n < 4,294,967,296)
1691 (defsubst imap-parse-number ()
1692 (when (looking-at "[0-9]+")
1694 (string-to-number (match-string 0))
1695 (goto-char (match-end 0)))))
1697 ;; literal = "{" number "}" CRLF *CHAR8
1698 ;; ; Number represents the number of CHAR8s
1700 (defsubst imap-parse-literal ()
1701 (when (looking-at "{\\([0-9]+\\)}\r\n")
1702 (let ((pos (match-end 0))
1703 (len (string-to-number (match-string 1))))
1704 (if (< (point-max) (+ pos len))
1706 (goto-char (+ pos len))
1707 (buffer-substring pos (+ pos len))))))
1709 ;; string = quoted / literal
1711 ;; quoted = DQUOTE *QUOTED-CHAR DQUOTE
1713 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
1714 ;; "\" quoted-specials
1716 ;; quoted-specials = DQUOTE / "\"
1718 ;; TEXT-CHAR = <any CHAR except CR and LF>
1720 (defsubst imap-parse-string ()
1721 (cond ((eq (char-after) ?\")
1723 (let ((p (point)) (name ""))
1724 (skip-chars-forward "^\"\\\\")
1725 (setq name (buffer-substring p (point)))
1726 (while (eq (char-after) ?\\)
1727 (setq p (1+ (point)))
1729 (skip-chars-forward "^\"\\\\")
1730 (setq name (concat name (buffer-substring p (point)))))
1733 ((eq (char-after) ?{)
1734 (imap-parse-literal))))
1738 (defsubst imap-parse-nil ()
1739 (if (looking-at "NIL")
1740 (goto-char (match-end 0))))
1742 ;; nstring = string / nil
1744 (defsubst imap-parse-nstring ()
1745 (or (imap-parse-string)
1746 (and (imap-parse-nil)
1749 ;; astring = atom / string
1751 ;; atom = 1*ATOM-CHAR
1753 ;; ATOM-CHAR = <any CHAR except atom-specials>
1755 ;; atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards /
1758 ;; list-wildcards = "%" / "*"
1760 ;; quoted-specials = DQUOTE / "\"
1762 (defsubst imap-parse-astring ()
1763 (or (imap-parse-string)
1764 (buffer-substring (point)
1765 (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
1766 (goto-char (1- (match-end 0)))
1770 ;; address = "(" addr-name SP addr-adl SP addr-mailbox SP
1773 ;; addr-adl = nstring
1774 ;; ; Holds route from [RFC-822] route-addr if
1777 ;; addr-host = nstring
1778 ;; ; NIL indicates [RFC-822] group syntax.
1779 ;; ; Otherwise, holds [RFC-822] domain name
1781 ;; addr-mailbox = nstring
1782 ;; ; NIL indicates end of [RFC-822] group; if
1783 ;; ; non-NIL and addr-host is NIL, holds
1784 ;; ; [RFC-822] group name.
1785 ;; ; Otherwise, holds [RFC-822] local-part
1786 ;; ; after removing [RFC-822] quoting
1788 ;; addr-name = nstring
1789 ;; ; If non-NIL, holds phrase from [RFC-822]
1790 ;; ; mailbox after removing [RFC-822] quoting
1793 (defsubst imap-parse-address ()
1795 (when (eq (char-after) ?\()
1797 (setq address (vector (prog1 (imap-parse-nstring)
1799 (prog1 (imap-parse-nstring)
1801 (prog1 (imap-parse-nstring)
1803 (imap-parse-nstring)))
1804 (when (eq (char-after) ?\))
1808 ;; address-list = "(" 1*address ")" / nil
1812 (defsubst imap-parse-address-list ()
1813 (if (eq (char-after) ?\()
1814 (let (address addresses)
1816 (while (and (not (eq (char-after) ?\)))
1817 ;; next line for MS Exchange bug
1818 (progn (and (eq (char-after) ? ) (imap-forward)) t)
1819 (setq address (imap-parse-address)))
1820 (setq addresses (cons address addresses)))
1821 (when (eq (char-after) ?\))
1823 (nreverse addresses)))
1824 (assert (imap-parse-nil) t "In imap-parse-address-list")))
1826 ;; mailbox = "INBOX" / astring
1827 ;; ; INBOX is case-insensitive. All case variants of
1828 ;; ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
1829 ;; ; not as an astring. An astring which consists of
1830 ;; ; the case-insensitive sequence "I" "N" "B" "O" "X"
1831 ;; ; is considered to be INBOX and not an astring.
1832 ;; ; Refer to section 5.1 for further
1833 ;; ; semantic details of mailbox names.
1835 (defsubst imap-parse-mailbox ()
1836 (let ((mailbox (imap-parse-astring)))
1837 (if (string-equal "INBOX" (upcase mailbox))
1841 ;; greeting = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
1843 ;; resp-cond-auth = ("OK" / "PREAUTH") SP resp-text
1844 ;; ; Authentication condition
1846 ;; resp-cond-bye = "BYE" SP resp-text
1848 (defun imap-parse-greeting ()
1849 "Parse a IMAP greeting."
1850 (cond ((looking-at "\\* OK ")
1851 (setq imap-state 'nonauth))
1852 ((looking-at "\\* PREAUTH ")
1853 (setq imap-state 'auth))
1854 ((looking-at "\\* BYE ")
1855 (setq imap-state 'closed))))
1857 ;; response = *(continue-req / response-data) response-done
1859 ;; continue-req = "+" SP (resp-text / base64) CRLF
1861 ;; response-data = "*" SP (resp-cond-state / resp-cond-bye /
1862 ;; mailbox-data / message-data / capability-data) CRLF
1864 ;; response-done = response-tagged / response-fatal
1866 ;; response-fatal = "*" SP resp-cond-bye CRLF
1867 ;; ; Server closes connection immediately
1869 ;; response-tagged = tag SP resp-cond-state CRLF
1871 ;; resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
1872 ;; ; Status condition
1874 ;; resp-cond-bye = "BYE" SP resp-text
1876 ;; mailbox-data = "FLAGS" SP flag-list /
1877 ;; "LIST" SP mailbox-list /
1878 ;; "LSUB" SP mailbox-list /
1879 ;; "SEARCH" *(SP nz-number) /
1880 ;; "STATUS" SP mailbox SP "("
1881 ;; [status-att SP number *(SP status-att SP number)] ")" /
1882 ;; number SP "EXISTS" /
1883 ;; number SP "RECENT"
1885 ;; message-data = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
1887 ;; capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
1889 ;; ; IMAP4rev1 servers which offer RFC 1730
1890 ;; ; compatibility MUST list "IMAP4" as the first
1893 (defun imap-parse-response ()
1894 "Parse a IMAP command response."
1896 (case (setq token (read (current-buffer)))
1897 (+ (setq imap-continuation
1898 (or (buffer-substring (min (point-max) (1+ (point)))
1901 (* (case (prog1 (setq token (read (current-buffer)))
1903 (OK (imap-parse-resp-text))
1904 (NO (imap-parse-resp-text))
1905 (BAD (imap-parse-resp-text))
1906 (BYE (imap-parse-resp-text))
1907 (FLAGS (imap-mailbox-put 'flags (imap-parse-flag-list)))
1908 (LIST (imap-parse-data-list 'list))
1909 (LSUB (imap-parse-data-list 'lsub))
1910 (SEARCH (imap-mailbox-put
1912 (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
1913 (STATUS (imap-parse-status))
1914 (CAPABILITY (setq imap-capability
1915 (read (concat "(" (upcase (buffer-substring
1916 (point) (point-max)))
1918 (ACL (imap-parse-acl))
1919 (t (case (prog1 (read (current-buffer))
1921 (EXISTS (imap-mailbox-put 'exists token))
1922 (RECENT (imap-mailbox-put 'recent token))
1924 (FETCH (imap-parse-fetch token))
1925 (t (message "Garbage: %s" (buffer-string)))))))
1927 (if (not (integerp token))
1928 (message "Garbage: %s" (buffer-string))
1929 (case (prog1 (setq status (read (current-buffer)))
1932 (setq imap-reached-tag (max imap-reached-tag token))
1933 (imap-parse-resp-text)))
1935 (setq imap-reached-tag (max imap-reached-tag token))
1937 (imap-parse-resp-text))
1939 (when (eq (char-after) ?\[)
1940 (setq code (buffer-substring (point)
1941 (search-forward "]")))
1943 (setq text (buffer-substring (point) (point-max)))
1944 (push (list token status code text)
1945 imap-failed-tags))))
1947 (setq imap-reached-tag (max imap-reached-tag token))
1949 (imap-parse-resp-text))
1951 (when (eq (char-after) ?\[)
1952 (setq code (buffer-substring (point)
1953 (search-forward "]")))
1955 (setq text (buffer-substring (point) (point-max)))
1956 (push (list token status code text) imap-failed-tags)
1957 (error "Internal error, tag %s status %s code %s text %s"
1958 token status code text))))
1959 (t (message "Garbage: %s" (buffer-string))))))))))
1961 ;; resp-text = ["[" resp-text-code "]" SP] text
1963 ;; text = 1*TEXT-CHAR
1965 ;; TEXT-CHAR = <any CHAR except CR and LF>
1967 (defun imap-parse-resp-text ()
1968 (imap-parse-resp-text-code))
1970 ;; resp-text-code = "ALERT" /
1971 ;; "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
1972 ;; "NEWNAME" SP string SP string /
1974 ;; "PERMANENTFLAGS" SP "("
1975 ;; [flag-perm *(SP flag-perm)] ")" /
1979 ;; "UIDNEXT" SP nz-number /
1980 ;; "UIDVALIDITY" SP nz-number /
1981 ;; "UNSEEN" SP nz-number /
1982 ;; resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
1984 ;; resp_code_apnd = "APPENDUID" SPACE nz_number SPACE uniqueid
1986 ;; resp_code_copy = "COPYUID" SPACE nz_number SPACE set SPACE set
1988 ;; set = sequence-num / (sequence-num ":" sequence-num) /
1990 ;; ; Identifies a set of messages. For message
1991 ;; ; sequence numbers, these are consecutive
1992 ;; ; numbers from 1 to the number of messages in
1994 ;; ; Comma delimits individual numbers, colon
1995 ;; ; delimits between two numbers inclusive.
1996 ;; ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
1997 ;; ; 14,15 for a mailbox with 15 messages.
1999 ;; sequence-num = nz-number / "*"
2000 ;; ; * is the largest number in use. For message
2001 ;; ; sequence numbers, it is the number of messages
2002 ;; ; in the mailbox. For unique identifiers, it is
2003 ;; ; the unique identifier of the last message in
2006 ;; flag-perm = flag / "\*"
2008 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2009 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2010 ;; ; Does not include "\Recent"
2012 ;; flag-extension = "\" atom
2013 ;; ; Future expansion. Client implementations
2014 ;; ; MUST accept flag-extension flags. Server
2015 ;; ; implementations MUST NOT generate
2016 ;; ; flag-extension flags except as defined by
2017 ;; ; future standard or standards-track
2018 ;; ; revisions of this specification.
2020 ;; flag-keyword = atom
2022 ;; resp-text-atom = 1*<any ATOM-CHAR except "]">
2024 (defun imap-parse-resp-text-code ()
2025 ;; xxx next line for stalker communigate pro 3.3.1 bug
2026 (when (looking-at " \\[")
2028 (when (eq (char-after) ?\[)
2030 (cond ((search-forward "PERMANENTFLAGS " nil t)
2031 (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2032 ((search-forward "UIDNEXT " nil t)
2033 (imap-mailbox-put 'uidnext (read (current-buffer))))
2034 ((search-forward "UNSEEN " nil t)
2035 (imap-mailbox-put 'unseen (read (current-buffer))))
2036 ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2037 (imap-mailbox-put 'uidvalidity (match-string 1)))
2038 ((search-forward "READ-ONLY" nil t)
2039 (imap-mailbox-put 'read-only t))
2040 ((search-forward "NEWNAME " nil t)
2041 (let (oldname newname)
2042 (setq oldname (imap-parse-string))
2044 (setq newname (imap-parse-string))
2045 (imap-mailbox-put 'newname newname oldname)))
2046 ((search-forward "TRYCREATE" nil t)
2047 (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2048 ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2049 (imap-mailbox-put 'appenduid
2050 (list (match-string 1)
2051 (string-to-number (match-string 2)))
2052 imap-current-target-mailbox))
2053 ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2054 (imap-mailbox-put 'copyuid (list (match-string 1)
2057 imap-current-target-mailbox))
2058 ((search-forward "ALERT] " nil t)
2059 (message "Imap server %s information: %s" imap-server
2060 (buffer-substring (point) (point-max)))))))
2062 ;; mailbox-list = "(" [mbx-list-flags] ")" SP
2063 ;; (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2065 ;; mbx-list-flags = *(mbx-list-oflag SP) mbx-list-sflag
2066 ;; *(SP mbx-list-oflag) /
2067 ;; mbx-list-oflag *(SP mbx-list-oflag)
2069 ;; mbx-list-oflag = "\Noinferiors" / flag-extension
2070 ;; ; Other flags; multiple possible per LIST response
2072 ;; mbx-list-sflag = "\Noselect" / "\Marked" / "\Unmarked"
2073 ;; ; Selectability flags; only one per LIST response
2075 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2076 ;; "\" quoted-specials
2078 ;; quoted-specials = DQUOTE / "\"
2080 (defun imap-parse-data-list (type)
2081 (let (flags delimiter mailbox)
2082 (setq flags (imap-parse-flag-list))
2083 (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2084 (setq delimiter (match-string 1))
2085 (goto-char (1+ (match-end 0)))
2086 (when (setq mailbox (imap-parse-mailbox))
2087 (imap-mailbox-put type t mailbox)
2088 (imap-mailbox-put 'list-flags flags mailbox)
2089 (imap-mailbox-put 'delimiter delimiter mailbox)))))
2091 ;; msg_att ::= "(" 1#("ENVELOPE" SPACE envelope /
2092 ;; "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2093 ;; "INTERNALDATE" SPACE date_time /
2094 ;; "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2095 ;; "RFC822.SIZE" SPACE number /
2096 ;; "BODY" ["STRUCTURE"] SPACE body /
2097 ;; "BODY" section ["<" number ">"] SPACE nstring /
2098 ;; "UID" SPACE uniqueid) ")"
2100 ;; date_time ::= <"> date_day_fixed "-" date_month "-" date_year
2101 ;; SPACE time SPACE zone <">
2103 ;; section ::= "[" [section_text / (nz_number *["." nz_number]
2104 ;; ["." (section_text / "MIME")])] "]"
2106 ;; section_text ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2107 ;; SPACE header_list / "TEXT"
2109 ;; header_fld_name ::= astring
2111 ;; header_list ::= "(" 1#header_fld_name ")"
2113 (defsubst imap-parse-header-list ()
2114 (when (eq (char-after) ?\()
2116 (while (not (eq (char-after) ?\)))
2118 (push (imap-parse-astring) strlist))
2120 (nreverse strlist))))
2122 (defsubst imap-parse-fetch-body-section ()
2124 (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2125 (if (eq (char-before) ? )
2127 (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2128 (search-forward "]" nil t))
2131 (defun imap-parse-fetch (response)
2132 (when (eq (char-after) ?\()
2133 (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2134 rfc822size body bodydetail bodystructure)
2135 (while (not (eq (char-after) ?\)))
2137 (let ((token (read (current-buffer))))
2139 (cond ((eq token 'UID)
2140 (setq uid (ignore-errors (read (current-buffer)))))
2142 (setq flags (imap-parse-flag-list)))
2143 ((eq token 'ENVELOPE)
2144 (setq envelope (imap-parse-envelope)))
2145 ((eq token 'INTERNALDATE)
2146 (setq internaldate (imap-parse-string)))
2148 (setq rfc822 (imap-parse-nstring)))
2149 ((eq token 'RFC822.HEADER)
2150 (setq rfc822header (imap-parse-nstring)))
2151 ((eq token 'RFC822.TEXT)
2152 (setq rfc822text (imap-parse-nstring)))
2153 ((eq token 'RFC822.SIZE)
2154 (setq rfc822size (read (current-buffer))))
2156 (if (eq (char-before) ?\[)
2158 (upcase (imap-parse-fetch-body-section))
2159 (and (eq (char-after) ?<)
2160 (buffer-substring (1+ (point))
2161 (search-forward ">" nil t)))
2162 (progn (imap-forward)
2163 (imap-parse-nstring)))
2165 (setq body (imap-parse-body))))
2166 ((eq token 'BODYSTRUCTURE)
2167 (setq bodystructure (imap-parse-body))))))
2169 (setq imap-current-message uid)
2170 (imap-message-put uid 'UID uid)
2171 (and flags (imap-message-put uid 'FLAGS flags))
2172 (and envelope (imap-message-put uid 'ENVELOPE envelope))
2173 (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2174 (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2175 (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2176 (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2177 (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2178 (and body (imap-message-put uid 'BODY body))
2179 (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2180 (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2181 (run-hooks 'imap-fetch-data-hook)))))
2183 ;; mailbox-data = ...
2184 ;; "STATUS" SP mailbox SP "("
2185 ;; [status-att SP number
2186 ;; *(SP status-att SP number)] ")"
2189 ;; status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2192 (defun imap-parse-status ()
2193 (let ((mailbox (imap-parse-mailbox)))
2194 (when (and mailbox (search-forward "(" nil t))
2195 (while (not (eq (char-after) ?\)))
2196 (let ((token (read (current-buffer))))
2197 (cond ((eq token 'MESSAGES)
2198 (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2200 (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2201 ((eq token 'UIDNEXT)
2202 (imap-mailbox-put 'uidnext (read (current-buffer)) mailbox))
2203 ((eq token 'UIDVALIDITY)
2204 (and (looking-at " \\([0-9]+\\)")
2205 (imap-mailbox-put 'uidvalidity (match-string 1) mailbox)
2206 (goto-char (match-end 1))))
2208 (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2210 (message "Unknown status data %s in mailbox %s ignored"
2211 token mailbox))))))))
2213 ;; acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2216 ;; identifier ::= astring
2218 ;; rights ::= astring
2220 (defun imap-parse-acl ()
2221 (let ((mailbox (imap-parse-mailbox))
2222 identifier rights acl)
2223 (while (eq (char-after) ?\ )
2225 (setq identifier (imap-parse-astring))
2227 (setq rights (imap-parse-astring))
2228 (setq acl (append acl (list (cons identifier rights)))))
2229 (imap-mailbox-put 'acl acl mailbox)))
2231 ;; flag-list = "(" [flag *(SP flag)] ")"
2233 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2234 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2235 ;; ; Does not include "\Recent"
2237 ;; flag-keyword = atom
2239 ;; flag-extension = "\" atom
2240 ;; ; Future expansion. Client implementations
2241 ;; ; MUST accept flag-extension flags. Server
2242 ;; ; implementations MUST NOT generate
2243 ;; ; flag-extension flags except as defined by
2244 ;; ; future standard or standards-track
2245 ;; ; revisions of this specification.
2247 (defun imap-parse-flag-list ()
2248 (let (flag-list start)
2249 (assert (eq (char-after) ?\() t "In imap-parse-flag-list")
2250 (while (and (not (eq (char-after) ?\)))
2253 ;; next line for Courier IMAP bug.
2254 (skip-chars-forward " ")
2256 (> (skip-chars-forward "^ )" (imap-point-at-eol)) 0))
2257 (push (buffer-substring start (point)) flag-list))
2258 (assert (eq (char-after) ?\)) t "In imap-parse-flag-list")
2260 (nreverse flag-list)))
2262 ;; envelope = "(" env-date SP env-subject SP env-from SP env-sender SP
2263 ;; env-reply-to SP env-to SP env-cc SP env-bcc SP
2264 ;; env-in-reply-to SP env-message-id ")"
2266 ;; env-bcc = "(" 1*address ")" / nil
2268 ;; env-cc = "(" 1*address ")" / nil
2270 ;; env-date = nstring
2272 ;; env-from = "(" 1*address ")" / nil
2274 ;; env-in-reply-to = nstring
2276 ;; env-message-id = nstring
2278 ;; env-reply-to = "(" 1*address ")" / nil
2280 ;; env-sender = "(" 1*address ")" / nil
2282 ;; env-subject = nstring
2284 ;; env-to = "(" 1*address ")" / nil
2286 (defun imap-parse-envelope ()
2287 (when (eq (char-after) ?\()
2289 (vector (prog1 (imap-parse-nstring) ;; date
2291 (prog1 (imap-parse-nstring) ;; subject
2293 (prog1 (imap-parse-address-list) ;; from
2295 (prog1 (imap-parse-address-list) ;; sender
2297 (prog1 (imap-parse-address-list) ;; reply-to
2299 (prog1 (imap-parse-address-list) ;; to
2301 (prog1 (imap-parse-address-list) ;; cc
2303 (prog1 (imap-parse-address-list) ;; bcc
2305 (prog1 (imap-parse-nstring) ;; in-reply-to
2307 (prog1 (imap-parse-nstring) ;; message-id
2310 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2312 (defsubst imap-parse-string-list ()
2313 (cond ((eq (char-after) ?\() ;; body-fld-param
2316 (while (setq str (imap-parse-string))
2318 ;; buggy stalker communigate pro 3.0 doesn't print SPC
2319 ;; between body-fld-param's sometimes
2320 (or (eq (char-after) ?\")
2322 (nreverse strlist)))
2326 ;; body-extension = nstring / number /
2327 ;; "(" body-extension *(SP body-extension) ")"
2328 ;; ; Future expansion. Client implementations
2329 ;; ; MUST accept body-extension fields. Server
2330 ;; ; implementations MUST NOT generate
2331 ;; ; body-extension fields except as defined by
2332 ;; ; future standard or standards-track
2333 ;; ; revisions of this specification.
2335 (defun imap-parse-body-extension ()
2336 (if (eq (char-after) ?\()
2339 (push (imap-parse-body-extension) b-e)
2340 (while (eq (char-after) ?\ )
2342 (push (imap-parse-body-extension) b-e))
2343 (assert (eq (char-after) ?\)) t "In imap-parse-body-extension")
2346 (or (imap-parse-number)
2347 (imap-parse-nstring))))
2349 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2350 ;; *(SP body-extension)]]
2351 ;; ; MUST NOT be returned on non-extensible
2354 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2355 ;; *(SP body-extension)]]
2356 ;; ; MUST NOT be returned on non-extensible
2359 (defsubst imap-parse-body-ext ()
2361 (when (eq (char-after) ?\ ) ;; body-fld-dsp
2364 (if (eq (char-after) ?\()
2367 (push (imap-parse-string) dsp)
2369 (push (imap-parse-string-list) dsp)
2371 (assert (imap-parse-nil) t "In imap-parse-body-ext"))
2372 (push (nreverse dsp) ext))
2373 (when (eq (char-after) ?\ ) ;; body-fld-lang
2375 (if (eq (char-after) ?\()
2376 (push (imap-parse-string-list) ext)
2377 (push (imap-parse-nstring) ext))
2378 (while (eq (char-after) ?\ ) ;; body-extension
2380 (setq ext (append (imap-parse-body-extension) ext)))))
2383 ;; body = "(" body-type-1part / body-type-mpart ")"
2385 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2386 ;; *(SP body-extension)]]
2387 ;; ; MUST NOT be returned on non-extensible
2390 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2391 ;; *(SP body-extension)]]
2392 ;; ; MUST NOT be returned on non-extensible
2395 ;; body-fields = body-fld-param SP body-fld-id SP body-fld-desc SP
2396 ;; body-fld-enc SP body-fld-octets
2398 ;; body-fld-desc = nstring
2400 ;; body-fld-dsp = "(" string SP body-fld-param ")" / nil
2402 ;; body-fld-enc = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2403 ;; "QUOTED-PRINTABLE") DQUOTE) / string
2405 ;; body-fld-id = nstring
2407 ;; body-fld-lang = nstring / "(" string *(SP string) ")"
2409 ;; body-fld-lines = number
2411 ;; body-fld-md5 = nstring
2413 ;; body-fld-octets = number
2415 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2417 ;; body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2418 ;; [SP body-ext-1part]
2420 ;; body-type-basic = media-basic SP body-fields
2421 ;; ; MESSAGE subtype MUST NOT be "RFC822"
2423 ;; body-type-msg = media-message SP body-fields SP envelope
2424 ;; SP body SP body-fld-lines
2426 ;; body-type-text = media-text SP body-fields SP body-fld-lines
2428 ;; body-type-mpart = 1*body SP media-subtype
2429 ;; [SP body-ext-mpart]
2431 ;; media-basic = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2432 ;; "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2433 ;; ; Defined in [MIME-IMT]
2435 ;; media-message = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2436 ;; ; Defined in [MIME-IMT]
2438 ;; media-subtype = string
2439 ;; ; Defined in [MIME-IMT]
2441 ;; media-text = DQUOTE "TEXT" DQUOTE SP media-subtype
2442 ;; ; Defined in [MIME-IMT]
2444 (defun imap-parse-body ()
2446 (when (eq (char-after) ?\()
2448 (if (eq (char-after) ?\()
2450 (while (and (eq (char-after) ?\()
2451 (setq subbody (imap-parse-body)))
2452 ;; buggy stalker communigate pro 3.0 insert a SPC between
2453 ;; parts in multiparts
2454 (when (and (eq (char-after) ?\ )
2455 (eq (char-after (1+ (point))) ?\())
2457 (push subbody body))
2459 (push (imap-parse-string) body) ;; media-subtype
2460 (when (eq (char-after) ?\ ) ;; body-ext-mpart:
2462 (if (eq (char-after) ?\() ;; body-fld-param
2463 (push (imap-parse-string-list) body)
2464 (push (and (imap-parse-nil) nil) body))
2466 (append (imap-parse-body-ext) body))) ;; body-ext-...
2467 (assert (eq (char-after) ?\)) t "In imap-parse-body")
2471 (push (imap-parse-string) body) ;; media-type
2473 (push (imap-parse-string) body) ;; media-subtype
2475 ;; next line for Sun SIMS bug
2476 (and (eq (char-after) ? ) (imap-forward))
2477 (if (eq (char-after) ?\() ;; body-fld-param
2478 (push (imap-parse-string-list) body)
2479 (push (and (imap-parse-nil) nil) body))
2481 (push (imap-parse-nstring) body) ;; body-fld-id
2483 (push (imap-parse-nstring) body) ;; body-fld-desc
2485 ;; next `or' for Sun SIMS bug, it regard body-fld-enc as a
2486 ;; nstring and return NIL instead of defaulting back to 7BIT
2487 ;; as the standard says.
2488 (push (or (imap-parse-nstring) "7BIT") body) ;; body-fld-enc
2490 (push (imap-parse-number) body) ;; body-fld-octets
2492 ;; ok, we're done parsing the required parts, what comes now is one
2495 ;; envelope (then we're parsing body-type-msg)
2496 ;; body-fld-lines (then we're parsing body-type-text)
2497 ;; body-ext-1part (then we're parsing body-type-basic)
2499 ;; the problem is that the two first are in turn optionally followed
2500 ;; by the third. So we parse the first two here (if there are any)...
2502 (when (eq (char-after) ?\ )
2505 (cond ((eq (char-after) ?\() ;; body-type-msg:
2506 (push (imap-parse-envelope) body) ;; envelope
2508 (push (imap-parse-body) body) ;; body
2509 ;; buggy stalker communigate pro 3.0 doesn't print
2510 ;; number of lines in message/rfc822 attachment
2511 (if (eq (char-after) ?\))
2514 (push (imap-parse-number) body))) ;; body-fld-lines
2515 ((setq lines (imap-parse-number)) ;; body-type-text:
2516 (push lines body)) ;; body-fld-lines
2518 (backward-char))))) ;; no match...
2520 ;; ...and then parse the third one here...
2522 (when (eq (char-after) ?\ ) ;; body-ext-1part:
2524 (push (imap-parse-nstring) body) ;; body-fld-md5
2525 (setq body (append (imap-parse-body-ext) body))) ;; body-ext-1part..
2527 (assert (eq (char-after) ?\)) t "In imap-parse-body 2")
2531 (when imap-debug ; (untrace-all)
2533 (buffer-disable-undo (get-buffer-create imap-debug))
2534 (mapcar (lambda (f) (trace-function-background f imap-debug))
2546 imap-interactive-login
2562 imap-send-command-wait
2567 imap-current-mailbox
2568 imap-current-mailbox-p-1
2569 imap-current-mailbox-p
2570 imap-mailbox-select-1
2572 imap-mailbox-examine-1
2573 imap-mailbox-examine
2574 imap-mailbox-unselect
2575 imap-mailbox-expunge
2577 imap-mailbox-create-1
2583 imap-mailbox-subscribe
2584 imap-mailbox-unsubscribe
2586 imap-mailbox-acl-get
2587 imap-mailbox-acl-set
2588 imap-mailbox-acl-delete
2589 imap-current-message
2590 imap-list-to-message-set
2597 imap-message-flag-permanent-p
2598 imap-message-flags-set
2599 imap-message-flags-del
2600 imap-message-flags-add
2601 imap-message-copyuid-1
2602 imap-message-copyuid
2604 imap-message-appenduid-1
2605 imap-message-appenduid
2617 imap-parse-resp-text
2618 imap-parse-resp-text-code
2619 imap-parse-data-list
2623 imap-parse-flag-list
2625 imap-parse-body-extension
2631 ;;; imap.el ends here