* smtp.el: New implementation; don't use `tram.el' and `luna.el'.
[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 (defcustom smtp-default-server nil
39   "Specify default SMTP server."
40   :type '(choice (const nil) string)
41   :group 'smtp)
42
43 (defcustom smtp-server (or (getenv "SMTPSERVER") smtp-default-server)
44   "The name of the host running SMTP server.  It can also be a function
45 called from `smtp-via-smtp' with arguments SENDER and RECIPIENTS."
46   :type '(choice (string :tag "Name")
47                  (function :tag "Function"))
48   :group 'smtp)
49
50 (defcustom smtp-service "smtp"
51   "SMTP service port number. \"smtp\" or 25."
52   :type '(choice (integer :tag "25" 25)
53                  (string :tag "smtp" "smtp"))
54   :group 'smtp)
55
56 (defcustom smtp-local-domain nil
57   "Local domain name without a host name.
58 If the function (system-name) returns the full internet address,
59 don't define this value."
60   :type '(choice (const nil) string)
61   :group 'smtp)
62
63 (defcustom smtp-fqdn nil
64   "Fully qualified domain name used for Message-ID."
65   :type '(choice (const nil) string)
66   :group 'smtp)
67
68 (defvar smtp-open-connection-function (function open-network-stream))
69
70 (defvar smtp-read-point nil)
71
72 (defvar smtp-connection-alist nil)
73
74 ;;; @ SMTP package structure
75 ;;; A package contains a mail message, an envelope sender address,
76 ;;; and one or more envelope recipient addresses.  In ESMTP model
77 ;;; we should guarantee the hook methods to access the current sending package.
78
79 (defmacro smtp-package-sender-internal (package)
80   `(aref ,package 0))
81
82 (defmacro smtp-package-recipients-internal (package)
83   `(aref ,package 1))
84
85 (defmacro smtp-package-buffer-internal (package)
86   `(aref ,package 2))
87
88 (defmacro smtp-make-package (sender recipients buffer)
89   `(vector ,sender ,recipients ,buffer))
90
91 ;;; @ SMTP connection structure
92 ;;; We should take care of emulation for other network streams.
93 ;;; They are likely to be implemented with sub program and the function
94 ;;; `process-contact' returns process ID instead of `(HOST SERVICE)' pair.
95
96 (defmacro smtp-connection-process-internal (connection)
97   `(aref ,connection 0))
98
99 (defmacro smtp-connection-server-internal (connection)
100   `(aref ,connection 1))
101
102 (defmacro smtp-connection-service-internal (connection)
103   `(aref ,connection 2))
104
105 (defmacro smtp-make-connection (process server service)
106   `(vector ,process ,server ,service))
107
108 (defun smtp-connection-opened (connection)
109   "Say whether the CONNECTION to server has been opened."
110   (let ((process (smtp-connection-process-internal connection)))
111     (if (memq (process-status process) '(open run))
112         t)))
113
114 (defun smtp-close-connection (connection)
115   "Close the CONNECTION to server."
116   (let ((process (smtp-connection-process-internal connection)))
117     (delete-process process)))
118
119 (defun smtp-make-fqdn ()
120   "Return user's fully qualified domain name."
121   (if smtp-fqdn
122       smtp-fqdn
123     (let ((system-name (system-name)))
124       (cond
125        (smtp-local-domain
126         (concat system-name "." smtp-local-domain))
127        ((string-match "[^.]\\.[^.]" system-name)
128         system-name)
129        (t
130         (error "Cannot generate valid FQDN. Set `smtp-fqdn' \
131 or `smtp-local-domain' correctly."))))))
132
133 (defun smtp-find-connection (buffer)
134   "Find the connection delivering to BUFFER."
135   (let ((entry (assq buffer smtp-connection-alist))
136         connection)
137     (when entry
138       (setq connection (nth 1 entry))
139       (if (smtp-connection-opened connection)
140           connection
141         (setq smtp-connection-alist
142               (delq entry smtp-connection-alist))
143         nil))))
144
145 (defun smtp-open-connection (buffer server service)
146   (let ((process
147          (as-binary-process
148           (funcall smtp-open-connection-function
149                    "SMTP" buffer  server service)))
150         connection)
151     (when process
152       (setq connection (smtp-make-connection process server service))
153       (set-process-filter process 'smtp-process-filter)
154       (setq smtp-connection-alist
155             (cons (list buffer connection)
156                   smtp-connection-alist))
157       connection)))
158
159 ;;;###autoload
160 (defun smtp-via-smtp (sender recipients buffer)
161   (let ((server
162          (if (functionp smtp-server)
163              (funcall smtp-server sender recipients)
164            smtp-server))
165         (package
166          (smtp-make-package sender recipients buffer)))
167     (save-excursion
168       (set-buffer
169        (get-buffer-create
170         (format "*trace of SMTP session to %s*" server)))
171       (erase-buffer)
172       (buffer-disable-undo)
173       (unless (smtp-find-connection (current-buffer))
174         (smtp-open-connection (current-buffer) server smtp-service))
175       (make-local-variable 'smtp-read-point)
176       (setq smtp-read-point (point-min))
177       (condition-case nil
178           (progn
179             (smtp-commit package)
180             t)
181         (smtp-response-error)))))
182
183 (defun smtp-commit (package)
184   (unwind-protect
185       (progn
186         (smtp-primitive-greeting package)
187         (smtp-primitive-helo package)
188         (smtp-primitive-mailfrom package)
189         (smtp-primitive-rcptto package)
190         (smtp-primitive-data package))
191     (let ((connection (smtp-find-connection (current-buffer))))
192       (when (smtp-connection-opened connection)
193         ;; QUIT
194         (smtp-primitive-quit package)
195         (smtp-close-connection connection)))))
196
197 ;;; @ hook methods for `smtp-commit'
198 ;;;
199 (defun smtp-primitive-greeting (package)
200   (let* ((connection
201           (smtp-find-connection (current-buffer)))
202          (response
203           (smtp-read-response
204            (smtp-connection-process-internal connection))))
205     (if (/= (car response) 220)
206         (smtp-response-error response))))
207
208 (defun smtp-primitive-helo (package)
209   (let* ((connection
210           (smtp-find-connection (current-buffer)))
211          (process
212           (smtp-connection-process-internal connection))
213          response)
214     (smtp-send-command process (format "HELO %s" (smtp-make-fqdn)))
215     (setq response (smtp-read-response process))
216     (if (/= (car response) 250)
217         (smtp-response-error response))))
218
219 (defun smtp-primitive-mailfrom (package)
220   (let* ((connection
221           (smtp-find-connection (current-buffer)))
222          (process
223           (smtp-connection-process-internal connection))
224          response)
225     (smtp-send-command
226      process (format "MAIL FROM:<%s>" (smtp-package-sender-internal package)))
227     (setq response (smtp-read-response process))
228     (if (/= (car response) 250)
229         (smtp-response-error response))))
230
231 (defun smtp-primitive-rcptto (package)
232   (let* ((connection
233           (smtp-find-connection (current-buffer)))
234          (process
235           (smtp-connection-process-internal connection))
236          (recipients
237           (smtp-package-recipients-internal package))
238          response)
239     (while recipients
240       (smtp-send-command
241        process (format "RCPT TO:<%s>" (pop recipients))))
242     (setq response (smtp-read-response process))
243     (unless (memq (car response) '(250 251))
244       (smtp-response-error response))))
245
246 (defun smtp-primitive-data (package)
247   (let* ((connection
248           (smtp-find-connection (current-buffer)))
249          (process
250           (smtp-connection-process-internal connection))
251          response)
252     (smtp-send-command process "DATA")
253     (setq response (smtp-read-response process))
254     (if (/= (car response) 354)
255         (smtp-response-error response))
256     (save-excursion
257       (set-buffer (smtp-package-buffer-internal package))
258       (goto-char (point-min))
259       (while (not (eobp))
260         (smtp-send-data
261          process (buffer-substring (point) (progn (end-of-line)(point))))
262         (forward-char)))
263     (smtp-send-command process ".")
264     (setq response (smtp-read-response process))
265     (if (/= (car response) 250)
266         (smtp-response-error response))))
267
268 (defun smtp-primitive-quit (package)
269   (let* ((connection
270           (smtp-find-connection (current-buffer)))
271          (process
272           (smtp-connection-process-internal connection))
273          response)
274     (smtp-send-command process "QUIT")
275     (setq response (smtp-read-response process))
276     (if (/= (car response) 221)
277         (smtp-response-error response))))
278
279 ;;; @ low level process manipulating function
280 ;;;
281 (defun smtp-process-filter (process output)
282   (save-excursion
283     (set-buffer (process-buffer process))
284     (goto-char (point-max))
285     (insert output)))
286
287 (put 'smtp-response-error 'error-message "SMTP response error")
288 (put 'smtp-response-error 'error-conditions '(smtp-protocol-error error))
289
290 (defun smtp-response-error (response)
291   (signal 'smtp-response-error response))
292
293 (defun smtp-read-response (process)
294   (let (case-fold-search
295         (response-continue t)
296         response)
297     (while response-continue
298       (goto-char smtp-read-point)
299       (while (not (search-forward "\r\n" nil t))
300         (accept-process-output process)
301         (goto-char smtp-read-point))
302       (setq response
303             (nconc response
304                    (list (buffer-substring
305                           (+ 4 smtp-read-point)
306                           (- (point) 2)))))
307       (goto-char
308        (prog1 smtp-read-point
309          (setq smtp-read-point (point))))
310       (when (looking-at "[1-5][0-9][0-9] ")
311         (setq response-continue nil)
312         (push (read (point-marker)) response)))
313     response))
314
315 (defun smtp-send-command (process command)
316   (save-excursion
317     (set-buffer (process-buffer process))
318     (goto-char (point-max))
319     (insert command "\r\n")
320     (setq smtp-read-point (point))
321     (process-send-string process command)
322     (process-send-string process "\r\n")))
323
324 (defun smtp-send-data (process data)
325   (save-excursion
326     (set-buffer (process-buffer process))
327     (goto-char (point-max))
328     (setq smtp-read-point (point))
329     ;; Escape "." at start of a line.
330     (if (eq (string-to-char data) ?.)
331         (process-send-string process "."))
332     (process-send-string process data)
333     (process-send-string process "\r\n")))
334
335 (defun smtp-deduce-address-list (smtp-text-buffer header-start header-end)
336   "Get address list suitable for smtp RCPT TO:<address>."
337   (let ((simple-address-list "")
338         this-line
339         this-line-end
340         addr-regexp
341         (smtp-address-buffer (generate-new-buffer " *smtp-mail*")))
342     (unwind-protect
343         (save-excursion
344           ;;
345           (set-buffer smtp-address-buffer)
346           (setq case-fold-search t)
347           (erase-buffer)
348           (insert (save-excursion
349                     (set-buffer smtp-text-buffer)
350                     (buffer-substring-no-properties header-start header-end)))
351           (goto-char (point-min))
352           ;; RESENT-* fields should stop processing of regular fields.
353           (save-excursion
354             (if (re-search-forward "^RESENT-TO:" header-end t)
355                 (setq addr-regexp
356                       "^\\(RESENT-TO:\\|RESENT-CC:\\|RESENT-BCC:\\)")
357               (setq addr-regexp  "^\\(TO:\\|CC:\\|BCC:\\)")))
358
359           (while (re-search-forward addr-regexp header-end t)
360             (replace-match "")
361             (setq this-line (match-beginning 0))
362             (forward-line 1)
363             ;; get any continuation lines.
364             (while (and (looking-at "^[ \t]+") (< (point) header-end))
365               (forward-line 1))
366             (setq this-line-end (point-marker))
367             (setq simple-address-list
368                   (concat simple-address-list " "
369                           (mail-strip-quoted-names
370                            (buffer-substring this-line this-line-end)))))
371           (erase-buffer)
372           (insert-string " ")
373           (insert-string simple-address-list)
374           (insert-string "\n")
375           ;; newline --> blank
376           (subst-char-in-region (point-min) (point-max) 10 ?  t)
377           ;; comma   --> blank
378           (subst-char-in-region (point-min) (point-max) ?, ?  t)
379           ;; tab     --> blank
380           (subst-char-in-region (point-min) (point-max)  9 ?  t)
381
382           (goto-char (point-min))
383           ;; tidyness in case hook is not robust when it looks at this
384           (while (re-search-forward "[ \t]+" header-end t) (replace-match " "))
385
386           (goto-char (point-min))
387           (let (recipient-address-list)
388             (while (re-search-forward " \\([^ ]+\\) " (point-max) t)
389               (backward-char 1)
390               (setq recipient-address-list
391                     (cons (buffer-substring (match-beginning 1) (match-end 1))
392                           recipient-address-list)))
393             recipient-address-list))
394       (kill-buffer smtp-address-buffer))))
395
396 (provide 'smtp)
397
398 ;;; smtp.el ends here