Update.
[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 ;; Keywords: SMTP, mail
9
10 ;; This file is part of FLIM (Faithful Library about Internet Message).
11
12 ;; This program is free software; you can redistribute it and/or
13 ;; modify it under the terms of the GNU General Public License as
14 ;; published by the Free Software Foundation; either version 2, or (at
15 ;; your option) any later version.
16
17 ;; This program is distributed in the hope that it will be useful, but
18 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 ;; General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with this program; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 ;;; Code:
28
29 (require 'poe)
30 (require 'poem)
31 (require 'pcustom)
32 (require 'mail-utils)                   ; mail-strip-quoted-names
33
34 (eval-when-compile (require 'cl))       ; push
35
36 (defgroup smtp nil
37   "SMTP protocol for sending mail."
38   :group 'mail)
39
40 (defcustom smtp-default-server nil
41   "*Specify default SMTP server."
42   :type '(choice (const nil) string)
43   :group 'smtp)
44
45 (defcustom smtp-server (or (getenv "SMTPSERVER") smtp-default-server)
46   "*The name of the host running SMTP server.  It can also be a function
47 called from `smtp-via-smtp' with arguments SENDER and RECIPIENTS."
48   :type '(choice (string :tag "Name")
49                  (function :tag "Function"))
50   :group 'smtp)
51
52 (defcustom smtp-service "smtp"
53   "*SMTP service port number. \"smtp\" or 25."
54   :type '(choice (integer :tag "25" 25)
55                  (string :tag "smtp" "smtp"))
56   :group 'smtp)
57
58 (defcustom smtp-use-8bitmime t
59   "*If non-nil, use ESMTP 8BITMIME if available."
60   :type 'boolean
61   :group 'smtp)
62
63 (defcustom smtp-local-domain nil
64   "*Local domain name without a host name.
65 If the function (system-name) returns the full internet address,
66 don't define this value."
67   :type '(choice (const nil) string)
68   :group 'smtp)
69
70 (defcustom smtp-debug-info nil
71   "*smtp debug info printout. messages and process buffer."
72   :type 'boolean
73   :group 'smtp)
74
75 (defvar smtp-read-point nil)
76
77 (defun smtp-make-fqdn ()
78   "Return user's fully qualified domain name."
79   (let ((system-name (system-name)))
80     (cond
81      (smtp-local-domain
82       (concat system-name "." smtp-local-domain))
83      ((string-match "[^.]\\.[^.]" system-name)
84       system-name)
85      (t
86       (error "Cannot generate valid FQDN. Set `smtp-local-domain' correctly.")))))
87
88 (defun smtp-via-smtp (sender recipients smtp-text-buffer)
89   (let ((server (if (functionp smtp-server)
90                     (funcall smtp-server sender recipients)
91                   smtp-server))
92         process response extensions)
93     (save-excursion
94       (set-buffer
95        (get-buffer-create
96         (format "*trace of SMTP session to %s*" server)))
97       (erase-buffer)
98       (make-local-variable 'smtp-read-point)
99       (setq smtp-read-point (point-min))
100
101       (unwind-protect
102           (catch 'done
103             (setq process (open-network-stream-as-binary
104                            "SMTP" (current-buffer) server smtp-service))
105             (or process (throw 'done nil))
106
107             (set-process-filter process 'smtp-process-filter)
108
109             ;; Greeting
110             (setq response (smtp-read-response process))
111             (if (or (null (car response))
112                     (not (integerp (car response)))
113                     (>= (car response) 400))
114                 (throw 'done (car (cdr response))))
115
116             ;; EHLO
117             (smtp-send-command process
118                                (format "EHLO %s" (smtp-make-fqdn)))
119             (setq response (smtp-read-response process))
120             (if (or (null (car response))
121                     (not (integerp (car response)))
122                     (>= (car response) 400))
123                 (progn
124                   ;; HELO
125                   (smtp-send-command process
126                                      (format "HELO %s" (smtp-make-fqdn)))
127                   (setq response (smtp-read-response process))
128                   (if (or (null (car response))
129                           (not (integerp (car response)))
130                           (>= (car response) 400))
131                       (throw 'done (car (cdr response)))))
132               (let ((extension-lines (cdr (cdr response))))
133                 (while extension-lines
134                   (push (intern (downcase (substring (car extension-lines) 4)))
135                         extensions)
136                   (setq extension-lines (cdr extension-lines)))))
137
138             ;; ONEX --- One message transaction only (sendmail extension?)
139             (if (or (memq 'onex extensions)
140                     (memq 'xone extensions))
141                 (progn
142                   (smtp-send-command process "ONEX")
143                   (setq response (smtp-read-response process))
144                   (if (or (null (car response))
145                           (not (integerp (car response)))
146                           (>= (car response) 400))
147                       (throw 'done (car (cdr response))))))
148
149             ;; VERB --- Verbose (sendmail extension?)
150             (if (and smtp-debug-info
151                      (or (memq 'verb extensions)
152                          (memq 'xvrb extensions)))
153                 (progn
154                   (smtp-send-command process "VERB")
155                   (setq response (smtp-read-response process))
156                   (if (or (null (car response))
157                           (not (integerp (car response)))
158                           (>= (car response) 400))
159                       (throw 'done (car (cdr response))))))
160
161             ;; XUSR --- Initial (user) submission (sendmail extension?)
162             (if (memq 'xusr extensions)
163                 (progn
164                   (smtp-send-command process "XUSR")
165                   (setq response (smtp-read-response process))
166                   (if (or (null (car response))
167                           (not (integerp (car response)))
168                           (>= (car response) 400))
169                       (throw 'done (car (cdr response))))))
170
171             ;; MAIL FROM:<sender>
172             (smtp-send-command
173              process
174              (format "MAIL FROM:<%s>%s%s"
175                      sender
176                      ;; SIZE --- Message Size Declaration (RFC1870)
177                      (if (memq 'size extensions)
178                          (format " SIZE=%d"
179                                  (save-excursion
180                                    (set-buffer smtp-text-buffer)
181                                    (+ (- (point-max) (point-min))
182                                       ;; Add one byte for each change-of-line
183                                       ;; because or CR-LF representation:
184                                       (count-lines (point-min) (point-max))
185                                       ;; For some reason, an empty line is
186                                       ;; added to the message.  Maybe this
187                                       ;; is a bug, but it can't hurt to add
188                                       ;; those two bytes anyway:
189                                       2)))
190                        "")
191                      ;; 8BITMIME --- 8bit-MIMEtransport (RFC1652)
192                      (if (and (memq '8bitmime extensions)
193                               smtp-use-8bitmime)
194                          " BODY=8BITMIME"
195                        "")))
196             (setq response (smtp-read-response process))
197             (if (or (null (car response))
198                     (not (integerp (car response)))
199                     (>= (car response) 400))
200                 (throw 'done (car (cdr response))))
201
202             ;; RCPT TO:<recipient>
203             (while recipients
204               (smtp-send-command process
205                                  (format "RCPT TO:<%s>" (car recipients)))
206               (setq recipients (cdr recipients))
207               (setq response (smtp-read-response process))
208               (if (or (null (car response))
209                       (not (integerp (car response)))
210                       (>= (car response) 400))
211                   (throw 'done (car (cdr response)))))
212
213             ;; DATA
214             (smtp-send-command process "DATA")
215             (setq response (smtp-read-response process))
216             (if (or (null (car response))
217                     (not (integerp (car response)))
218                     (>= (car response) 400))
219                 (throw 'done (car (cdr response))))
220
221             ;; Mail contents
222             (smtp-send-data process smtp-text-buffer)
223
224             ;; DATA end "."
225             (smtp-send-command process ".")
226             (setq response (smtp-read-response process))
227             (if (or (null (car response))
228                     (not (integerp (car response)))
229                     (>= (car response) 400))
230                 (throw 'done (car (cdr response))))
231
232             t)
233
234         (if (and process
235                  (eq (process-status process) 'open))
236             (progn
237               ;; QUIT
238               (smtp-send-command process "QUIT")
239               (smtp-read-response process)
240               (delete-process process)))))))
241
242 (defun smtp-process-filter (process output)
243   (save-excursion
244     (set-buffer (process-buffer process))
245     (goto-char (point-max))
246     (insert output)))
247
248 (defun smtp-read-response (process)
249   (let ((case-fold-search nil)
250         (response-strings nil)
251         (response-continue t)
252         (return-value '(nil ()))
253         match-end)
254
255     (while response-continue
256       (goto-char smtp-read-point)
257       (while (not (search-forward "\r\n" nil t))
258         (accept-process-output process)
259         (goto-char smtp-read-point))
260
261       (setq match-end (point))
262       (setq response-strings
263             (cons (buffer-substring smtp-read-point (- match-end 2))
264                   response-strings))
265         
266       (goto-char smtp-read-point)
267       (if (looking-at "[0-9]+ ")
268           (let ((begin (match-beginning 0))
269                 (end (match-end 0)))
270             (if smtp-debug-info
271                 (message "%s" (car response-strings)))
272
273             (setq smtp-read-point match-end)
274
275             ;; ignore lines that start with "0"
276             (if (looking-at "0[0-9]+ ")
277                 nil
278               (setq response-continue nil)
279               (setq return-value
280                     (cons (string-to-int
281                            (buffer-substring begin end))
282                           (nreverse response-strings)))))
283         
284         (if (looking-at "[0-9]+-")
285             (progn (if smtp-debug-info
286                      (message "%s" (car response-strings)))
287                    (setq smtp-read-point match-end)
288                    (setq response-continue t))
289           (progn
290             (setq smtp-read-point match-end)
291             (setq response-continue nil)
292             (setq return-value
293                   (cons nil (nreverse response-strings)))))))
294     (setq smtp-read-point match-end)
295     return-value))
296
297 (defun smtp-send-command (process command)
298   (goto-char (point-max))
299   (insert command "\r\n")
300   (setq smtp-read-point (point))
301   (process-send-string process command)
302   (process-send-string process "\r\n"))
303
304 (defun smtp-send-data-1 (process data)
305   (goto-char (point-max))
306   (if smtp-debug-info
307       (insert data "\r\n"))
308   (setq smtp-read-point (point))
309   ;; Escape "." at start of a line.
310   (if (eq (string-to-char data) ?.)
311       (process-send-string process "."))
312   (process-send-string process data)
313   (process-send-string process "\r\n"))
314
315 (defun smtp-send-data (process buffer)
316   (let ((data-continue t)
317         (sending-data nil)
318         this-line
319         this-line-end)
320
321     (save-excursion
322       (set-buffer buffer)
323       (goto-char (point-min)))
324
325     (while data-continue
326       (save-excursion
327         (set-buffer buffer)
328         (beginning-of-line)
329         (setq this-line (point))
330         (end-of-line)
331         (setq this-line-end (point))
332         (setq sending-data nil)
333         (setq sending-data (buffer-substring this-line this-line-end))
334         (if (or (/= (forward-line 1) 0) (eobp))
335             (setq data-continue nil)))
336
337       (smtp-send-data-1 process sending-data))))
338
339 (defun smtp-deduce-address-list (smtp-text-buffer header-start header-end)
340   "Get address list suitable for smtp RCPT TO:<address>."
341   (let ((case-fold-search t)
342         (simple-address-list "")
343         this-line
344         this-line-end
345         addr-regexp
346         (smtp-address-buffer (generate-new-buffer " *smtp-mail*")))
347     (unwind-protect
348         (save-excursion
349           ;;
350           (set-buffer smtp-address-buffer)
351           (erase-buffer)
352           (insert (save-excursion
353                     (set-buffer smtp-text-buffer)
354                     (buffer-substring-no-properties header-start header-end)))
355           (goto-char (point-min))
356           ;; RESENT-* fields should stop processing of regular fields.
357           (save-excursion
358             (if (re-search-forward "^RESENT-TO:" header-end t)
359                 (setq addr-regexp
360                       "^\\(RESENT-TO:\\|RESENT-CC:\\|RESENT-BCC:\\)")
361               (setq addr-regexp  "^\\(TO:\\|CC:\\|BCC:\\)")))
362
363           (while (re-search-forward addr-regexp header-end t)
364             (replace-match "")
365             (setq this-line (match-beginning 0))
366             (forward-line 1)
367             ;; get any continuation lines.
368             (while (and (looking-at "^[ \t]+") (< (point) header-end))
369               (forward-line 1))
370             (setq this-line-end (point-marker))
371             (setq simple-address-list
372                   (concat simple-address-list " "
373                           (mail-strip-quoted-names
374                            (buffer-substring this-line this-line-end)))))
375           (erase-buffer)
376           (insert-string " ")
377           (insert-string simple-address-list)
378           (insert-string "\n")
379           ;; newline --> blank
380           (subst-char-in-region (point-min) (point-max) 10 ?  t)
381           ;; comma   --> blank
382           (subst-char-in-region (point-min) (point-max) ?, ?  t)
383           ;; tab     --> blank
384           (subst-char-in-region (point-min) (point-max)  9 ?  t)
385
386           (goto-char (point-min))
387           ;; tidyness in case hook is not robust when it looks at this
388           (while (re-search-forward "[ \t]+" header-end t) (replace-match " "))
389
390           (goto-char (point-min))
391           (let (recipient-address-list)
392             (while (re-search-forward " \\([^ ]+\\) " (point-max) t)
393               (backward-char 1)
394               (setq recipient-address-list
395                     (cons (buffer-substring (match-beginning 1) (match-end 1))
396                           recipient-address-list)))
397             recipient-address-list))
398       (kill-buffer smtp-address-buffer))))
399
400 (provide 'smtp)
401
402 ;;; smtp.el ends here