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