ff254c5f8155ec1333387df3354fec132b967b65
[elisp/gnus.git-] / lisp / mail-source.el
1 ;;; mail-source.el --- functions for fetching mail
2 ;; Copyright (C) 1999, 2000 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; Keywords: news, mail
6
7 ;; This file is part of GNU Emacs.
8
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)
12 ;; any later version.
13
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.
18
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.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (eval-when-compile (require 'cl))
29 (eval-and-compile
30   (autoload 'pop3-movemail "pop3")
31   (autoload 'pop3-get-message-count "pop3"))
32 (require 'format-spec)
33
34 (defgroup mail-source nil
35   "The mail-fetching library."
36   :group 'gnus)
37
38 (defcustom mail-sources nil
39   "*Where the mail backends will look for incoming mail.
40 This variable is a list of mail source specifiers."
41   :group 'mail-source
42   :type 'sexp)
43
44 (defcustom mail-source-primary-source nil
45   "*Primary source for incoming mail.
46 If non-nil, this maildrop will be checked periodically for new mail."
47   :group 'mail-source
48   :type 'sexp)
49
50 (defcustom mail-source-crash-box "~/.emacs-mail-crash-box"
51   "File where mail will be stored while processing it."
52   :group 'mail-source
53   :type 'file)
54
55 (defcustom mail-source-directory "~/Mail/"
56   "Directory where files (if any) will be stored."
57   :group 'mail-source
58   :type 'directory)
59
60 (defcustom mail-source-default-file-modes 384
61   "Set the mode bits of all new mail files to this integer."
62   :group 'mail-source
63   :type 'integer)
64
65 (defcustom mail-source-delete-incoming nil
66   "*If non-nil, delete incoming files after handling."
67   :group 'mail-source
68   :type 'boolean)
69
70 (defcustom mail-source-report-new-mail-interval 5
71   "Interval in minutes between checks for new mail."
72   :group 'mail-source
73   :type 'number)
74
75 (defcustom mail-source-idle-time-delay 5
76   "Number of idle seconds to wait before checking for new mail."
77   :group 'mail-source
78   :type 'number)
79
80 ;;; Internal variables.
81
82 (defvar mail-source-string ""
83   "A dynamically bound string that says what the current mail source is.")
84
85 (defvar mail-source-new-mail-available nil
86   "Flag indicating when new mail is available.")
87
88 (eval-and-compile
89   (defvar mail-source-common-keyword-map
90     '((:plugged))
91     "Mapping from keywords to default values.
92 Common keywords should be listed here.")
93
94   (defvar mail-source-keyword-map
95     '((file
96        (:prescript)
97        (:prescript-delay)
98        (:postscript)
99        (:path (or (getenv "MAIL")
100                   (concat "/usr/spool/mail/" (user-login-name)))))
101       (directory
102        (:path)
103        (:suffix ".spool")
104        (:predicate identity))
105       (pop
106        (:prescript)
107        (:prescript-delay)
108        (:postscript)
109        (:server (getenv "MAILHOST"))
110        (:port 110)
111        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
112        (:program)
113        (:function)
114        (:password)
115        (:connection)
116        (:authentication password))
117       (maildir
118        (:path (or (getenv "MAILDIR") "~/Maildir/"))
119        (:subdirs ("new" "cur"))
120        (:function))
121       (imap
122        (:server (getenv "MAILHOST"))
123        (:port)
124        (:stream)
125        (:authentication)
126        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
127        (:password)
128        (:mailbox "INBOX")
129        (:predicate "UNSEEN UNDELETED")
130        (:fetchflag "\\Deleted")
131        (:dontexpunge))
132       (webmail
133        (:subtype hotmail)
134        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
135        (:password)
136        (:dontexpunge)
137        (:authentication password)))
138     "Mapping from keywords to default values.
139 All keywords that can be used must be listed here."))
140
141 (defvar mail-source-fetcher-alist
142   '((file mail-source-fetch-file)
143     (directory mail-source-fetch-directory)
144     (pop mail-source-fetch-pop)
145     (maildir mail-source-fetch-maildir)
146     (imap mail-source-fetch-imap)
147     (webmail mail-source-fetch-webmail))
148   "A mapping from source type to fetcher function.")
149
150 (defvar mail-source-password-cache nil)
151
152 (defvar mail-source-plugged t)
153
154 ;;; Functions
155
156 (eval-and-compile
157   (defun mail-source-strip-keyword (keyword)
158     "Strip the leading colon off the KEYWORD."
159     (intern (substring (symbol-name keyword) 1))))
160
161 (eval-and-compile
162   (defun mail-source-bind-1 (type)
163     (let* ((defaults (cdr (assq type mail-source-keyword-map)))
164            default bind)
165       (while (setq default (pop defaults))
166         (push (list (mail-source-strip-keyword (car default))
167                     nil)
168               bind))
169       bind)))
170
171 (defmacro mail-source-bind (type-source &rest body)
172   "Return a `let' form that binds all variables in source TYPE.
173 TYPE-SOURCE is a list where the first element is the TYPE, and
174 the second variable is the SOURCE.
175 At run time, the mail source specifier SOURCE will be inspected,
176 and the variables will be set according to it.  Variables not
177 specified will be given default values.
178
179 After this is done, BODY will be executed in the scope
180 of the `let' form.
181
182 The variables bound and their default values are described by
183 the `mail-source-keyword-map' variable."
184   `(let ,(mail-source-bind-1 (car type-source))
185      (mail-source-set-1 ,(cadr type-source))
186      ,@body))
187
188 (put 'mail-source-bind 'lisp-indent-function 1)
189 (put 'mail-source-bind 'edebug-form-spec '(form body))
190
191 (defun mail-source-set-1 (source)
192   (let* ((type (pop source))
193          (defaults (cdr (assq type mail-source-keyword-map)))
194          default value keyword)
195     (while (setq default (pop defaults))
196       (set (mail-source-strip-keyword (setq keyword (car default)))
197            (if (setq value (plist-get source keyword))
198                (mail-source-value value)
199              (mail-source-value (cadr default)))))))
200
201 (eval-and-compile
202   (defun mail-source-bind-common-1 ()
203     (let* ((defaults mail-source-common-keyword-map)
204            default bind)
205       (while (setq default (pop defaults))
206         (push (list (mail-source-strip-keyword (car default))
207                     nil)
208               bind))
209       bind)))
210
211 (defun mail-source-set-common-1 (source)
212   (let* ((type (pop source))
213          (defaults mail-source-common-keyword-map)
214          (defaults-1 (cdr (assq type mail-source-keyword-map)))
215          default value keyword)
216     (while (setq default (pop defaults))
217       (set (mail-source-strip-keyword (setq keyword (car default)))
218            (if (setq value (plist-get source keyword))
219                (mail-source-value value)
220              (if (setq value (assq  keyword defaults-1))
221                  (mail-source-value (cadr value))
222                (mail-source-value (cadr default))))))))
223
224 (defmacro mail-source-bind-common (source &rest body)
225   "Return a `let' form that binds all common variables.
226 See `mail-source-bind'."
227   `(let ,(mail-source-bind-common-1)
228      (mail-source-set-common-1 source)
229      ,@body))
230
231 (put 'mail-source-bind-common 'lisp-indent-function 1)
232 (put 'mail-source-bind-common 'edebug-form-spec '(form body))
233
234 (defun mail-source-value (value)
235   "Return the value of VALUE."
236   (cond
237    ;; String
238    ((stringp value)
239     value)
240    ;; Function
241    ((and (listp value)
242          (functionp (car value)))
243     (eval value))
244    ;; Just return the value.
245    (t
246     value)))
247
248 (defun mail-source-fetch (source callback)
249   "Fetch mail from SOURCE and call CALLBACK zero or more times.
250 CALLBACK will be called with the name of the file where (some of)
251 the mail from SOURCE is put.
252 Return the number of files that were found."
253   (mail-source-bind-common source
254     (if (or mail-source-plugged plugged)
255         (save-excursion
256           (let ((function (cadr (assq (car source) mail-source-fetcher-alist)))
257                 (found 0))
258             (unless function
259               (error "%S is an invalid mail source specification" source))
260             ;; If there's anything in the crash box, we do it first.
261             (when (file-exists-p mail-source-crash-box)
262               (message "Processing mail from %s..." mail-source-crash-box)
263               (setq found (mail-source-callback
264                            callback mail-source-crash-box)))
265             (+ found
266                (condition-case err
267                    (funcall function source callback)
268                  (error
269                   (unless (yes-or-no-p
270                            (format "Mail source error (%s).  Continue? " err))
271                     (error "Cannot get new mail."))
272                   0))))))))
273
274 (defun mail-source-make-complex-temp-name (prefix)
275   (let ((newname (make-temp-name prefix))
276         (newprefix prefix))
277     (while (file-exists-p newname)
278       (setq newprefix (concat newprefix "x"))
279       (setq newname (make-temp-name newprefix)))
280     newname))
281
282 (defun mail-source-callback (callback info)
283   "Call CALLBACK on the mail file, and then remove the mail file.
284 Pass INFO on to CALLBACK."
285   (if (or (not (file-exists-p mail-source-crash-box))
286           (zerop (nth 7 (file-attributes mail-source-crash-box))))
287       (progn
288         (when (file-exists-p mail-source-crash-box)
289           (delete-file mail-source-crash-box))
290         0)
291     (prog1
292         (funcall callback mail-source-crash-box info)
293       (when (file-exists-p mail-source-crash-box)
294         ;; Delete or move the incoming mail out of the way.
295         (if mail-source-delete-incoming
296             (delete-file mail-source-crash-box)
297           (let ((incoming
298                  (mail-source-make-complex-temp-name
299                   (expand-file-name
300                    "Incoming" mail-source-directory))))
301             (unless (file-exists-p (file-name-directory incoming))
302               (make-directory (file-name-directory incoming) t))
303             (rename-file mail-source-crash-box incoming t)))))))
304
305 (defun mail-source-movemail (from to)
306   "Move FROM to TO using movemail."
307   (if (not (file-writable-p to))
308       (error "Can't write to crash box %s.  Not moving mail" to)
309     (let ((to (file-truename (expand-file-name to)))
310           errors result)
311       (setq to (file-truename to)
312             from (file-truename from))
313       ;; Set TO if have not already done so, and rename or copy
314       ;; the file FROM to TO if and as appropriate.
315       (cond
316        ((file-exists-p to)
317         ;; The crash box exists already.
318         t)
319        ((not (file-exists-p from))
320         ;; There is no inbox.
321         (setq to nil))
322        ((zerop (nth 7 (file-attributes from)))
323         ;; Empty file.
324         (setq to nil))
325        (t
326         ;; If getting from mail spool directory, use movemail to move
327         ;; rather than just renaming, so as to interlock with the
328         ;; mailer.
329         (unwind-protect
330             (save-excursion
331               (setq errors (generate-new-buffer " *mail source loss*"))
332               (let ((default-directory "/"))
333                 (setq result
334                       (apply
335                        'call-process
336                        (append
337                         (list
338                          (expand-file-name "movemail" exec-directory)
339                          nil errors nil from to)))))
340               (when (file-exists-p to)
341                 (set-file-modes to mail-source-default-file-modes))
342               (if (and (not (buffer-modified-p errors))
343                        (zerop result))
344                   ;; No output => movemail won.
345                   t
346                 (set-buffer errors)
347                 ;; There may be a warning about older revisions.  We
348                 ;; ignore that.
349                 (goto-char (point-min))
350                 (if (search-forward "older revision" nil t)
351                     t
352                   ;; Probably a real error.
353                   (subst-char-in-region (point-min) (point-max) ?\n ?\  )
354                   (goto-char (point-max))
355                   (skip-chars-backward " \t")
356                   (delete-region (point) (point-max))
357                   (goto-char (point-min))
358                   (when (looking-at "movemail: ")
359                     (delete-region (point-min) (match-end 0)))
360                   (unless (yes-or-no-p
361                            (format "movemail: %s (%d return).  Continue? "
362                                    (buffer-string) result))
363                     (error "%s" (buffer-string)))
364                   (setq to nil)))))))
365       (when (and errors
366                  (buffer-name errors))
367         (kill-buffer errors))
368       ;; Return whether we moved successfully or not.
369       to)))
370
371 (defun mail-source-movemail-and-remove (from to)
372   "Move FROM to TO using movemail, then remove FROM if empty."
373   (or (not (mail-source-movemail from to))
374       (not (zerop (nth 7 (file-attributes from))))
375       (delete-file from)))
376
377 (defvar mail-source-read-passwd nil)
378 (defun mail-source-read-passwd (prompt &rest args)
379   "Read a password using PROMPT.
380 If ARGS, PROMPT is used as an argument to `format'."
381   (let ((prompt
382          (if args
383              (apply 'format prompt args)
384            prompt)))
385     (unless mail-source-read-passwd
386       (if (or (fboundp 'read-passwd) (load "passwd" t))
387           (setq mail-source-read-passwd 'read-passwd)
388         (unless (fboundp 'ange-ftp-read-passwd)
389           (autoload 'ange-ftp-read-passwd "ange-ftp"))
390         (setq mail-source-read-passwd 'ange-ftp-read-passwd)))
391     (funcall mail-source-read-passwd prompt)))
392
393 (defun mail-source-fetch-with-program (program)
394   (zerop (call-process shell-file-name nil nil nil
395                        shell-command-switch program)))
396
397 (defun mail-source-run-script (script spec &optional delay)
398   (when script
399     (if (and (symbolp script) (fboundp script))
400         (funcall script)
401       (mail-source-call-script
402        (format-spec script spec))))
403   (when delay
404     (sleep-for delay)))
405
406 (defun mail-source-call-script (script)
407   (let ((background nil))
408     (when (string-match "& *$" script)
409       (setq script (substring script 0 (match-beginning 0))
410             background 0))
411     (call-process shell-file-name nil background nil
412                   shell-command-switch script)))
413
414 ;;;
415 ;;; Different fetchers
416 ;;;
417
418 (defun mail-source-fetch-file (source callback)
419   "Fetcher for single-file sources."
420   (mail-source-bind (file source)
421     (mail-source-run-script
422      prescript (format-spec-make ?t mail-source-crash-box)
423      prescript-delay)
424     (let ((mail-source-string (format "file:%s" path)))
425       (if (mail-source-movemail path mail-source-crash-box)
426           (prog1
427               (mail-source-callback callback path)
428             (mail-source-run-script
429              postscript (format-spec-make ?t mail-source-crash-box)))
430         0))))
431
432 (defun mail-source-fetch-directory (source callback)
433   "Fetcher for directory sources."
434   (mail-source-bind (directory source)
435     (let ((found 0)
436           (mail-source-string (format "directory:%s" path)))
437       (dolist (file (directory-files
438                      path t (concat (regexp-quote suffix) "$")))
439         (when (and (file-regular-p file)
440                    (funcall predicate file)
441                    (mail-source-movemail file mail-source-crash-box))
442           (incf found (mail-source-callback callback file))))
443       found)))
444
445 (defun mail-source-fetch-pop (source callback)
446   "Fetcher for single-file sources."
447   (mail-source-bind (pop source)
448     (mail-source-run-script
449      prescript
450      (format-spec-make ?p password ?t mail-source-crash-box
451                        ?s server ?P port ?u user)
452      prescript-delay)
453     (let ((from (format "%s:%s:%s" server user port))
454           (mail-source-string (format "pop:%s@%s" user server))
455           result)
456       (when (eq authentication 'password)
457         (setq password
458               (or password
459                   (cdr (assoc from mail-source-password-cache))
460                   (mail-source-read-passwd
461                    (format "Password for %s at %s: " user server)))))
462       (when server
463         (setenv "MAILHOST" server))
464       (setq result
465             (cond
466              (program
467               (mail-source-fetch-with-program
468                (format-spec
469                 program
470                 (format-spec-make ?p password ?t mail-source-crash-box
471                                   ?s server ?P port ?u user))))
472              (function
473               (funcall function mail-source-crash-box))
474              ;; The default is to use pop3.el.
475              (t
476               (let ((pop3-password password)
477                     (pop3-maildrop user)
478                     (pop3-mailhost server)
479                     (pop3-port port)
480                     (pop3-authentication-scheme
481                      (if (eq authentication 'apop) 'apop 'pass))
482                     (pop3-connection-type connection))
483                 (save-excursion (pop3-movemail mail-source-crash-box))))))
484       (if result
485           (progn
486             (when (eq authentication 'password)
487               (unless (assoc from mail-source-password-cache)
488                 (push (cons from password) mail-source-password-cache)))
489             (prog1
490                 (mail-source-callback callback server)
491               ;; Update display-time's mail flag, if relevant.
492               (if (equal source mail-source-primary-source)
493                   (setq mail-source-new-mail-available nil))
494               (mail-source-run-script
495                postscript
496                (format-spec-make ?p password ?t mail-source-crash-box
497                                  ?s server ?P port ?u user))))
498         ;; We nix out the password in case the error
499         ;; was because of a wrong password being given.
500         (setq mail-source-password-cache
501               (delq (assoc from mail-source-password-cache)
502                     mail-source-password-cache))
503         0))))
504
505 (defun mail-source-check-pop (source)
506   "Check whether there is new mail."
507   (mail-source-bind (pop source)
508     (let ((from (format "%s:%s:%s" server user port))
509           (mail-source-string (format "pop:%s@%s" user server))
510           result)
511       (when (eq authentication 'password)
512         (setq password
513               (or password
514                   (cdr (assoc from mail-source-password-cache))
515                   (mail-source-read-passwd
516                    (format "Password for %s at %s: " user server))))
517         (unless (assoc from mail-source-password-cache)
518           (push (cons from password) mail-source-password-cache)))
519       (when server
520         (setenv "MAILHOST" server))
521       (setq result
522             (cond
523              ;; No easy way to check whether mail is waiting for these.
524              (program)
525              (function)
526              ;; The default is to use pop3.el.
527              (t
528               (let ((pop3-password password)
529                     (pop3-maildrop user)
530                     (pop3-mailhost server)
531                     (pop3-port port)
532                     (pop3-authentication-scheme
533                      (if (eq authentication 'apop) 'apop 'pass)))
534                 (save-excursion (pop3-get-message-count))))))
535       (if result
536           ;; Inform display-time that we have new mail.
537           (setq mail-source-new-mail-available (> result 0))
538         ;; We nix out the password in case the error
539         ;; was because of a wrong password being given.
540         (setq mail-source-password-cache
541               (delq (assoc from mail-source-password-cache)
542                     mail-source-password-cache)))
543       result)))
544
545 (defun mail-source-new-mail-p ()
546   "Handler for `display-time' to indicate when new mail is available."
547   ;; Only report flag setting; flag is updated on a different schedule.
548   mail-source-new-mail-available)
549
550
551 (defvar mail-source-report-new-mail nil)
552 (defvar mail-source-report-new-mail-timer nil)
553 (defvar mail-source-report-new-mail-idle-timer nil)
554
555 (eval-when-compile (require 'timer))
556
557 (defun mail-source-start-idle-timer ()
558   ;; Start our idle timer if necessary, so we delay the check until the
559   ;; user isn't typing.
560   (unless mail-source-report-new-mail-idle-timer
561     (setq mail-source-report-new-mail-idle-timer
562           (run-with-idle-timer
563            mail-source-idle-time-delay
564            nil
565            (lambda ()
566              (setq mail-source-report-new-mail-idle-timer nil)
567              (mail-source-check-pop mail-source-primary-source))))
568     ;; Since idle timers created when Emacs is already in the idle
569     ;; state don't get activated until Emacs _next_ becomes idle, we
570     ;; need to force our timer to be considered active now.  We do
571     ;; this by being naughty and poking the timer internals directly
572     ;; (element 0 of the vector is nil if the timer is active).
573     (aset mail-source-report-new-mail-idle-timer 0 nil)))
574
575 (defun mail-source-report-new-mail (arg)
576   "Toggle whether to report when new mail is available.
577 This only works when `display-time' is enabled."
578   (interactive "P")
579   (if (not mail-source-primary-source)
580       (error "Need to set `mail-source-primary-source' to check for new mail."))
581   (let ((on (if (null arg)
582                 (not mail-source-report-new-mail)
583               (> (prefix-numeric-value arg) 0))))
584     (setq mail-source-report-new-mail on)
585     (and mail-source-report-new-mail-timer
586          (cancel-timer mail-source-report-new-mail-timer))
587     (and mail-source-report-new-mail-idle-timer
588          (cancel-timer mail-source-report-new-mail-idle-timer))
589     (setq mail-source-report-new-mail-timer nil)
590     (setq mail-source-report-new-mail-idle-timer nil)
591     (if on
592         (progn
593           (require 'time)
594           (setq display-time-mail-function #'mail-source-new-mail-p)
595           ;; Set up the main timer.
596           (setq mail-source-report-new-mail-timer
597                 (run-at-time t (* 60 mail-source-report-new-mail-interval)
598                              #'mail-source-start-idle-timer))
599           ;; When you get new mail, clear "Mail" from the mode line.
600           (add-hook 'nnmail-post-get-new-mail-hook
601                     'display-time-event-handler)
602           (message "Mail check enabled"))
603       (setq display-time-mail-function nil)
604       (remove-hook 'nnmail-post-get-new-mail-hook
605                    'display-time-event-handler)
606       (message "Mail check disabled"))))
607
608 (defun mail-source-fetch-maildir (source callback)
609   "Fetcher for maildir sources."
610   (mail-source-bind (maildir source)
611     (let ((found 0)
612           mail-source-string)
613       (unless (string-match "/$" path)
614         (setq path (concat path "/")))
615       (dolist (subdir subdirs)
616         (when (file-directory-p (concat path subdir))
617           (setq mail-source-string (format "maildir:%s%s" path subdir))
618           (dolist (file (directory-files (concat path subdir) t))
619             (when (and (not (file-directory-p file))
620                        (not (if function
621                                 (funcall function file mail-source-crash-box)
622                               (let ((coding-system-for-write 
623                                      mm-text-coding-system)
624                                     (coding-system-for-read 
625                                      mm-text-coding-system))
626                                 (with-temp-file mail-source-crash-box
627                                   (insert-file-contents file)
628                                   (goto-char (point-min))
629                                   (unless (looking-at "\n*From ")
630                                     (insert "From maildir " 
631                                             (current-time-string) "\n"))
632                                   (while (re-search-forward "^From " nil t)
633                                     (replace-match ">From "))
634                                   (goto-char (point-max))
635                                   (insert "\n\n"))
636                                 (delete-file file)))))
637               (incf found (mail-source-callback callback file))))))
638       found)))
639
640 (eval-and-compile
641   (autoload 'imap-open "imap")
642   (autoload 'imap-authenticate "imap")
643   (autoload 'imap-mailbox-select "imap")
644   (autoload 'imap-mailbox-unselect "imap")
645   (autoload 'imap-mailbox-close "imap")
646   (autoload 'imap-search "imap")
647   (autoload 'imap-fetch "imap")
648   (autoload 'imap-close "imap")
649   (autoload 'imap-error-text "imap")
650   (autoload 'imap-message-flags-add "imap")
651   (autoload 'imap-list-to-message-set "imap")
652   (autoload 'nnheader-ms-strip-cr "nnheader"))
653
654 (defun mail-source-fetch-imap (source callback)
655   "Fetcher for imap sources."
656   (mail-source-bind (imap source)
657     (let ((from (format "%s:%s:%s" server user port))
658           (found 0)
659           (buf (get-buffer-create
660                 (format " *imap source %s:%s:%s *" server user mailbox)))
661           (mail-source-string (format "imap:%s:%s" server mailbox))
662           remove)
663       (if (and (imap-open server port stream authentication buf)
664                (imap-authenticate
665                 user (or (cdr (assoc from mail-source-password-cache))
666                          password) buf)
667                (imap-mailbox-select mailbox nil buf))
668           (let (str
669                 (coding-system-for-write 'binary)
670                 (output-coding-system 'binary))
671             (with-temp-file mail-source-crash-box
672               ;; remember password
673               (with-current-buffer buf
674                 (when (or imap-password
675                           (assoc from mail-source-password-cache))
676                   (push (cons from imap-password) mail-source-password-cache)))
677               ;; if predicate is nil, use all uids
678               (dolist (uid (imap-search (or predicate "1:*") buf))
679                 (when (setq str (imap-fetch uid "RFC822.PEEK" 'RFC822 nil buf))
680                   (push uid remove)
681                   (insert "From imap " (current-time-string) "\n")
682                   (save-excursion
683                     (insert str "\n\n"))
684                   (while (re-search-forward "^From " nil t)
685                     (replace-match ">From "))
686                   (goto-char (point-max))))
687               (nnheader-ms-strip-cr))
688             (incf found (mail-source-callback callback server))
689             (when (and remove fetchflag)
690               (imap-message-flags-add
691                (imap-list-to-message-set remove) fetchflag nil buf))
692             (if dontexpunge
693                 (imap-mailbox-unselect buf)
694               (imap-mailbox-close buf))
695             (imap-close buf))
696         (imap-close buf)
697         ;; We nix out the password in case the error
698         ;; was because of a wrong password being given.
699         (setq mail-source-password-cache
700               (delq (assoc from mail-source-password-cache)
701                     mail-source-password-cache))
702         (error (imap-error-text buf)))
703       (kill-buffer buf)
704       found)))
705
706 (eval-and-compile
707   (autoload 'webmail-fetch "webmail"))
708
709 (defun mail-source-fetch-webmail (source callback)
710   "Fetch for webmail source."
711   (mail-source-bind (webmail source)
712     (let ((mail-source-string (format "webmail:%s:%s" subtype user))
713           (webmail-newmail-only dontexpunge)
714           (webmail-move-to-trash-can (not dontexpunge)))
715       (when (eq authentication 'password)
716         (setq password
717               (or password
718                   (cdr (assoc (format "webmail:%s:%s" subtype user) 
719                               mail-source-password-cache))
720                   (mail-source-read-passwd
721                    (format "Password for %s at %s: " user subtype))))
722         (when (and password
723                    (not (assoc (format "webmail:%s:%s" subtype user) 
724                                mail-source-password-cache)))
725           (push (cons (format "webmail:%s:%s" subtype user) password) 
726                 mail-source-password-cache)))
727       (webmail-fetch mail-source-crash-box subtype user password)
728       (mail-source-callback callback (symbol-name subtype)))))
729
730 (provide 'mail-source)
731
732 ;;; mail-source.el ends here