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")))
116 (:authentication password))
118 (:path (or (getenv "MAILDIR") "~/Maildir/"))
119 (:subdirs ("new" "cur"))
122 (:server (getenv "MAILHOST"))
126 (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
129 (:predicate "UNSEEN UNDELETED")
130 (:fetchflag "\\Deleted")
134 (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
137 (:authentication password)))
138 "Mapping from keywords to default values.
139 All keywords that can be used must be listed here."))
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.")
150 (defvar mail-source-password-cache nil)
152 (defvar mail-source-plugged t)
157 (defun mail-source-strip-keyword (keyword)
158 "Strip the leading colon off the KEYWORD."
159 (intern (substring (symbol-name keyword) 1))))
162 (defun mail-source-bind-1 (type)
163 (let* ((defaults (cdr (assq type mail-source-keyword-map)))
165 (while (setq default (pop defaults))
166 (push (list (mail-source-strip-keyword (car default))
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.
179 After this is done, BODY will be executed in the scope
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))
188 (put 'mail-source-bind 'lisp-indent-function 1)
189 (put 'mail-source-bind 'edebug-form-spec '(form body))
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)))))))
202 (defun mail-source-bind-common-1 ()
203 (let* ((defaults mail-source-common-keyword-map)
205 (while (setq default (pop defaults))
206 (push (list (mail-source-strip-keyword (car default))
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))))))))
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)
231 (put 'mail-source-bind-common 'lisp-indent-function 1)
232 (put 'mail-source-bind-common 'edebug-form-spec '(form body))
234 (defun mail-source-value (value)
235 "Return the value of VALUE."
242 (functionp (car value)))
244 ;; Just return the value.
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)
256 (let ((function (cadr (assq (car source) mail-source-fetcher-alist)))
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)))
267 (funcall function source callback)
270 (format "Mail source error (%s). Continue? " err))
271 (error "Cannot get new mail."))
274 (defun mail-source-make-complex-temp-name (prefix)
275 (let ((newname (make-temp-name prefix))
277 (while (file-exists-p newname)
278 (setq newprefix (concat newprefix "x"))
279 (setq newname (make-temp-name newprefix)))
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))))
288 (when (file-exists-p mail-source-crash-box)
289 (delete-file mail-source-crash-box))
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)
298 (mail-source-make-complex-temp-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)))))))
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)))
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.
317 ;; The crash box exists already.
319 ((not (file-exists-p from))
320 ;; There is no inbox.
322 ((zerop (nth 7 (file-attributes from)))
326 ;; If getting from mail spool directory, use movemail to move
327 ;; rather than just renaming, so as to interlock with the
331 (setq errors (generate-new-buffer " *mail source loss*"))
332 (let ((default-directory "/"))
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))
344 ;; No output => movemail won.
347 ;; There may be a warning about older revisions. We
349 (goto-char (point-min))
350 (if (search-forward "older revision" nil 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)))
361 (format "movemail: %s (%d return). Continue? "
362 (buffer-string) result))
363 (error "%s" (buffer-string)))
366 (buffer-name errors))
367 (kill-buffer errors))
368 ;; Return whether we moved successfully or not.
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))))
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'."
383 (apply 'format prompt args)
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)))
393 (defun mail-source-fetch-with-program (program)
394 (zerop (call-process shell-file-name nil nil nil
395 shell-command-switch program)))
397 (defun mail-source-run-script (script spec &optional delay)
399 (if (and (symbolp script) (fboundp script))
401 (mail-source-call-script
402 (format-spec script spec))))
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))
411 (call-process shell-file-name nil background nil
412 shell-command-switch script)))
415 ;;; Different fetchers
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)
424 (let ((mail-source-string (format "file:%s" path)))
425 (if (mail-source-movemail path mail-source-crash-box)
427 (mail-source-callback callback path)
428 (mail-source-run-script
429 postscript (format-spec-make ?t mail-source-crash-box)))
432 (defun mail-source-fetch-directory (source callback)
433 "Fetcher for directory sources."
434 (mail-source-bind (directory source)
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))))
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
450 (format-spec-make ?p password ?t mail-source-crash-box
451 ?s server ?P port ?u user)
453 (let ((from (format "%s:%s:%s" server user port))
454 (mail-source-string (format "pop:%s@%s" user server))
456 (when (eq authentication 'password)
459 (cdr (assoc from mail-source-password-cache))
460 (mail-source-read-passwd
461 (format "Password for %s at %s: " user server)))))
463 (setenv "MAILHOST" server))
467 (mail-source-fetch-with-program
470 (format-spec-make ?p password ?t mail-source-crash-box
471 ?s server ?P port ?u user))))
473 (funcall function mail-source-crash-box))
474 ;; The default is to use pop3.el.
476 (let ((pop3-password password)
478 (pop3-mailhost server)
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))))))
486 (when (eq authentication 'password)
487 (unless (assoc from mail-source-password-cache)
488 (push (cons from password) mail-source-password-cache)))
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
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))
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))
511 (when (eq authentication '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)))
520 (setenv "MAILHOST" server))
523 ;; No easy way to check whether mail is waiting for these.
526 ;; The default is to use pop3.el.
528 (let ((pop3-password password)
530 (pop3-mailhost server)
532 (pop3-authentication-scheme
533 (if (eq authentication 'apop) 'apop 'pass)))
534 (save-excursion (pop3-get-message-count))))))
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)))
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)
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)
555 (eval-when-compile (require 'timer))
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
563 mail-source-idle-time-delay
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)))
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."
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)
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"))))
608 (defun mail-source-fetch-maildir (source callback)
609 "Fetcher for maildir sources."
610 (mail-source-bind (maildir source)
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))
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))
636 (delete-file file)))))
637 (incf found (mail-source-callback callback file))))))
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"))
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))
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))
663 (if (and (imap-open server port stream authentication buf)
665 user (or (cdr (assoc from mail-source-password-cache))
667 (imap-mailbox-select mailbox nil buf))
669 (coding-system-for-write 'binary)
670 (output-coding-system 'binary))
671 (with-temp-file mail-source-crash-box
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))
681 (insert "From imap " (current-time-string) "\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))
693 (imap-mailbox-unselect buf)
694 (imap-mailbox-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)))
707 (autoload 'webmail-fetch "webmail"))
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)
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))))
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)))))
730 (provide 'mail-source)
732 ;;; mail-source.el ends here