136e03049d1d977dcbe6a25a8479981cb38361c4
[elisp/flim.git] / smtp.el
1 ;;; smtp.el --- basic functions to send mail with SMTP server
2
3 ;; Copyright (C) 1995, 1996, 1998, 1999 Free Software Foundation, Inc.
4
5 ;; Author: Tomoji Kagatani <kagatani@rbc.ncl.omron.co.jp>
6 ;;      Simon Leinen <simon@switch.ch> (ESMTP support)
7 ;;      Shuhei KOBAYASHI <shuhei@aqua.ocn.ne.jp>
8 ;;      Daiki Ueno <ueno@unixuser.org>
9 ;; Keywords: SMTP, mail
10
11 ;; This file is part of FLIM (Faithful Library about Internet Message).
12
13 ;; This program is free software; you can redistribute it and/or
14 ;; modify it under the terms of the GNU General Public License as
15 ;; published by the Free Software Foundation; either version 2, or (at
16 ;; your option) any later version.
17
18 ;; This program is distributed in the hope that it will be useful, but
19 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21 ;; General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with this program; see the file COPYING.  If not, write to the
25 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
27
28 ;;; Code:
29
30 (require 'pces)
31 (require 'pcustom)
32 (require 'mail-utils)                   ; mail-strip-quoted-names
33
34 (defgroup smtp nil
35   "SMTP protocol for sending mail."
36   :group 'mail)
37
38 (defgroup smtp-extensions nil
39   "SMTP service extensions (RFC1869)."
40   :group 'smtp)
41
42 (defcustom smtp-default-server nil
43   "Specify default SMTP server."
44   :type '(choice (const nil) string)
45   :group 'smtp)
46
47 (defcustom smtp-server (or (getenv "SMTPSERVER") smtp-default-server)
48   "The name of the host running SMTP server.  It can also be a function
49 called from `smtp-via-smtp' with arguments SENDER and RECIPIENTS."
50   :type '(choice (string :tag "Name")
51                  (function :tag "Function"))
52   :group 'smtp)
53
54 (defcustom smtp-service "smtp"
55   "SMTP service port number. \"smtp\" or 25."
56   :type '(choice (integer :tag "25" 25)
57                  (string :tag "smtp" "smtp"))
58   :group 'smtp)
59
60 (defcustom smtp-local-domain nil
61   "Local domain name without a host name.
62 If the function (system-name) returns the full internet address,
63 don't define this value."
64   :type '(choice (const nil) string)
65   :group 'smtp)
66
67 (defcustom smtp-fqdn nil
68   "Fully qualified domain name used for Message-ID."
69   :type '(choice (const nil) string)
70   :group 'smtp)
71
72 (defcustom smtp-use-8bitmime t
73   "If non-nil, use ESMTP 8BITMIME (RFC1652) if available."
74   :type 'boolean
75   :group 'smtp-extensions)
76
77 (defcustom smtp-use-size t
78   "If non-nil, use ESMTP SIZE (RFC1870) if available."
79   :type 'boolean
80   :group 'smtp-extensions)
81
82 (defcustom smtp-use-starttls nil
83   "If non-nil, use STARTTLS (RFC2595) if available."
84   :type 'boolean
85   :group 'smtp-extensions)
86
87 (defvar smtp-open-connection-function #'open-network-stream)
88
89 (defvar smtp-read-point nil)
90
91 (defvar smtp-connection-alist nil)
92
93 (defvar smtp-submit-package-function #'smtp-submit-package)
94
95 ;;; @ SMTP package structure
96 ;;; A package contains a mail message, an envelope sender address,
97 ;;; and one or more envelope recipient addresses.  In ESMTP model,
98 ;;; we should guarantee the user to access the current sending package
99 ;;; anywhere from the hook methods (or SMTP commands).
100
101 (defmacro smtp-package-sender-internal (package)
102   `(aref ,package 0))
103
104 (defmacro smtp-package-recipients-internal (package)
105   `(aref ,package 1))
106
107 (defmacro smtp-package-buffer-internal (package)
108   `(aref ,package 2))
109
110 (defmacro smtp-make-package (sender recipients buffer)
111   `(vector ,sender ,recipients ,buffer))
112
113 (defun smtp-package-buffer-size (package)
114   (save-excursion
115     (set-buffer (smtp-package-buffer-internal package))
116     (let ((size
117            (+ (buffer-size)
118               ;; Add one byte for each change-of-line
119               ;; because or CR-LF representation:
120               (count-lines (point-min) (point-max))
121               ;; For some reason, an empty line is
122               ;; added to the message.  Maybe this
123               ;; is a bug, but it can't hurt to add
124               ;; those two bytes anyway:
125               2)))
126       (goto-char (point-min))
127       (while (re-search-forward "^\\." nil t)
128         (setq size (1+ size)))
129       size)))
130
131 ;;; @ SMTP connection structure
132 ;;; We should take care of a emulation for another network stream.
133 ;;; They are likely to be implemented with a external program and the function
134 ;;; `process-contact' returns the process ID instead of `(HOST SERVICE)' pair.
135
136 (defmacro smtp-connection-process-internal (connection)
137   `(aref ,connection 0))
138
139 (defmacro smtp-connection-server-internal (connection)
140   `(aref ,connection 1))
141
142 (defmacro smtp-connection-service-internal (connection)
143   `(aref ,connection 2))
144
145 (defmacro smtp-connection-extensions-internal (connection)
146   `(aref ,connection 3))
147
148 (defmacro smtp-connection-set-extensions-internal (connection extensions)
149   `(aset ,connection 3 ,extensions))
150
151 (defmacro smtp-make-connection (process server service)
152   `(vector ,process ,server ,service nil))
153
154 (defun smtp-connection-opened (connection)
155   "Say whether the CONNECTION to server has been opened."
156   (let ((process (smtp-connection-process-internal connection)))
157     (if (memq (process-status process) '(open run))
158         t)))
159
160 (defun smtp-close-connection (connection)
161   "Close the CONNECTION to server."
162   (let ((process (smtp-connection-process-internal connection)))
163     (delete-process process)))
164
165 (defun smtp-make-fqdn ()
166   "Return user's fully qualified domain name."
167   (if smtp-fqdn
168       smtp-fqdn
169     (let ((system-name (system-name)))
170       (cond
171        (smtp-local-domain
172         (concat system-name "." smtp-local-domain))
173        ((string-match "[^.]\\.[^.]" system-name)
174         system-name)
175        (t
176         (error "Cannot generate valid FQDN. Set `smtp-fqdn' \
177 or `smtp-local-domain' correctly."))))))
178
179 (defun smtp-find-connection (buffer)
180   "Find the connection delivering to BUFFER."
181   (let ((entry (assq buffer smtp-connection-alist))
182         connection)
183     (when entry
184       (setq connection (nth 1 entry))
185       (if (smtp-connection-opened connection)
186           connection
187         (setq smtp-connection-alist
188               (delq entry smtp-connection-alist))
189         nil))))
190
191 (eval-and-compile
192   (autoload 'starttls-open-stream "starttls")
193   (autoload 'starttls-negotiate "starttls"))
194
195 (defun smtp-open-connection (buffer server service)
196   (let ((process
197          (as-binary-process
198           (funcall smtp-open-connection-function
199                    "SMTP" buffer  server service)))
200         connection)
201     (when process
202       (setq connection (smtp-make-connection process server service))
203       (set-process-filter process 'smtp-process-filter)
204       (setq smtp-connection-alist
205             (cons (list buffer connection)
206                   smtp-connection-alist))
207       connection)))
208
209 ;;;###autoload
210 (defun smtp-via-smtp (sender recipients buffer)
211   (let ((server
212          (if (functionp smtp-server)
213              (funcall smtp-server sender recipients)
214            smtp-server))
215         (package
216          (smtp-make-package sender recipients buffer))
217         (smtp-open-connection-function
218          (if smtp-use-starttls
219              #'starttls-open-stream
220            smtp-open-connection-function)))
221     (save-excursion
222       (set-buffer
223        (get-buffer-create
224         (format "*trace of SMTP session to %s*" server)))
225       (erase-buffer)
226       (buffer-disable-undo)
227       (unless (smtp-find-connection (current-buffer))
228         (smtp-open-connection (current-buffer) server smtp-service))
229       (make-local-variable 'smtp-read-point)
230       (setq smtp-read-point (point-min))
231       (condition-case nil
232           (progn
233             (funcall smtp-submit-package-function package)
234             t)
235         (smtp-response-error)))))
236
237 (defun smtp-submit-package (package)
238   (unwind-protect
239       (progn
240         (smtp-primitive-greeting package)
241         (smtp-primitive-helo package)
242         (smtp-primitive-mailfrom package)
243         (smtp-primitive-rcptto package)
244         (smtp-primitive-data package))
245     (let ((connection (smtp-find-connection (current-buffer))))
246       (when (smtp-connection-opened connection)
247         ;; QUIT
248         (smtp-primitive-quit package)
249         (smtp-close-connection connection)))))
250
251 ;;; @ hook methods for `smtp-submit-package'
252 ;;;
253 (defun smtp-primitive-greeting (package)
254   (let* ((connection
255           (smtp-find-connection (current-buffer)))
256          (response
257           (smtp-read-response
258            (smtp-connection-process-internal connection))))
259     (if (/= (car response) 220)
260         (smtp-response-error response))))
261
262 (defun smtp-primitive-ehlo (package)
263   (let* ((connection
264           (smtp-find-connection (current-buffer)))
265          (process
266           (smtp-connection-process-internal connection))
267          response)
268     (smtp-send-command process (format "EHLO %s" (smtp-make-fqdn)))
269     (setq response (smtp-read-response process))
270     (if (/= (car response) 250)
271         (smtp-response-error response))
272     (smtp-connection-set-extensions-internal
273      connection (mapcar
274                  (lambda (extension)
275                    (mapcar
276                     (lambda (parameter)
277                       (car (read-from-string (downcase parameter))))
278                     (split-string extension)))
279                  (cdr response)))))
280
281 (defun smtp-primitive-helo (package)
282   (let* ((connection
283           (smtp-find-connection (current-buffer)))
284          (process
285           (smtp-connection-process-internal connection))
286          response)
287     (smtp-send-command process (format "HELO %s" (smtp-make-fqdn)))
288     (setq response (smtp-read-response process))
289     (if (/= (car response) 250)
290         (smtp-response-error response))))
291
292 (defun smtp-primitive-starttls (package)
293   (let* ((connection
294           (smtp-find-connection (current-buffer)))
295          (process
296           (smtp-connection-process-internal connection))
297          response)
298     ;; STARTTLS --- begin a TLS negotiation (RFC 2595)
299     (smtp-send-command process "STARTTLS")
300     (setq response (smtp-read-response process))
301     (starttls-negotiate process)))
302
303 (defun smtp-primitive-mailfrom (package)
304   (let* ((connection
305           (smtp-find-connection (current-buffer)))
306          (process
307           (smtp-connection-process-internal connection))
308          (extensions
309           (smtp-connection-extensions-internal
310            connection))
311          (sender
312           (smtp-package-sender-internal package))
313          extension
314          response)
315     ;; SIZE --- Message Size Declaration (RFC1870)
316     (if (and smtp-use-size
317              (assq 'size extensions))
318         (setq extension (format "SIZE=%d" (smtp-package-buffer-size package))))
319     ;; 8BITMIME --- 8bit-MIMEtransport (RFC1652)
320     (if (and smtp-use-8bitmime
321              (assq '8bitmime extensions))
322         (setq extension (concat extension " BODY=8BITMIME")))
323     (smtp-send-command
324      process
325      (if extension
326          (format "MAIL FROM:<%s> %s" sender extension)
327        (format "MAIL FROM:<%s>" sender)))
328     (setq response (smtp-read-response process))
329     (if (/= (car response) 250)
330         (smtp-response-error response))))
331
332 (defun smtp-primitive-rcptto (package)
333   (let* ((connection
334           (smtp-find-connection (current-buffer)))
335          (process
336           (smtp-connection-process-internal connection))
337          (recipients
338           (smtp-package-recipients-internal package))
339          response)
340     (while recipients
341       (smtp-send-command
342        process (format "RCPT TO:<%s>" (pop recipients))))
343     (setq response (smtp-read-response process))
344     (unless (memq (car response) '(250 251))
345       (smtp-response-error response))))
346
347 (defun smtp-primitive-data (package)
348   (let* ((connection
349           (smtp-find-connection (current-buffer)))
350          (process
351           (smtp-connection-process-internal connection))
352          response)
353     (smtp-send-command process "DATA")
354     (setq response (smtp-read-response process))
355     (if (/= (car response) 354)
356         (smtp-response-error response))
357     (save-excursion
358       (set-buffer (smtp-package-buffer-internal package))
359       (goto-char (point-min))
360       (while (not (eobp))
361         (smtp-send-data
362          process (buffer-substring (point) (progn (end-of-line)(point))))
363         (forward-char)))
364     (smtp-send-command process ".")
365     (setq response (smtp-read-response process))
366     (if (/= (car response) 250)
367         (smtp-response-error response))))
368
369 (defun smtp-primitive-quit (package)
370   (let* ((connection
371           (smtp-find-connection (current-buffer)))
372          (process
373           (smtp-connection-process-internal connection))
374          response)
375     (smtp-send-command process "QUIT")
376     (setq response (smtp-read-response process))
377     (if (/= (car response) 221)
378         (smtp-response-error response))))
379
380 ;;; @ low level process manipulating function
381 ;;;
382 (defun smtp-process-filter (process output)
383   (save-excursion
384     (set-buffer (process-buffer process))
385     (goto-char (point-max))
386     (insert output)))
387
388 (put 'smtp-response-error 'error-message "SMTP response error")
389 (put 'smtp-response-error 'error-conditions '(smtp-response-error error))
390
391 (defun smtp-response-error (response)
392   (signal 'smtp-response-error response))
393
394 (defun smtp-read-response (process)
395   (let (case-fold-search
396         (response-continue t)
397         response)
398     (while response-continue
399       (goto-char smtp-read-point)
400       (while (not (search-forward "\r\n" nil t))
401         (accept-process-output process)
402         (goto-char smtp-read-point))
403       (setq response
404             (nconc response
405                    (list (buffer-substring
406                           (+ 4 smtp-read-point)
407                           (- (point) 2)))))
408       (goto-char
409        (prog1 smtp-read-point
410          (setq smtp-read-point (point))))
411       (if (looking-at "[1-5][0-9][0-9] ")
412           (setq response (cons (read (point-marker)) response)
413                 response-continue nil)))
414     response))
415
416 (defun smtp-send-command (process command)
417   (save-excursion
418     (set-buffer (process-buffer process))
419     (goto-char (point-max))
420     (insert command "\r\n")
421     (setq smtp-read-point (point))
422     (process-send-string process command)
423     (process-send-string process "\r\n")))
424
425 (defun smtp-send-data (process data)
426   (save-excursion
427     (set-buffer (process-buffer process))
428     (goto-char (point-max))
429     (setq smtp-read-point (point))
430     ;; Escape "." at start of a line.
431     (if (eq (string-to-char data) ?.)
432         (process-send-string process "."))
433     (process-send-string process data)
434     (process-send-string process "\r\n")))
435
436 (defun smtp-deduce-address-list (smtp-text-buffer header-start header-end)
437   "Get address list suitable for smtp RCPT TO:<address>."
438   (let ((simple-address-list "")
439         this-line
440         this-line-end
441         addr-regexp
442         (smtp-address-buffer (generate-new-buffer " *smtp-mail*")))
443     (unwind-protect
444         (save-excursion
445           ;;
446           (set-buffer smtp-address-buffer)
447           (setq case-fold-search t)
448           (erase-buffer)
449           (insert (save-excursion
450                     (set-buffer smtp-text-buffer)
451                     (buffer-substring-no-properties header-start header-end)))
452           (goto-char (point-min))
453           ;; RESENT-* fields should stop processing of regular fields.
454           (save-excursion
455             (if (re-search-forward "^RESENT-TO:" header-end t)
456                 (setq addr-regexp
457                       "^\\(RESENT-TO:\\|RESENT-CC:\\|RESENT-BCC:\\)")
458               (setq addr-regexp  "^\\(TO:\\|CC:\\|BCC:\\)")))
459
460           (while (re-search-forward addr-regexp header-end t)
461             (replace-match "")
462             (setq this-line (match-beginning 0))
463             (forward-line 1)
464             ;; get any continuation lines.
465             (while (and (looking-at "^[ \t]+") (< (point) header-end))
466               (forward-line 1))
467             (setq this-line-end (point-marker))
468             (setq simple-address-list
469                   (concat simple-address-list " "
470                           (mail-strip-quoted-names
471                            (buffer-substring this-line this-line-end)))))
472           (erase-buffer)
473           (insert-string " ")
474           (insert-string simple-address-list)
475           (insert-string "\n")
476           ;; newline --> blank
477           (subst-char-in-region (point-min) (point-max) 10 ?  t)
478           ;; comma   --> blank
479           (subst-char-in-region (point-min) (point-max) ?, ?  t)
480           ;; tab     --> blank
481           (subst-char-in-region (point-min) (point-max)  9 ?  t)
482
483           (goto-char (point-min))
484           ;; tidyness in case hook is not robust when it looks at this
485           (while (re-search-forward "[ \t]+" header-end t) (replace-match " "))
486
487           (goto-char (point-min))
488           (let (recipient-address-list)
489             (while (re-search-forward " \\([^ ]+\\) " (point-max) t)
490               (backward-char 1)
491               (setq recipient-address-list
492                     (cons (buffer-substring (match-beginning 1) (match-end 1))
493                           recipient-address-list)))
494             recipient-address-list))
495       (kill-buffer smtp-address-buffer))))
496
497 (provide 'smtp)
498
499 ;;; smtp.el ends here