Add webmail as mail source. Now only support HoTMaiL.
[gnus] / lisp / mail-source.el
1 ;;; mail-source.el --- functions for fetching mail
2 ;; Copyright (C) 1999 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 (require 'format-spec)
32
33 (defgroup mail-source nil
34   "The mail-fetching library."
35   :group 'gnus)
36
37 (defcustom mail-sources nil
38   "*Where the mail backends will look for incoming mail.
39 This variable is a list of mail source specifiers."
40   :group 'mail-source
41   :type 'sexp)
42
43 (defcustom mail-source-crash-box "~/.emacs-mail-crash-box"
44   "File where mail will be stored while processing it."
45   :group 'mail-source
46   :type 'file)
47
48 (defcustom mail-source-directory "~/Mail/"
49   "Directory where files (if any) will be stored."
50   :group 'mail-source
51   :type 'directory)
52
53 (defcustom mail-source-default-file-modes 384
54   "Set the mode bits of all new mail files to this integer."
55   :group 'mail-source
56   :type 'integer)
57
58 (defcustom mail-source-delete-incoming nil
59   "*If non-nil, delete incoming files after handling."
60   :group 'mail-source
61   :type 'boolean)
62
63 ;;; Internal variables.
64
65 (defvar mail-source-string ""
66   "A dynamically bound string that says what the current mail source is.")
67
68 (eval-and-compile
69   (defvar mail-source-keyword-map
70     '((file
71        (:prescript)
72        (:prescript-delay)
73        (:postscript)
74        (:path (or (getenv "MAIL")
75                   (concat "/usr/spool/mail/" (user-login-name)))))
76       (directory
77        (:path)
78        (:suffix ".spool")
79        (:predicate identity))
80       (pop
81        (:prescript)
82        (:prescript-delay)
83        (:postscript)
84        (:server (getenv "MAILHOST"))
85        (:port 110)
86        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
87        (:program)
88        (:function)
89        (:password)
90        (:authentication password))
91       (maildir
92        (:path "~/Maildir/new/")
93        (:function))
94       (imap
95        (:server (getenv "MAILHOST"))
96        (:port)
97        (:stream)
98        (:authentication)
99        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
100        (:password)
101        (:mailbox "INBOX")
102        (:predicate "UNSEEN UNDELETED")
103        (:fetchflag "\Deleted")
104        (:dontexpunge))
105       (webmail
106        (:wmtype hotmail)
107        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
108        (:password)))
109     "Mapping from keywords to default values.
110 All keywords that can be used must be listed here."))
111
112 (defvar mail-source-fetcher-alist
113   '((file mail-source-fetch-file)
114     (directory mail-source-fetch-directory)
115     (pop mail-source-fetch-pop)
116     (maildir mail-source-fetch-maildir)
117     (imap mail-source-fetch-imap)
118     (webmail mail-source-fetch-webmail))
119   "A mapping from source type to fetcher function.")
120
121 (defvar mail-source-password-cache nil)
122
123 ;;; Functions
124
125 (eval-and-compile
126   (defun mail-source-strip-keyword (keyword)
127   "Strip the leading colon off the KEYWORD."
128   (intern (substring (symbol-name keyword) 1))))
129
130 (eval-and-compile
131   (defun mail-source-bind-1 (type)
132     (let* ((defaults (cdr (assq type mail-source-keyword-map)))
133            default bind)
134       (while (setq default (pop defaults))
135         (push (list (mail-source-strip-keyword (car default))
136                     nil)
137               bind))
138       bind)))
139
140 (defmacro mail-source-bind (type-source &rest body)
141   "Return a `let' form that binds all variables in source TYPE.
142 TYPE-SOURCE is a list where the first element is the TYPE, and
143 the second variable is the SOURCE.
144 At run time, the mail source specifier SOURCE will be inspected,
145 and the variables will be set according to it.  Variables not
146 specified will be given default values.
147
148 After this is done, BODY will be executed in the scope
149 of the `let' form.
150
151 The variables bound and their default values are described by
152 the `mail-source-keyword-map' variable."
153   `(let ,(mail-source-bind-1 (car type-source))
154      (mail-source-set-1 ,(cadr type-source))
155      ,@body))
156
157 (put 'mail-source-bind 'lisp-indent-function 1)
158 (put 'mail-source-bind 'edebug-form-spec '(form body))
159
160 (defun mail-source-set-1 (source)
161   (let* ((type (pop source))
162          (defaults (cdr (assq type mail-source-keyword-map)))
163          default value keyword)
164     (while (setq default (pop defaults))
165       (set (mail-source-strip-keyword (setq keyword (car default)))
166            (if (setq value (plist-get source keyword))
167                (mail-source-value value)
168              (mail-source-value (cadr default)))))))
169
170 (defun mail-source-value (value)
171   "Return the value of VALUE."
172   (cond
173    ;; String
174    ((stringp value)
175     value)
176    ;; Function
177    ((and (listp value)
178          (functionp (car value)))
179     (eval value))
180    ;; Just return the value.
181    (t
182     value)))
183
184 (defun mail-source-fetch (source callback)
185   "Fetch mail from SOURCE and call CALLBACK zero or more times.
186 CALLBACK will be called with the name of the file where (some of)
187 the mail from SOURCE is put.
188 Return the number of files that were found."
189   (save-excursion
190     (let ((function (cadr (assq (car source) mail-source-fetcher-alist)))
191           (found 0))
192       (unless function
193         (error "%S is an invalid mail source specification" source))
194       ;; If there's anything in the crash box, we do it first.
195       (when (file-exists-p mail-source-crash-box)
196         (message "Processing mail from %s..." mail-source-crash-box)
197         (setq found (mail-source-callback
198                      callback mail-source-crash-box)))
199       (+ found
200          (condition-case err
201              (funcall function source callback)
202            (error
203             (unless (yes-or-no-p
204                      (format "Mail source error (%s).  Continue? " err))
205               (error "Cannot get new mail."))
206             0))))))
207
208 (defun mail-source-make-complex-temp-name (prefix)
209   (let ((newname (make-temp-name prefix))
210         (newprefix prefix))
211     (while (file-exists-p newname)
212       (setq newprefix (concat newprefix "x"))
213       (setq newname (make-temp-name newprefix)))
214     newname))
215
216 (defun mail-source-callback (callback info)
217   "Call CALLBACK on the mail file, and then remove the mail file.
218 Pass INFO on to CALLBACK."
219   (if (or (not (file-exists-p mail-source-crash-box))
220           (zerop (nth 7 (file-attributes mail-source-crash-box))))
221       (progn
222         (when (file-exists-p mail-source-crash-box)
223           (delete-file mail-source-crash-box))
224         0)
225     (prog1
226         (funcall callback mail-source-crash-box info)
227       (when (file-exists-p mail-source-crash-box)
228         ;; Delete or move the incoming mail out of the way.
229         (if mail-source-delete-incoming
230             (delete-file mail-source-crash-box)
231           (let ((incoming
232                  (mail-source-make-complex-temp-name
233                   (expand-file-name
234                    "Incoming" mail-source-directory))))
235             (unless (file-exists-p (file-name-directory incoming))
236               (make-directory (file-name-directory incoming) t))
237             (rename-file mail-source-crash-box incoming t)))))))
238
239 (defun mail-source-movemail (from to)
240   "Move FROM to TO using movemail."
241   (if (not (file-writable-p to))
242       (error "Can't write to crash box %s.  Not moving mail" to)
243     (let ((to (file-truename (expand-file-name to)))
244           errors result)
245       (setq to (file-truename to)
246             from (file-truename from))
247       ;; Set TO if have not already done so, and rename or copy
248       ;; the file FROM to TO if and as appropriate.
249       (cond
250        ((file-exists-p to)
251         ;; The crash box exists already.
252         t)
253        ((not (file-exists-p from))
254         ;; There is no inbox.
255         (setq to nil))
256        ((zerop (nth 7 (file-attributes from)))
257         ;; Empty file.
258         (setq to nil))
259        (t
260         ;; If getting from mail spool directory, use movemail to move
261         ;; rather than just renaming, so as to interlock with the
262         ;; mailer.
263         (unwind-protect
264             (save-excursion
265               (setq errors (generate-new-buffer " *mail source loss*"))
266               (let ((default-directory "/"))
267                 (setq result
268                       (apply
269                        'call-process
270                        (append
271                         (list
272                          (expand-file-name "movemail" exec-directory)
273                          nil errors nil from to)))))
274               (when (file-exists-p to)
275                 (set-file-modes to mail-source-default-file-modes))
276               (if (and (not (buffer-modified-p errors))
277                        (zerop result))
278                   ;; No output => movemail won.
279                   t
280                 (set-buffer errors)
281                 ;; There may be a warning about older revisions.  We
282                 ;; ignore that.
283                 (goto-char (point-min))
284                 (if (search-forward "older revision" nil t)
285                     t
286                   ;; Probably a real error.
287                   (subst-char-in-region (point-min) (point-max) ?\n ?\  )
288                   (goto-char (point-max))
289                   (skip-chars-backward " \t")
290                   (delete-region (point) (point-max))
291                   (goto-char (point-min))
292                   (when (looking-at "movemail: ")
293                     (delete-region (point-min) (match-end 0)))
294                   (unless (yes-or-no-p
295                            (format "movemail: %s (%d return).  Continue? "
296                                    (buffer-string) result))
297                     (error "%s" (buffer-string)))
298                   (setq to nil)))))))
299       (when (and errors
300                  (buffer-name errors))
301         (kill-buffer errors))
302       ;; Return whether we moved successfully or not.
303       to)))
304
305 (defun mail-source-movemail-and-remove (from to)
306   "Move FROM to TO using movemail, then remove FROM if empty."
307   (or (not (mail-source-movemail from to))
308       (not (zerop (nth 7 (file-attributes from))))
309       (delete-file from)))
310
311 (defvar mail-source-read-passwd nil)
312 (defun mail-source-read-passwd (prompt &rest args)
313   "Read a password using PROMPT.
314 If ARGS, PROMPT is used as an argument to `format'."
315   (let ((prompt
316          (if args
317              (apply 'format prompt args)
318            prompt)))
319     (unless mail-source-read-passwd
320       (if (or (fboundp 'read-passwd) (load "passwd" t))
321           (setq mail-source-read-passwd 'read-passwd)
322         (unless (fboundp 'ange-ftp-read-passwd)
323           (autoload 'ange-ftp-read-passwd "ange-ftp"))
324         (setq mail-source-read-passwd 'ange-ftp-read-passwd)))
325     (funcall mail-source-read-passwd prompt)))
326
327 (defun mail-source-fetch-with-program (program)
328   (zerop (call-process shell-file-name nil nil nil
329                        shell-command-switch program)))
330
331 (defun mail-source-run-script (script spec &optional delay)
332   (when script
333     (if (and (symbolp script) (fboundp script))
334         (funcall script)
335       (mail-source-call-script
336        (format-spec script spec))))
337   (when delay
338     (sleep-for delay)))
339
340 (defun mail-source-call-script (script)
341   (let ((background nil))
342     (when (string-match "& *$" script)
343       (setq script (substring script 0 (match-beginning 0))
344             background 0))
345     (call-process shell-file-name nil background nil
346                   shell-command-switch script)))
347
348 ;;;
349 ;;; Different fetchers
350 ;;;
351
352 (defun mail-source-fetch-file (source callback)
353   "Fetcher for single-file sources."
354   (mail-source-bind (file source)
355     (mail-source-run-script
356      prescript (format-spec-make ?t mail-source-crash-box)
357      prescript-delay)
358     (let ((mail-source-string (format "file:%s" path)))
359       (if (mail-source-movemail path mail-source-crash-box)
360           (prog1
361               (mail-source-callback callback path)
362             (mail-source-run-script
363              postscript (format-spec-make ?t mail-source-crash-box)))
364         0))))
365
366 (defun mail-source-fetch-directory (source callback)
367   "Fetcher for directory sources."
368   (mail-source-bind (directory source)
369     (let ((found 0)
370           (mail-source-string (format "directory:%s" path)))
371       (dolist (file (directory-files
372                      path t (concat (regexp-quote suffix) "$")))
373         (when (and (file-regular-p file)
374                    (funcall predicate file)
375                    (mail-source-movemail file mail-source-crash-box))
376           (incf found (mail-source-callback callback file))))
377       found)))
378
379 (defun mail-source-fetch-pop (source callback)
380   "Fetcher for single-file sources."
381   (mail-source-bind (pop source)
382     (mail-source-run-script
383      prescript
384      (format-spec-make ?p password ?t mail-source-crash-box
385                                       ?s server ?P port ?u user)
386      prescript-delay)
387     (let ((from (format "%s:%s:%s" server user port))
388           (mail-source-string (format "pop:%s@%s" user server))
389           result)
390       (when (eq authentication 'password)
391         (setq password
392               (or password
393                   (cdr (assoc from mail-source-password-cache))
394                   (mail-source-read-passwd
395                    (format "Password for %s at %s: " user server)))))
396       (when server
397         (setenv "MAILHOST" server))
398       (setq result
399             (cond
400              (program
401               (mail-source-fetch-with-program
402                (format-spec
403                 program
404                 (format-spec-make ?p password ?t mail-source-crash-box
405                                   ?s server ?P port ?u user))))
406              (function
407               (funcall function mail-source-crash-box))
408              ;; The default is to use pop3.el.
409              (t
410               (let ((pop3-password password)
411                     (pop3-maildrop user)
412                     (pop3-mailhost server)
413                     (pop3-port port)
414                     (pop3-authentication-scheme
415                      (if (eq authentication 'apop) 'apop 'pass)))
416                 (save-excursion (pop3-movemail mail-source-crash-box))))))
417       (if result
418           (progn
419             (when (eq authentication 'password)
420               (unless (assoc from mail-source-password-cache)
421                 (push (cons from password) mail-source-password-cache)))
422             (prog1
423                 (mail-source-callback callback server)
424               (mail-source-run-script
425                postscript
426                (format-spec-make ?p password ?t mail-source-crash-box
427                                  ?s server ?P port ?u user))))
428         ;; We nix out the password in case the error
429         ;; was because of a wrong password being given.
430         (setq mail-source-password-cache
431               (delq (assoc from mail-source-password-cache)
432                     mail-source-password-cache))
433         0))))
434
435 (defun mail-source-fetch-maildir (source callback)
436   "Fetcher for maildir sources."
437   (mail-source-bind (maildir source)
438     (let ((found 0)
439           (mail-source-string (format "maildir:%s" path)))
440       (dolist (file (directory-files path t))
441         (when (and (file-regular-p file)
442                    (not (if function
443                             (funcall function file mail-source-crash-box)
444                           (rename-file file mail-source-crash-box))))
445           (incf found (mail-source-callback callback file))))
446       found)))
447
448 (eval-and-compile
449   (autoload 'imap-open "imap")
450   (autoload 'imap-authenticate "imap")
451   (autoload 'imap-mailbox-select "imap")
452   (autoload 'imap-mailbox-unselect "imap")
453   (autoload 'imap-mailbox-close "imap")
454   (autoload 'imap-search "imap")
455   (autoload 'imap-fetch "imap")
456   (autoload 'imap-close "imap")
457   (autoload 'imap-error-text "imap")
458   (autoload 'imap-message-flags-add "imap")
459   (autoload 'imap-list-to-message-set "imap")
460   (autoload 'nnheader-ms-strip-cr "nnheader"))
461
462 (defun mail-source-fetch-imap (source callback)
463   "Fetcher for imap sources."
464   (mail-source-bind (imap source)
465     (let ((found 0)
466           (buf (get-buffer-create (generate-new-buffer-name " *imap source*")))
467           (mail-source-string (format "imap:%s:%s" server mailbox))
468           remove)
469       (if (and (imap-open server port stream authentication buf)
470                (imap-authenticate user password buf)
471                (imap-mailbox-select mailbox nil buf))
472           (let (str (coding-system-for-write 'binary))
473             (with-temp-file mail-source-crash-box
474               ;; if predicate is nil, use all uids
475               (dolist (uid (imap-search (or predicate "1:*") buf))
476                 (when (setq str (imap-fetch uid "RFC822.PEEK" 'RFC822 nil buf))
477                   (push uid remove)
478                   (insert "From imap " (current-time-string) "\n")
479                   (save-excursion
480                     (insert str "\n\n"))
481                   (while (re-search-forward "^From " nil t)
482                     (replace-match ">From "))
483                   (goto-char (point-max))))
484               (nnheader-ms-strip-cr))
485             (incf found (mail-source-callback callback server))
486             (when (and remove fetchflag)
487               (imap-message-flags-add
488                (imap-list-to-message-set remove) fetchflag nil buf))
489             (if dontexpunge
490                 (imap-mailbox-unselect buf)
491               (imap-mailbox-close buf))
492             (imap-close buf))
493         (imap-close buf)
494         (error (imap-error-text buf)))
495       (kill-buffer buf)
496       found)))
497
498 (eval-and-compile
499   (autoload 'webmail-fetch "webmail"))
500
501 (defun mail-source-fetch-webmail (source callback)
502   "Fetch for webmail source."
503   (mail-source-bind (webmail source)
504     (save-excursion
505       (webmail-fetch mail-source-crash-box wmtype user password)
506       (mail-source-callback callback (symbol-name wmtype)))))
507
508 (provide 'mail-source)
509
510 ;;; mail-source.el ends here