1 ;;; mail-source.el --- functions for fetching mail
2 ;; Copyright (C) 1999, 2000 Free Software Foundation, Inc.
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; Keywords: news, mail
7 ;; This file is part of GNU Emacs.
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING. If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
28 (eval-when-compile (require 'cl))
30 (autoload 'pop3-movemail "pop3")
31 (autoload 'pop3-get-message-count "pop3"))
32 (require 'format-spec)
34 (defgroup mail-source nil
35 "The mail-fetching library."
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."
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."
50 (defcustom mail-source-crash-box "~/.emacs-mail-crash-box"
51 "File where mail will be stored while processing it."
55 (defcustom mail-source-directory "~/Mail/"
56 "Directory where files (if any) will be stored."
60 (defcustom mail-source-default-file-modes 384
61 "Set the mode bits of all new mail files to this integer."
65 (defcustom mail-source-delete-incoming nil
66 "*If non-nil, delete incoming files after handling."
70 (defcustom mail-source-report-new-mail-interval 5
71 "Interval in minutes between checks for new mail."
75 (defcustom mail-source-idle-time-delay 5
76 "Number of idle seconds to wait before checking for new mail."
80 ;;; Internal variables.
82 (defvar mail-source-string ""
83 "A dynamically bound string that says what the current mail source is.")
85 (defvar mail-source-new-mail-available nil
86 "Flag indicating when new mail is available.")
89 (defvar mail-source-common-keyword-map
91 "Mapping from keywords to default values.
92 Common keywords should be listed here.")
94 (defvar mail-source-keyword-map
99 (:path (or (getenv "MAIL")
100 (concat "/usr/spool/mail/" (user-login-name)))))
104 (:predicate identity))
109 (:server (getenv "MAILHOST"))
111 (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
115 (:authentication password))
117 (:path (or (getenv "MAILDIR") "~/Maildir/"))
118 (:subdirs ("new" "cur"))
121 (:server (getenv "MAILHOST"))
125 (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
128 (:predicate "UNSEEN UNDELETED")
129 (:fetchflag "\\Deleted")
133 (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
136 (:authentication password)))
137 "Mapping from keywords to default values.
138 All keywords that can be used must be listed here."))
140 (defvar mail-source-fetcher-alist
141 '((file mail-source-fetch-file)
142 (directory mail-source-fetch-directory)
143 (pop mail-source-fetch-pop)
144 (maildir mail-source-fetch-maildir)
145 (imap mail-source-fetch-imap)
146 (webmail mail-source-fetch-webmail))
147 "A mapping from source type to fetcher function.")
149 (defvar mail-source-password-cache nil)
151 (defvar mail-source-plugged t)
156 (defun mail-source-strip-keyword (keyword)
157 "Strip the leading colon off the KEYWORD."
158 (intern (substring (symbol-name keyword) 1))))
161 (defun mail-source-bind-1 (type)
162 (let* ((defaults (cdr (assq type mail-source-keyword-map)))
164 (while (setq default (pop defaults))
165 (push (list (mail-source-strip-keyword (car default))
170 (defmacro mail-source-bind (type-source &rest body)
171 "Return a `let' form that binds all variables in source TYPE.
172 TYPE-SOURCE is a list where the first element is the TYPE, and
173 the second variable is the SOURCE.
174 At run time, the mail source specifier SOURCE will be inspected,
175 and the variables will be set according to it. Variables not
176 specified will be given default values.
178 After this is done, BODY will be executed in the scope
181 The variables bound and their default values are described by
182 the `mail-source-keyword-map' variable."
183 `(let ,(mail-source-bind-1 (car type-source))
184 (mail-source-set-1 ,(cadr type-source))
187 (put 'mail-source-bind 'lisp-indent-function 1)
188 (put 'mail-source-bind 'edebug-form-spec '(form body))
190 (defun mail-source-set-1 (source)
191 (let* ((type (pop source))
192 (defaults (cdr (assq type mail-source-keyword-map)))
193 default value keyword)
194 (while (setq default (pop defaults))
195 (set (mail-source-strip-keyword (setq keyword (car default)))
196 (if (setq value (plist-get source keyword))
197 (mail-source-value value)
198 (mail-source-value (cadr default)))))))
201 (defun mail-source-bind-common-1 ()
202 (let* ((defaults mail-source-common-keyword-map)
204 (while (setq default (pop defaults))
205 (push (list (mail-source-strip-keyword (car default))
210 (defun mail-source-set-common-1 (source)
211 (let* ((type (pop source))
212 (defaults mail-source-common-keyword-map)
213 (defaults-1 (cdr (assq type mail-source-keyword-map)))
214 default value keyword)
215 (while (setq default (pop defaults))
216 (set (mail-source-strip-keyword (setq keyword (car default)))
217 (if (setq value (plist-get source keyword))
218 (mail-source-value value)
219 (if (setq value (assq keyword defaults-1))
220 (mail-source-value (cadr value))
221 (mail-source-value (cadr default))))))))
223 (defmacro mail-source-bind-common (source &rest body)
224 "Return a `let' form that binds all common variables.
225 See `mail-source-bind'."
226 `(let ,(mail-source-bind-common-1)
227 (mail-source-set-common-1 source)
230 (put 'mail-source-bind-common 'lisp-indent-function 1)
231 (put 'mail-source-bind-common 'edebug-form-spec '(form body))
233 (defun mail-source-value (value)
234 "Return the value of VALUE."
241 (functionp (car value)))
243 ;; Just return the value.
247 (defun mail-source-fetch (source callback)
248 "Fetch mail from SOURCE and call CALLBACK zero or more times.
249 CALLBACK will be called with the name of the file where (some of)
250 the mail from SOURCE is put.
251 Return the number of files that were found."
252 (mail-source-bind-common source
253 (if (or mail-source-plugged plugged)
255 (let ((function (cadr (assq (car source) mail-source-fetcher-alist)))
258 (error "%S is an invalid mail source specification" source))
259 ;; If there's anything in the crash box, we do it first.
260 (when (file-exists-p mail-source-crash-box)
261 (message "Processing mail from %s..." mail-source-crash-box)
262 (setq found (mail-source-callback
263 callback mail-source-crash-box)))
266 (funcall function source callback)
269 (format "Mail source error (%s). Continue? " err))
270 (error "Cannot get new mail."))
273 (defun mail-source-make-complex-temp-name (prefix)
274 (let ((newname (make-temp-name prefix))
276 (while (file-exists-p newname)
277 (setq newprefix (concat newprefix "x"))
278 (setq newname (make-temp-name newprefix)))
281 (defun mail-source-callback (callback info)
282 "Call CALLBACK on the mail file, and then remove the mail file.
283 Pass INFO on to CALLBACK."
284 (if (or (not (file-exists-p mail-source-crash-box))
285 (zerop (nth 7 (file-attributes mail-source-crash-box))))
287 (when (file-exists-p mail-source-crash-box)
288 (delete-file mail-source-crash-box))
291 (funcall callback mail-source-crash-box info)
292 (when (file-exists-p mail-source-crash-box)
293 ;; Delete or move the incoming mail out of the way.
294 (if mail-source-delete-incoming
295 (delete-file mail-source-crash-box)
297 (mail-source-make-complex-temp-name
299 "Incoming" mail-source-directory))))
300 (unless (file-exists-p (file-name-directory incoming))
301 (make-directory (file-name-directory incoming) t))
302 (rename-file mail-source-crash-box incoming t)))))))
304 (defun mail-source-movemail (from to)
305 "Move FROM to TO using movemail."
306 (if (not (file-writable-p to))
307 (error "Can't write to crash box %s. Not moving mail" to)
308 (let ((to (file-truename (expand-file-name to)))
310 (setq to (file-truename to)
311 from (file-truename from))
312 ;; Set TO if have not already done so, and rename or copy
313 ;; the file FROM to TO if and as appropriate.
316 ;; The crash box exists already.
318 ((not (file-exists-p from))
319 ;; There is no inbox.
321 ((zerop (nth 7 (file-attributes from)))
325 ;; If getting from mail spool directory, use movemail to move
326 ;; rather than just renaming, so as to interlock with the
330 (setq errors (generate-new-buffer " *mail source loss*"))
331 (let ((default-directory "/"))
337 (expand-file-name "movemail" exec-directory)
338 nil errors nil from to)))))
339 (when (file-exists-p to)
340 (set-file-modes to mail-source-default-file-modes))
341 (if (and (not (buffer-modified-p errors))
343 ;; No output => movemail won.
346 ;; There may be a warning about older revisions. We
348 (goto-char (point-min))
349 (if (search-forward "older revision" nil t)
351 ;; Probably a real error.
352 (subst-char-in-region (point-min) (point-max) ?\n ?\ )
353 (goto-char (point-max))
354 (skip-chars-backward " \t")
355 (delete-region (point) (point-max))
356 (goto-char (point-min))
357 (when (looking-at "movemail: ")
358 (delete-region (point-min) (match-end 0)))
360 (format "movemail: %s (%d return). Continue? "
361 (buffer-string) result))
362 (error "%s" (buffer-string)))
365 (buffer-name errors))
366 (kill-buffer errors))
367 ;; Return whether we moved successfully or not.
370 (defun mail-source-movemail-and-remove (from to)
371 "Move FROM to TO using movemail, then remove FROM if empty."
372 (or (not (mail-source-movemail from to))
373 (not (zerop (nth 7 (file-attributes from))))
376 (defvar mail-source-read-passwd nil)
377 (defun mail-source-read-passwd (prompt &rest args)
378 "Read a password using PROMPT.
379 If ARGS, PROMPT is used as an argument to `format'."
382 (apply 'format prompt args)
384 (unless mail-source-read-passwd
385 (if (or (fboundp 'read-passwd) (load "passwd" t))
386 (setq mail-source-read-passwd 'read-passwd)
387 (unless (fboundp 'ange-ftp-read-passwd)
388 (autoload 'ange-ftp-read-passwd "ange-ftp"))
389 (setq mail-source-read-passwd 'ange-ftp-read-passwd)))
390 (funcall mail-source-read-passwd prompt)))
392 (defun mail-source-fetch-with-program (program)
393 (zerop (call-process shell-file-name nil nil nil
394 shell-command-switch program)))
396 (defun mail-source-run-script (script spec &optional delay)
398 (if (and (symbolp script) (fboundp script))
400 (mail-source-call-script
401 (format-spec script spec))))
405 (defun mail-source-call-script (script)
406 (let ((background nil))
407 (when (string-match "& *$" script)
408 (setq script (substring script 0 (match-beginning 0))
410 (call-process shell-file-name nil background nil
411 shell-command-switch script)))
414 ;;; Different fetchers
417 (defun mail-source-fetch-file (source callback)
418 "Fetcher for single-file sources."
419 (mail-source-bind (file source)
420 (mail-source-run-script
421 prescript (format-spec-make ?t mail-source-crash-box)
423 (let ((mail-source-string (format "file:%s" path)))
424 (if (mail-source-movemail path mail-source-crash-box)
426 (mail-source-callback callback path)
427 (mail-source-run-script
428 postscript (format-spec-make ?t mail-source-crash-box)))
431 (defun mail-source-fetch-directory (source callback)
432 "Fetcher for directory sources."
433 (mail-source-bind (directory source)
435 (mail-source-string (format "directory:%s" path)))
436 (dolist (file (directory-files
437 path t (concat (regexp-quote suffix) "$")))
438 (when (and (file-regular-p file)
439 (funcall predicate file)
440 (mail-source-movemail file mail-source-crash-box))
441 (incf found (mail-source-callback callback file))))
444 (defun mail-source-fetch-pop (source callback)
445 "Fetcher for single-file sources."
446 (mail-source-bind (pop source)
447 (mail-source-run-script
449 (format-spec-make ?p password ?t mail-source-crash-box
450 ?s server ?P port ?u user)
452 (let ((from (format "%s:%s:%s" server user port))
453 (mail-source-string (format "pop:%s@%s" user server))
455 (when (eq authentication 'password)
458 (cdr (assoc from mail-source-password-cache))
459 (mail-source-read-passwd
460 (format "Password for %s at %s: " user server)))))
462 (setenv "MAILHOST" server))
466 (mail-source-fetch-with-program
469 (format-spec-make ?p password ?t mail-source-crash-box
470 ?s server ?P port ?u user))))
472 (funcall function mail-source-crash-box))
473 ;; The default is to use pop3.el.
475 (let ((pop3-password password)
477 (pop3-mailhost server)
479 (pop3-authentication-scheme
480 (if (eq authentication 'apop) 'apop 'pass)))
481 (save-excursion (pop3-movemail mail-source-crash-box))))))
484 (when (eq authentication 'password)
485 (unless (assoc from mail-source-password-cache)
486 (push (cons from password) mail-source-password-cache)))
488 (mail-source-callback callback server)
489 ;; Update display-time's mail flag, if relevant.
490 (if (equal source mail-source-primary-source)
491 (setq mail-source-new-mail-available nil))
492 (mail-source-run-script
494 (format-spec-make ?p password ?t mail-source-crash-box
495 ?s server ?P port ?u user))))
496 ;; We nix out the password in case the error
497 ;; was because of a wrong password being given.
498 (setq mail-source-password-cache
499 (delq (assoc from mail-source-password-cache)
500 mail-source-password-cache))
503 (defun mail-source-check-pop (source)
504 "Check whether there is new mail."
505 (mail-source-bind (pop source)
506 (let ((from (format "%s:%s:%s" server user port))
507 (mail-source-string (format "pop:%s@%s" user server))
509 (when (eq authentication 'password)
512 (cdr (assoc from mail-source-password-cache))
513 (mail-source-read-passwd
514 (format "Password for %s at %s: " user server))))
515 (unless (assoc from mail-source-password-cache)
516 (push (cons from password) mail-source-password-cache)))
518 (setenv "MAILHOST" server))
521 ;; No easy way to check whether mail is waiting for these.
524 ;; The default is to use pop3.el.
526 (let ((pop3-password password)
528 (pop3-mailhost server)
530 (pop3-authentication-scheme
531 (if (eq authentication 'apop) 'apop 'pass)))
532 (save-excursion (pop3-get-message-count))))))
534 ;; Inform display-time that we have new mail.
535 (setq mail-source-new-mail-available (> result 0))
536 ;; We nix out the password in case the error
537 ;; was because of a wrong password being given.
538 (setq mail-source-password-cache
539 (delq (assoc from mail-source-password-cache)
540 mail-source-password-cache)))
543 (defun mail-source-new-mail-p ()
544 "Handler for `display-time' to indicate when new mail is available."
545 ;; Only report flag setting; flag is updated on a different schedule.
546 mail-source-new-mail-available)
549 (defvar mail-source-report-new-mail nil)
550 (defvar mail-source-report-new-mail-timer nil)
551 (defvar mail-source-report-new-mail-idle-timer nil)
553 (eval-when-compile (require 'timer))
555 (defun mail-source-start-idle-timer ()
556 ;; Start our idle timer if necessary, so we delay the check until the
557 ;; user isn't typing.
558 (unless mail-source-report-new-mail-idle-timer
559 (setq mail-source-report-new-mail-idle-timer
561 mail-source-idle-time-delay
564 (setq mail-source-report-new-mail-idle-timer nil)
565 (mail-source-check-pop mail-source-primary-source))))
566 ;; Since idle timers created when Emacs is already in the idle
567 ;; state don't get activated until Emacs _next_ becomes idle, we
568 ;; need to force our timer to be considered active now. We do
569 ;; this by being naughty and poking the timer internals directly
570 ;; (element 0 of the vector is nil if the timer is active).
571 (aset mail-source-report-new-mail-idle-timer 0 nil)))
573 (defun mail-source-report-new-mail (arg)
574 "Toggle whether to report when new mail is available.
575 This only works when `display-time' is enabled."
577 (if (not mail-source-primary-source)
578 (error "Need to set `mail-source-primary-source' to check for new mail."))
579 (let ((on (if (null arg)
580 (not mail-source-report-new-mail)
581 (> (prefix-numeric-value arg) 0))))
582 (setq mail-source-report-new-mail on)
583 (and mail-source-report-new-mail-timer
584 (cancel-timer mail-source-report-new-mail-timer))
585 (and mail-source-report-new-mail-idle-timer
586 (cancel-timer mail-source-report-new-mail-idle-timer))
587 (setq mail-source-report-new-mail-timer nil)
588 (setq mail-source-report-new-mail-idle-timer nil)
592 (setq display-time-mail-function #'mail-source-new-mail-p)
593 ;; Set up the main timer.
594 (setq mail-source-report-new-mail-timer
595 (run-at-time t (* 60 mail-source-report-new-mail-interval)
596 #'mail-source-start-idle-timer))
597 ;; When you get new mail, clear "Mail" from the mode line.
598 (add-hook 'nnmail-post-get-new-mail-hook
599 'display-time-event-handler)
600 (message "Mail check enabled"))
601 (setq display-time-mail-function nil)
602 (remove-hook 'nnmail-post-get-new-mail-hook
603 'display-time-event-handler)
604 (message "Mail check disabled"))))
606 (defun mail-source-fetch-maildir (source callback)
607 "Fetcher for maildir sources."
608 (mail-source-bind (maildir source)
611 (unless (string-match "/$" path)
612 (setq path (concat path "/")))
613 (dolist (subdir subdirs)
614 (when (file-directory-p (concat path subdir))
615 (setq mail-source-string (format "maildir:%s%s" path subdir))
616 (dolist (file (directory-files (concat path subdir) t))
617 (when (and (not (file-directory-p file))
619 (funcall function file mail-source-crash-box)
620 (let ((coding-system-for-write
621 mm-text-coding-system)
622 (coding-system-for-read
623 mm-text-coding-system))
624 (with-temp-file mail-source-crash-box
625 (insert-file-contents file)
626 (goto-char (point-min))
627 (unless (looking-at "\n*From ")
628 (insert "From maildir "
629 (current-time-string) "\n"))
630 (while (re-search-forward "^From " nil t)
631 (replace-match ">From "))
632 (goto-char (point-max))
634 (delete-file file)))))
635 (incf found (mail-source-callback callback file))))))
639 (autoload 'imap-open "imap")
640 (autoload 'imap-authenticate "imap")
641 (autoload 'imap-mailbox-select "imap")
642 (autoload 'imap-mailbox-unselect "imap")
643 (autoload 'imap-mailbox-close "imap")
644 (autoload 'imap-search "imap")
645 (autoload 'imap-fetch "imap")
646 (autoload 'imap-close "imap")
647 (autoload 'imap-error-text "imap")
648 (autoload 'imap-message-flags-add "imap")
649 (autoload 'imap-list-to-message-set "imap")
650 (autoload 'nnheader-ms-strip-cr "nnheader"))
652 (defun mail-source-fetch-imap (source callback)
653 "Fetcher for imap sources."
654 (mail-source-bind (imap source)
655 (let ((from (format "%s:%s:%s" server user port))
657 (buf (get-buffer-create (generate-new-buffer-name " *imap source*")))
658 (mail-source-string (format "imap:%s:%s" server mailbox))
660 (if (and (imap-open server port stream authentication buf)
662 user (or (cdr (assoc from mail-source-password-cache))
664 (imap-mailbox-select mailbox nil buf))
665 (let (str (coding-system-for-write 'binary))
666 (with-temp-file mail-source-crash-box
668 (with-current-buffer buf
669 (when (or imap-password
670 (assoc from mail-source-password-cache))
671 (push (cons from imap-password) mail-source-password-cache)))
672 ;; if predicate is nil, use all uids
673 (dolist (uid (imap-search (or predicate "1:*") buf))
674 (when (setq str (imap-fetch uid "RFC822.PEEK" 'RFC822 nil buf))
676 (insert "From imap " (current-time-string) "\n")
679 (while (re-search-forward "^From " nil t)
680 (replace-match ">From "))
681 (goto-char (point-max))))
682 (nnheader-ms-strip-cr))
683 (incf found (mail-source-callback callback server))
684 (when (and remove fetchflag)
685 (imap-message-flags-add
686 (imap-list-to-message-set remove) fetchflag nil buf))
688 (imap-mailbox-unselect buf)
689 (imap-mailbox-close buf))
692 ;; We nix out the password in case the error
693 ;; was because of a wrong password being given.
694 (setq mail-source-password-cache
695 (delq (assoc from mail-source-password-cache)
696 mail-source-password-cache))
697 (error (imap-error-text buf)))
702 (autoload 'webmail-fetch "webmail"))
704 (defun mail-source-fetch-webmail (source callback)
705 "Fetch for webmail source."
706 (mail-source-bind (webmail source)
707 (let ((mail-source-string (format "webmail:%s:%s" subtype user))
708 (webmail-newmail-only dontexpunge)
709 (webmail-move-to-trash-can (not dontexpunge)))
710 (when (eq authentication 'password)
713 (cdr (assoc (format "webmail:%s:%s" subtype user)
714 mail-source-password-cache))
715 (mail-source-read-passwd
716 (format "Password for %s at %s: " user subtype))))
718 (not (assoc (format "webmail:%s:%s" subtype user)
719 mail-source-password-cache)))
720 (push (cons (format "webmail:%s:%s" subtype user) password)
721 mail-source-password-cache)))
722 (webmail-fetch mail-source-crash-box subtype user password)
723 (mail-source-callback callback (symbol-name subtype)))))
725 (provide 'mail-source)
727 ;;; mail-source.el ends here