Initial Commit
[packages] / xemacs-packages / mail-lib / smtpmail.el
1 ;;; smtpmail.el --- simple SMTP protocol (RFC 821) for sending mail
2
3 ;; Copyright (C) 1995, 1996, 2001, 2002, 2003, 2004, 2005,
4 ;;   2006 Free Software Foundation, Inc.
5
6 ;; Author: Tomoji Kagatani <kagatani@rbc.ncl.omron.co.jp>
7 ;; Maintainer: Simon Josefsson <simon@josefsson.org>
8 ;; w32 Maintainer: Brian D. Carlstrom <bdc@ai.mit.edu>
9 ;; ESMTP support: Simon Leinen <simon@switch.ch>
10 ;; Hacked by Mike Taylor, 11th October 1999 to add support for
11 ;; automatically appending a domain to RCPT TO: addresses.
12 ;; AUTH=LOGIN support: Stephen Cranefield <scranefield@infoscience.otago.ac.nz>
13 ;; Keywords: mail
14
15 ;; This file is part of XEmacs.
16
17 ;; XEmacs is free software; you can redistribute it and/or modify
18 ;; it under the terms of the GNU General Public License as published by
19 ;; the Free Software Foundation; either version 2, or (at your option)
20 ;; any later version.
21
22 ;; XEmacs is distributed in the hope that it will be useful,
23 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
24 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 ;; GNU General Public License for more details.
26
27 ;; You should have received a copy of the GNU General Public License
28 ;; along with XEmacs; see the file COPYING.  If not, write to the
29 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
30 ;; Boston, MA 02110-1301, USA.
31
32 ;;; Commentary:
33
34 ;; Send Mail to smtp host from smtpmail temp buffer.
35
36 ;; Please add these lines in your .emacs(_emacs) or use customize.
37 ;;
38 ;;(setq send-mail-function 'smtpmail-send-it) ; if you use `mail'
39 ;;(setq message-send-mail-function 'smtpmail-send-it) ; if you use message/Gnus
40 ;;(setq smtpmail-default-smtp-server "YOUR SMTP HOST")
41 ;;(setq smtpmail-local-domain "YOUR DOMAIN NAME")
42 ;;(setq smtpmail-sendto-domain "YOUR DOMAIN NAME")
43 ;;(setq smtpmail-debug-info t) ; only to debug problems
44 ;;(setq smtpmail-auth-credentials  ; or use ~/.authinfo
45 ;;      '(("YOUR SMTP HOST" 25 "username" "password")))
46 ;;(setq smtpmail-starttls-credentials
47 ;;      '(("YOUR SMTP HOST" 25 "~/.my_smtp_tls.key" "~/.my_smtp_tls.cert")))
48 ;; Where the 25 equals the value of `smtpmail-smtp-service', it can be an
49 ;; integer or a string, just as long as they match (eq).
50
51 ;; To queue mail, set smtpmail-queue-mail to t and use
52 ;; smtpmail-send-queued-mail to send.
53
54 ;; Modified by Stephen Cranefield <scranefield@infoscience.otago.ac.nz>,
55 ;; 22/6/99, to support SMTP Authentication by the AUTH=LOGIN mechanism.
56 ;; See http://help.netscape.com/products/server/messaging/3x/info/smtpauth.html
57 ;; Rewritten by Simon Josefsson to use same credential variable as AUTH
58 ;; support below.
59
60 ;; Modified by Simon Josefsson <jas@pdc.kth.se>, 22/2/99, to support SMTP
61 ;; Authentication by the AUTH mechanism.
62 ;; See http://www.ietf.org/rfc/rfc2554.txt
63
64 ;; Modified by Simon Josefsson <simon@josefsson.org>, 2000-10-07, to support
65 ;; STARTTLS.  Requires external program
66 ;; ftp://ftp.opaopa.org/pub/elisp/starttls-*.tar.gz.
67 ;; See http://www.ietf.org/rfc/rfc2246.txt, http://www.ietf.org/rfc/rfc2487.txt
68
69 ;;; Code:
70
71 (require 'sendmail)
72 (autoload 'starttls-open-stream "starttls")
73 (autoload 'starttls-negotiate "starttls")
74 (autoload 'mail-strip-quoted-names "mail-utils")
75 (autoload 'mail-check-safe-charset "mail-utils")
76 (autoload 'message-make-date "message")
77 (autoload 'message-make-message-id "message")
78 (autoload 'rfc2104-hash "rfc2104")
79 (autoload 'base64-decode-string "base64")
80 (autoload 'netrc-parse "netrc")
81 (autoload 'netrc-machine "netrc")
82 (autoload 'netrc-get "netrc")
83
84 ;;;
85 (defgroup smtpmail nil
86   "SMTP protocol for sending mail."
87   :group 'mail)
88
89
90 (defcustom smtpmail-default-smtp-server nil
91   "*Specify default SMTP server.
92 This only has effect if you specify it before loading the smtpmail library."
93   :type '(choice (const nil) string)
94   :group 'smtpmail)
95
96 (defcustom smtpmail-smtp-server
97   (or (getenv "SMTPSERVER") smtpmail-default-smtp-server)
98   "*The name of the host running SMTP server."
99   :type '(choice (const nil) string)
100   :group 'smtpmail)
101
102 (defcustom smtpmail-smtp-service 25
103   "*SMTP service port number.
104 The default value would be \"smtp\" or 25 ."
105   :type '(choice (integer :tag "Port") (string :tag "Service"))
106   :group 'smtpmail)
107
108 (defcustom smtpmail-local-domain nil
109   "*Local domain name without a host name.
110 If the function (system-name) returns the full internet address,
111 don't define this value."
112   :type '(choice (const nil) string)
113   :group 'smtpmail)
114
115 (defcustom smtpmail-sendto-domain nil
116   "*Local domain name without a host name.
117 This is appended (with an @-sign) to any specified recipients which do
118 not include an @-sign, so that each RCPT TO address is fully qualified.
119 \(Some configurations of sendmail require this.)
120
121 Don't bother to set this unless you have get an error like:
122         Sending failed; SMTP protocol error
123 when sending mail, and the *trace of SMTP session to <somewhere>*
124 buffer includes an exchange like:
125         RCPT TO: <someone>
126         501 <someone>: recipient address must contain a domain
127 "
128   :type '(choice (const nil) string)
129   :group 'smtpmail)
130
131 (defcustom smtpmail-debug-info nil
132   "Whether to print info in buffer *trace of SMTP session to <somewhere>*.
133 See also `smtpmail-debug-verb' which determines if the SMTP protocol should
134 be verbose as well."
135   :type 'boolean
136   :group 'smtpmail)
137
138 (defcustom smtpmail-debug-verb nil
139   "Whether this library sends the SMTP VERB command or not.
140 The commands enables verbose information from the SMTP server."
141   :type 'boolean
142   :group 'smtpmail)
143
144 (defcustom smtpmail-code-conv-from nil ;; *junet*
145   "*smtpmail code convert from this code to *internal*..for tiny-mime.."
146   :type 'boolean
147   :group 'smtpmail)
148
149 (defcustom smtpmail-queue-mail nil
150   "*Specify if mail is queued (if t) or sent immediately (if nil).
151 If queued, it is stored in the directory `smtpmail-queue-dir'
152 and sent with `smtpmail-send-queued-mail'."
153   :type 'boolean
154   :group 'smtpmail)
155
156 (defcustom smtpmail-queue-dir "~/Mail/queued-mail/"
157   "*Directory where `smtpmail.el' stores queued mail."
158   :type 'directory
159   :group 'smtpmail)
160
161 (defcustom smtpmail-auth-credentials "~/.authinfo"
162   "Specify username and password for servers, directly or via .netrc file.
163 This variable can either be a filename pointing to a file in netrc(5)
164 format, or list of four-element lists that contain, in order,
165 `servername' (a string), `port' (an integer), `user' (a string) and
166 `password' (a string, or nil to query the user when needed).  If you
167 need to enter a `realm' too, add it to the user string, so that it
168 looks like `user@realm'."
169   :type '(choice file
170                  (repeat (list (string  :tag "Server")
171                        (integer :tag "Port")
172                        (string  :tag "Username")
173                        (choice (const :tag "Query when needed" nil)
174                                        (string  :tag "Password")))))
175   :group 'smtpmail)
176
177 (defcustom smtpmail-starttls-credentials '(("" 25 "" ""))
178   "Specify STARTTLS keys and certificates for servers.
179 This is a list of four-element list with `servername' (a string),
180 `port' (an integer), `key' (a filename) and `certificate' (a filename)."
181   :type '(repeat (list (string  :tag "Server")
182                        (integer :tag "Port")
183                        (file    :tag "Key")
184                        (file    :tag "Certificate")))
185   :group 'smtpmail)
186
187 (defcustom smtpmail-warn-about-unknown-extensions nil
188   "*If set, print warnings about unknown SMTP extensions.
189 This is mainly useful for development purposes, to learn about
190 new SMTP extensions that might be useful to support."
191   :type 'boolean
192   :group 'smtpmail)
193
194 (defvar smtpmail-queue-index-file "index"
195   "File name of queued mail index,
196 This is relative to `smtpmail-queue-dir'.")
197
198 (defvar smtpmail-address-buffer)
199 (defvar smtpmail-recipient-address-list)
200
201 (defvar smtpmail-queue-counter 0)
202
203 ;; Buffer-local variable.
204 (defvar smtpmail-read-point)
205
206 (defvar smtpmail-queue-index (concat smtpmail-queue-dir
207                                      smtpmail-queue-index-file))
208
209 (defconst smtpmail-auth-supported '(cram-md5 plain login)
210   "List of supported SMTP AUTH mechanisms.")
211
212 ;;;
213 ;;;
214 ;;;
215
216 (defvar smtpmail-mail-address nil
217   "Value to use for envelope-from address for mail from ambient buffer.")
218
219 ;;;###autoload
220 (defun smtpmail-send-it ()
221   (let ((errbuf (if mail-interactive
222                     (generate-new-buffer " smtpmail errors")
223                   0))
224         (tembuf (generate-new-buffer " smtpmail temp"))
225         (case-fold-search nil)
226         delimline
227         (mailbuf (current-buffer))
228         ;; Examine this variable now, so that
229         ;; local binding in the mail buffer will take effect.
230         (smtpmail-mail-address
231          (or (and mail-specify-envelope-from (mail-envelope-from))
232              (user-mail-address))) ;; XEmacs
233         ;; XEmacs: Don't frob `smtpmail-code-conv-from' here
234         )
235     (unwind-protect
236         (save-excursion
237           (set-buffer tembuf)
238           (erase-buffer)
239           (insert-buffer-substring mailbuf)
240           (goto-char (point-max))
241           ;; require one newline at the end.
242           (or (= (preceding-char) ?\n)
243               (insert ?\n))
244           ;; Change header-delimiter to be what sendmail expects.
245           (mail-sendmail-undelimit-header)
246           (setq delimline (point-marker))
247 ;;        (sendmail-synch-aliases)
248           (if (and mail-aliases (fboundp 'expand-mail-aliases)) ; XEmacs
249               (expand-mail-aliases (point-min) delimline))
250           (goto-char (point-min))
251           ;; ignore any blank lines in the header
252           (while (and (re-search-forward "\n\n\n*" delimline t)
253                       (< (point) delimline))
254             (replace-match "\n"))
255           (let ((case-fold-search t))
256             ;; We used to process Resent-... headers here,
257             ;; but it was not done properly, and the job
258             ;; is done correctly in smtpmail-deduce-address-list.
259             ;; Don't send out a blank subject line
260             (goto-char (point-min))
261             (if (re-search-forward "^Subject:\\([ \t]*\n\\)+\\b" delimline t)
262                 (replace-match "")
263               ;; This one matches a Subject just before the header delimiter.
264               (if (and (re-search-forward "^Subject:\\([ \t]*\n\\)+" delimline t)
265                        (= (match-end 0) delimline))
266                   (replace-match "")))
267             ;; Put the "From:" field in unless for some odd reason
268             ;; they put one in themselves.
269             (goto-char (point-min))
270             (if (not (re-search-forward "^From:" delimline t))
271                 (let* ((login smtpmail-mail-address)
272                        (fullname (user-full-name)))
273                   (cond ((eq mail-from-style 'angles)
274                          (insert "From: " fullname)
275                          (let ((fullname-start (+ (point-min) 6))
276                                (fullname-end (point-marker)))
277                            (goto-char fullname-start)
278                            ;; Look for a character that cannot appear unquoted
279                            ;; according to RFC 822.
280                            (if (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]"
281                                                   fullname-end 1)
282                                (progn
283                                  ;; Quote fullname, escaping specials.
284                                  (goto-char fullname-start)
285                                  (insert "\"")
286                                  (while (re-search-forward "[\"\\]"
287                                                            fullname-end 1)
288                                    (replace-match "\\\\\\&" t))
289                                  (insert "\""))))
290                          (insert " <" login ">\n"))
291                         ((eq mail-from-style 'parens)
292                          (insert "From: " login " (")
293                          (let ((fullname-start (point)))
294                            (insert fullname)
295                            (let ((fullname-end (point-marker)))
296                              (goto-char fullname-start)
297                              ;; RFC 822 says \ and nonmatching parentheses
298                              ;; must be escaped in comments.
299                              ;; Escape every instance of ()\ ...
300                              (while (re-search-forward "[()\\]" fullname-end 1)
301                                (replace-match "\\\\\\&" t))
302                              ;; ... then undo escaping of matching parentheses,
303                              ;; including matching nested parentheses.
304                              (goto-char fullname-start)
305                              (while (re-search-forward
306                                      "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
307                                      fullname-end 1)
308                                (replace-match "\\1(\\3)" t)
309                                (goto-char fullname-start))))
310                          (insert ")\n"))
311                         ((null mail-from-style)
312                          (insert "From: " login "\n")))))
313             ;; Insert a `Message-Id:' field if there isn't one yet.
314             (goto-char (point-min))
315             (unless (re-search-forward "^Message-Id:" delimline t)
316               (insert "Message-Id: " (message-make-message-id) "\n"))
317             ;; Insert a `Date:' field if there isn't one yet.
318             (goto-char (point-min))
319             (unless (re-search-forward "^Date:" delimline t)
320               (insert "Date: " (message-make-date) "\n"))
321             ;; Insert an extra newline if we need it to work around
322             ;; Sun's bug that swallows newlines.
323             (goto-char (1+ delimline))
324             (if (eval mail-mailer-swallows-blank-line)
325                 (newline))
326             ;; Find and handle any FCC fields.
327             (goto-char (point-min))
328             (if (re-search-forward "^FCC:" delimline t)
329                 (mail-do-fcc delimline))
330             (if mail-interactive
331                 (with-current-buffer errbuf
332                   (erase-buffer))))
333           ;;
334           ;;
335           ;;
336           (setq smtpmail-address-buffer (generate-new-buffer "*smtp-mail*"))
337           (setq smtpmail-recipient-address-list
338                     (smtpmail-deduce-address-list tembuf (point-min) delimline))
339           (kill-buffer smtpmail-address-buffer)
340
341           ;; XEmacs change
342           (mail-check-safe-charset)
343
344           (smtpmail-do-bcc delimline)
345           ; Send or queue
346           (if (not smtpmail-queue-mail)
347               (if (not (null smtpmail-recipient-address-list))
348                   (if (not (smtpmail-via-smtp
349                             smtpmail-recipient-address-list tembuf))
350                       (error "Sending failed; SMTP protocol error"))
351                 (error "Sending failed; no recipients"))
352             (let* ((file-data
353                     (expand-file-name
354                      (format "%s_%i"
355                              (format-time-string "%Y-%m-%d_%H:%M:%S")
356                              (setq smtpmail-queue-counter
357                                    (1+ smtpmail-queue-counter)))
358                      smtpmail-queue-dir))
359                    (file-data (convert-standard-filename file-data))
360                    (file-elisp (concat file-data ".el"))
361                    (buffer-data (create-file-buffer file-data))
362                    (buffer-elisp (create-file-buffer file-elisp))
363                    (buffer-scratch "*queue-mail*"))
364               (unless (file-exists-p smtpmail-queue-dir)
365                 (make-directory smtpmail-queue-dir t))
366               (with-current-buffer buffer-data
367                 (erase-buffer)
368                 (insert-buffer-substring tembuf)
369                 (write-file file-data)
370                 (set-buffer buffer-elisp)
371                 (erase-buffer)
372                 (insert (concat
373                          "(setq smtpmail-recipient-address-list '"
374                          (prin1-to-string smtpmail-recipient-address-list)
375                          ")\n"))
376                 (write-file file-elisp)
377                 (set-buffer (generate-new-buffer buffer-scratch))
378                 (insert (concat file-data "\n"))
379                 (append-to-file (point-min)
380                                 (point-max)
381                                 smtpmail-queue-index)
382                 )
383               (kill-buffer buffer-scratch)
384               (kill-buffer buffer-data)
385               (kill-buffer buffer-elisp))))
386       (kill-buffer tembuf)
387       (if (bufferp errbuf)
388           (kill-buffer errbuf)))))
389
390 ;;;###autoload
391 (defun smtpmail-send-queued-mail ()
392   "Send mail that was queued as a result of setting `smtpmail-queue-mail'."
393   (interactive)
394   (with-temp-buffer
395     ;;; Get index, get first mail, send it, update index, get second
396     ;;; mail, send it, etc...
397     (let ((file-msg ""))
398       (insert-file-contents smtpmail-queue-index)
399       (goto-char (point-min))
400       (while (not (eobp))
401         (setq file-msg (buffer-substring (point) (line-end-position)))
402         (load file-msg)
403         ;; Insert the message literally: it is already encoded as per
404         ;; the MIME headers, and code conversions might guess the
405         ;; encoding wrongly.
406         (with-temp-buffer
407           (let ((coding-system-for-read 'binary)) ;; XEmacs
408             (insert-file-contents file-msg))
409           (let ((smtpmail-mail-address
410                  (or (and mail-specify-envelope-from (mail-envelope-from))
411                      (user-mail-address)))) ;; XEmacs
412             (if (not (null smtpmail-recipient-address-list))
413                 (if (not (smtpmail-via-smtp smtpmail-recipient-address-list
414                                             (current-buffer)))
415                     (error "Sending failed; SMTP protocol error"))
416               (error "Sending failed; no recipients"))))
417         (delete-file file-msg)
418         (delete-file (concat file-msg ".el"))
419         (delete-region (point-at-bol) (point-at-bol 2)))
420       (write-region (point-min) (point-max) smtpmail-queue-index))))
421
422 ;(defun smtpmail-via-smtp (host,port,sender,destination,smtpmail-text-buffer)
423
424 (defun smtpmail-fqdn ()
425   (if smtpmail-local-domain
426       (concat (system-name) "." smtpmail-local-domain)
427     (system-name)))
428
429 (defsubst smtpmail-cred-server (cred)
430   (nth 0 cred))
431
432 (defsubst smtpmail-cred-port (cred)
433   (nth 1 cred))
434
435 (defsubst smtpmail-cred-key (cred)
436   (nth 2 cred))
437
438 (defsubst smtpmail-cred-user (cred)
439   (nth 2 cred))
440
441 (defsubst smtpmail-cred-cert (cred)
442   (nth 3 cred))
443
444 (defsubst smtpmail-cred-passwd (cred)
445   (nth 3 cred))
446
447 (defun smtpmail-find-credentials (cred server port)
448   (catch 'done
449     (let ((l cred) el)
450       (while (setq el (pop l))
451         (when (and (equal server (smtpmail-cred-server el))
452                    (equal port (smtpmail-cred-port el)))
453           (throw 'done el))))))
454
455 (defun smtpmail-maybe-append-domain (recipient)
456   (if (or (not smtpmail-sendto-domain)
457           (string-match "@" recipient))
458       recipient
459     (concat recipient "@" smtpmail-sendto-domain)))
460
461 (defun smtpmail-intersection (list1 list2)
462   (let ((result nil))
463     (dolist (el2 list2)
464       (when (memq el2 list1)
465         (push el2 result)))
466     (nreverse result)))
467
468 (defvar starttls-extra-args)
469 (defvar starttls-extra-arguments)
470
471 (defun smtpmail-open-stream (process-buffer host port)
472   (let ((cred (smtpmail-find-credentials
473                smtpmail-starttls-credentials host port)))
474     (if (null (and cred (condition-case ()
475                             ;; XEmacs change
476                             (with-boundp '(starttls-use-gnutls
477                                            starttls-gnutls-program
478                                            starttls-program)
479                               (require 'starttls)
480                               (call-process (if starttls-use-gnutls
481                                                 starttls-gnutls-program
482                                               starttls-program)))
483                           (error nil))))
484         ;; The normal case.
485         (open-network-stream "SMTP" process-buffer host port)
486       (let* ((cred-key (smtpmail-cred-key cred))
487              (cred-cert (smtpmail-cred-cert cred))
488              (starttls-extra-args
489               (append
490                starttls-extra-args
491                (when (and (stringp cred-key) (stringp cred-cert)
492                           (file-regular-p
493                            (setq cred-key (expand-file-name cred-key)))
494                           (file-regular-p
495                            (setq cred-cert (expand-file-name cred-cert))))
496                  (list "--key-file" cred-key "--cert-file" cred-cert))))
497              (starttls-extra-arguments
498               (append
499                starttls-extra-arguments
500                (when (and (stringp cred-key) (stringp cred-cert)
501                           (file-regular-p
502                            (setq cred-key (expand-file-name cred-key)))
503                           (file-regular-p
504                            (setq cred-cert (expand-file-name cred-cert))))
505                  (list "--x509keyfile" cred-key "--x509certfile" cred-cert)))))
506         (starttls-open-stream "SMTP" process-buffer host port)))))
507
508 (defun smtpmail-try-auth-methods (process supported-extensions host port)
509   (let* ((mechs (cdr-safe (assoc 'auth supported-extensions)))
510          (mech (car (smtpmail-intersection smtpmail-auth-supported mechs)))
511          (cred (if (stringp smtpmail-auth-credentials)
512                    (let* ((netrc (netrc-parse smtpmail-auth-credentials))
513                           (port-name (format "%s" (or port "smtp")))
514                           (hostentry (netrc-machine netrc host port-name
515                                                     port-name)))
516                      (when hostentry
517                        (list host port
518                              (netrc-get hostentry "login")
519                              (netrc-get hostentry "password"))))
520                  (smtpmail-find-credentials
521                   smtpmail-auth-credentials host port)))
522          (passwd (when cred
523                    (or (smtpmail-cred-passwd cred)
524                        (read-passwd
525                         (format "SMTP password for %s:%s: "
526                                 (smtpmail-cred-server cred)
527                                 (smtpmail-cred-port cred))))))
528          ret)
529     (when (and cred mech)
530       (cond
531        ((eq mech 'cram-md5)
532         (smtpmail-send-command process (upcase (format "AUTH %s" mech)))
533         (if (or (null (car (setq ret (smtpmail-read-response process))))
534                 (not (integerp (car ret)))
535                 (>= (car ret) 400))
536             (throw 'done nil))
537         (when (eq (car ret) 334)
538           (let* ((challenge (substring (cadr ret) 4))
539                  (decoded (base64-decode-string challenge))
540                  (hash (rfc2104-hash 'md5 64 16 passwd decoded))
541                  (response (concat (smtpmail-cred-user cred) " " hash))
542                  (encoded (base64-encode-string response)))
543             (smtpmail-send-command process (format "%s" encoded))
544             (if (or (null (car (setq ret (smtpmail-read-response process))))
545                     (not (integerp (car ret)))
546                     (>= (car ret) 400))
547                 (throw 'done nil)))))
548        ((eq mech 'login)
549         (smtpmail-send-command process "AUTH LOGIN")
550         (if (or (null (car (setq ret (smtpmail-read-response process))))
551                 (not (integerp (car ret)))
552                 (>= (car ret) 400))
553             (throw 'done nil))
554         (smtpmail-send-command
555          process (base64-encode-string (smtpmail-cred-user cred)))
556         (if (or (null (car (setq ret (smtpmail-read-response process))))
557                 (not (integerp (car ret)))
558                 (>= (car ret) 400))
559             (throw 'done nil))
560         (smtpmail-send-command process (base64-encode-string passwd))
561         (if (or (null (car (setq ret (smtpmail-read-response process))))
562                 (not (integerp (car ret)))
563                 (>= (car ret) 400))
564             (throw 'done nil)))
565        ((eq mech 'plain)
566         ;; We used to send an empty initial request, and wait for an
567         ;; empty response, and then send the password, but this
568         ;; violate a SHOULD in RFC 2222 paragraph 5.1.  Note that this
569         ;; is not sent if the server did not advertise AUTH PLAIN in
570         ;; the EHLO response.  See RFC 2554 for more info.
571         (smtpmail-send-command process
572                                (concat "AUTH PLAIN "
573                                        (base64-encode-string
574                                         (concat "\0"
575                                                 (smtpmail-cred-user cred)
576                                                 "\0"
577                                                 passwd))))
578         (if (or (null (car (setq ret (smtpmail-read-response process))))
579                 (not (integerp (car ret)))
580                 (not (equal (car ret) 235)))
581             (throw 'done nil)))
582
583        (t
584         (error "Mechanism %s not implemented" mech)))
585       ;; Remember the password.
586       (when (and (not (stringp smtpmail-auth-credentials))
587                  (null (smtpmail-cred-passwd cred)))
588         (setcar (cdr (cdr (cdr cred))) passwd)))))
589
590 (defun smtpmail-via-smtp (recipient smtpmail-text-buffer)
591   (let ((process nil)
592         (host (or smtpmail-smtp-server
593                   (error "`smtpmail-smtp-server' not defined")))
594         (port smtpmail-smtp-service)
595         ;; smtpmail-mail-address should be set to the appropriate
596         ;; buffer-local value by the caller, but in case not:
597         (envelope-from (or smtpmail-mail-address
598                            (and mail-specify-envelope-from
599                                 (mail-envelope-from))
600                            (user-mail-address))) ;; XEmacs
601         response-code
602         greeting
603         process-buffer
604         (supported-extensions '()))
605     (unwind-protect
606         (catch 'done
607           ;; get or create the trace buffer
608           (setq process-buffer
609                 (get-buffer-create (format "*trace of SMTP session to %s*" host)))
610
611           ;; clear the trace buffer of old output
612           (with-current-buffer process-buffer
613             (setq buffer-undo-list t)
614             (erase-buffer))
615
616           ;; open the connection to the server
617           (setq process (smtpmail-open-stream process-buffer host port))
618           (and (null process) (throw 'done nil))
619
620           ;; set the send-filter
621           (set-process-filter process 'smtpmail-process-filter)
622
623           (with-current-buffer process-buffer
624             ;; XEmacs change
625             (if (or (featurep 'mule) (featurep 'file-coding))
626                 (set-process-coding-system process 'no-conversion-unix 'no-conversion-unix))
627             (make-local-variable 'smtpmail-read-point)
628             (setq smtpmail-read-point (point-min))
629
630
631             (if (or (null (car (setq greeting (smtpmail-read-response process))))
632                     (not (integerp (car greeting)))
633                     (>= (car greeting) 400))
634                 (throw 'done nil)
635               )
636
637             (let ((do-ehlo t)
638                   (do-starttls t))
639               (while do-ehlo
640             ;; EHLO
641             (smtpmail-send-command process (format "EHLO %s" (smtpmail-fqdn)))
642
643             (if (or (null (car (setq response-code
644                                      (smtpmail-read-response process))))
645                     (not (integerp (car response-code)))
646                     (>= (car response-code) 400))
647                 (progn
648                   ;; HELO
649                   (smtpmail-send-command
650                    process (format "HELO %s" (smtpmail-fqdn)))
651
652                   (if (or (null (car (setq response-code
653                                            (smtpmail-read-response process))))
654                           (not (integerp (car response-code)))
655                           (>= (car response-code) 400))
656                       (throw 'done nil)))
657               (dolist (line (cdr (cdr response-code)))
658                 (let ((name (mapcar (lambda (s) (intern (downcase s)))
659                                     (split-string (substring line 4) "[ ]"))))
660                   (and (eq (length name) 1)
661                        (setq name (car name)))
662                     (and name
663                        (cond ((memq (if (consp name) (car name) name)
664                                     '(verb xvrb 8bitmime onex xone
665                                                   expn size dsn etrn
666                                       enhancedstatuscodes
667                                       help xusr
668                                       auth=login auth starttls))
669                                 (setq supported-extensions
670                                       (cons name supported-extensions)))
671                                (smtpmail-warn-about-unknown-extensions
672                               (message "Unknown extension %s" name)))))))
673
674             (if (and do-starttls
675                      (smtpmail-find-credentials smtpmail-starttls-credentials host port)
676                      (member 'starttls supported-extensions)
677                      (numberp (process-id process)))
678                 (progn
679                   (smtpmail-send-command process (format "STARTTLS"))
680                   (if (or (null (car (setq response-code (smtpmail-read-response process))))
681                           (not (integerp (car response-code)))
682                           (>= (car response-code) 400))
683                       (throw 'done nil))
684                   (starttls-negotiate process)
685                   (setq do-starttls nil))
686               (setq do-ehlo nil))))
687
688             (smtpmail-try-auth-methods process supported-extensions host port)
689
690             (if (or (member 'onex supported-extensions)
691                     (member 'xone supported-extensions))
692                 (progn
693                   (smtpmail-send-command process (format "ONEX"))
694                   (if (or (null (car (setq response-code (smtpmail-read-response process))))
695                           (not (integerp (car response-code)))
696                           (>= (car response-code) 400))
697                       (throw 'done nil))))
698
699             (if (and smtpmail-debug-verb
700                      (or (member 'verb supported-extensions)
701                          (member 'xvrb supported-extensions)))
702                 (progn
703                   (smtpmail-send-command process (format "VERB"))
704                   (if (or (null (car (setq response-code (smtpmail-read-response process))))
705                           (not (integerp (car response-code)))
706                           (>= (car response-code) 400))
707                       (throw 'done nil))))
708
709             (if (member 'xusr supported-extensions)
710                 (progn
711                   (smtpmail-send-command process (format "XUSR"))
712                   (if (or (null (car (setq response-code (smtpmail-read-response process))))
713                           (not (integerp (car response-code)))
714                           (>= (car response-code) 400))
715                       (throw 'done nil))))
716
717             ;; MAIL FROM:<sender>
718             (let ((size-part
719                    (if (or (member 'size supported-extensions)
720                            (assoc 'size supported-extensions))
721                        (format " SIZE=%d"
722                                (with-current-buffer smtpmail-text-buffer
723                                  ;; size estimate:
724                                  (+ (- (point-max) (point-min))
725                                     ;; Add one byte for each change-of-line
726                                     ;; because of CR-LF representation:
727                                     (count-lines (point-min) (point-max)))))
728                      ""))
729                   (body-part
730                    (if (member '8bitmime supported-extensions)
731                        ;; FIXME:
732                        ;; Code should be added here that transforms
733                        ;; the contents of the message buffer into
734                        ;; something the receiving SMTP can handle.
735                        ;; For a receiver that supports 8BITMIME, this
736                        ;; may mean converting BINARY to BASE64, or
737                        ;; adding Content-Transfer-Encoding and the
738                        ;; other MIME headers.  The code should also
739                        ;; return an indication of what encoding the
740                        ;; message buffer is now, i.e. ASCII or
741                        ;; 8BITMIME.
742                        (if nil
743                            " BODY=8BITMIME"
744                          "")
745                      "")))
746 ;             (smtpmail-send-command process (format "MAIL FROM:%s@%s" (user-login-name) (smtpmail-fqdn)))
747               (smtpmail-send-command process (format "MAIL FROM:<%s>%s%s"
748                                                      envelope-from
749                                                      size-part
750                                                      body-part))
751
752               (if (or (null (car (setq response-code (smtpmail-read-response process))))
753                       (not (integerp (car response-code)))
754                       (>= (car response-code) 400))
755                   (throw 'done nil)
756                 ))
757
758             ;; RCPT TO:<recipient>
759             (let ((n 0))
760               (while (not (null (nth n recipient)))
761                 (smtpmail-send-command process (format "RCPT TO:<%s>" (smtpmail-maybe-append-domain (nth n recipient))))
762                 (setq n (1+ n))
763
764                 (setq response-code (smtpmail-read-response process))
765                 (if (or (null (car response-code))
766                         (not (integerp (car response-code)))
767                         (>= (car response-code) 400))
768                     (throw 'done nil)
769                   )
770                 ))
771
772             ;; DATA
773             (smtpmail-send-command process "DATA")
774
775             (if (or (null (car (setq response-code (smtpmail-read-response process))))
776                     (not (integerp (car response-code)))
777                     (>= (car response-code) 400))
778                 (throw 'done nil)
779               )
780
781             ;; Mail contents
782             (smtpmail-send-data process smtpmail-text-buffer)
783
784             ;;DATA end "."
785             (smtpmail-send-command process ".")
786
787             (if (or (null (car (setq response-code (smtpmail-read-response process))))
788                     (not (integerp (car response-code)))
789                     (>= (car response-code) 400))
790                 (throw 'done nil)
791               )
792
793             ;;QUIT
794 ;           (smtpmail-send-command process "QUIT")
795 ;           (and (null (car (smtpmail-read-response process)))
796 ;                (throw 'done nil))
797             t ))
798       (if process
799           (with-current-buffer (process-buffer process)
800             (smtpmail-send-command process "QUIT")
801             (smtpmail-read-response process)
802
803 ;           (if (or (null (car (setq response-code (smtpmail-read-response process))))
804 ;                   (not (integerp (car response-code)))
805 ;                   (>= (car response-code) 400))
806 ;               (throw 'done nil)
807 ;             )
808             (delete-process process)
809             (unless smtpmail-debug-info
810               (kill-buffer process-buffer)))))))
811
812
813 (defun smtpmail-process-filter (process output)
814   (with-current-buffer (process-buffer process)
815     (goto-char (point-max))
816     (insert output)))
817
818 (defun smtpmail-read-response (process)
819   (let ((case-fold-search nil)
820         (response-strings nil)
821         (response-continue t)
822         (return-value '(nil ()))
823         match-end)
824     (catch 'done
825       (while response-continue
826         (goto-char smtpmail-read-point)
827         (while (not (search-forward "\r\n" nil t))
828           (unless (memq (process-status process) '(open run))
829             (throw 'done nil))
830           (accept-process-output process)
831           (goto-char smtpmail-read-point))
832
833         (setq match-end (point))
834         (setq response-strings
835               (cons (buffer-substring smtpmail-read-point (- match-end 2))
836                     response-strings))
837
838         (goto-char smtpmail-read-point)
839         (if (looking-at "[0-9]+ ")
840             (let ((begin (match-beginning 0))
841                   (end (match-end 0)))
842               (if smtpmail-debug-info
843                   (message "%s" (car response-strings)))
844
845               (setq smtpmail-read-point match-end)
846
847               ;; ignore lines that start with "0"
848               (if (looking-at "0[0-9]+ ")
849                   nil
850                 (setq response-continue nil)
851                 (setq return-value
852                       (cons (string-to-number
853                              (buffer-substring begin end))
854                             (nreverse response-strings)))))
855
856           (if (looking-at "[0-9]+-")
857               (progn (if smtpmail-debug-info
858                          (message "%s" (car response-strings)))
859                      (setq smtpmail-read-point match-end)
860                      (setq response-continue t))
861             (progn
862               (setq smtpmail-read-point match-end)
863               (setq response-continue nil)
864               (setq return-value
865                     (cons nil (nreverse response-strings)))))))
866       (setq smtpmail-read-point match-end))
867     return-value))
868
869
870 (defun smtpmail-send-command (process command)
871   (goto-char (point-max))
872   (if (= (aref command 0) ?P)
873       (insert "PASS <omitted>\r\n")
874     (insert command "\r\n"))
875   (setq smtpmail-read-point (point))
876   (process-send-string process command)
877   (process-send-string process "\r\n"))
878
879 (defun smtpmail-send-data-1 (process data)
880   (goto-char (point-max))
881
882   ;; XEmacs change
883   (if (and (or (featurep 'mule) (featurep 'file-coding))
884            (not (null smtpmail-code-conv-from)))
885       (setq data (encode-coding-string data smtpmail-code-conv-from)))
886
887   (if smtpmail-debug-info
888       (insert data "\r\n"))
889
890   (setq smtpmail-read-point (point))
891   ;; Escape "." at start of a line
892   (if (eq (string-to-char data) ?.)
893       (process-send-string process "."))
894   (process-send-string process data)
895   (process-send-string process "\r\n")
896   )
897
898 (defun smtpmail-send-data (process buffer)
899   (let ((data-continue t) sending-data)
900     (with-current-buffer buffer
901       (goto-char (point-min)))
902     (while data-continue
903       (with-current-buffer buffer
904         (setq sending-data (buffer-substring (point-at-bol) (point-at-eol)))
905         (end-of-line 2)
906         (setq data-continue (not (eobp))))
907       (smtpmail-send-data-1 process sending-data))))
908
909 (defun smtpmail-deduce-address-list (smtpmail-text-buffer header-start header-end)
910   "Get address list suitable for smtp RCPT TO: <address>."
911   (unwind-protect
912       (with-current-buffer smtpmail-address-buffer
913         (erase-buffer)
914         (let
915             ((case-fold-search t)
916              (simple-address-list "")
917              this-line
918              this-line-end
919              addr-regexp)
920           (insert-buffer-substring smtpmail-text-buffer header-start header-end)
921           (goto-char (point-min))
922           ;; RESENT-* fields should stop processing of regular fields.
923           (save-excursion
924             (setq addr-regexp
925                   (if (re-search-forward "^Resent-\\(to\\|cc\\|bcc\\):"
926                                          header-end t)
927                       "^Resent-\\(to\\|cc\\|bcc\\):"
928                     "^\\(To:\\|Cc:\\|Bcc:\\)")))
929
930           (while (re-search-forward addr-regexp header-end t)
931             (replace-match "")
932             (setq this-line (match-beginning 0))
933             (forward-line 1)
934             ;; get any continuation lines
935             (while (and (looking-at "^[ \t]+") (< (point) header-end))
936               (forward-line 1))
937             (setq this-line-end (point-marker))
938             (setq simple-address-list
939                   (concat simple-address-list " "
940                           (mail-strip-quoted-names (buffer-substring this-line this-line-end))))
941             )
942           (erase-buffer)
943           (insert " " simple-address-list "\n")
944           (subst-char-in-region (point-min) (point-max) 10 ?  t);; newline --> blank
945           (subst-char-in-region (point-min) (point-max) ?, ?  t);; comma   --> blank
946           (subst-char-in-region (point-min) (point-max)  9 ?  t);; tab     --> blank
947
948           (goto-char (point-min))
949           ;; tidyness in case hook is not robust when it looks at this
950           (while (re-search-forward "[ \t]+" header-end t) (replace-match " "))
951
952           (goto-char (point-min))
953           (let (recipient-address-list)
954             (while (re-search-forward " \\([^ ]+\\) " (point-max) t)
955               (backward-char 1)
956               (setq recipient-address-list (cons (buffer-substring (match-beginning 1) (match-end 1))
957                                                  recipient-address-list))
958               )
959             (setq smtpmail-recipient-address-list recipient-address-list))
960
961           )
962         )
963     )
964   )
965
966
967 (defun smtpmail-do-bcc (header-end)
968   "Delete [Resent-]BCC: and their continuation lines from the header area.
969 There may be multiple BCC: lines, and each may have arbitrarily
970 many continuation lines."
971   (let ((case-fold-search t))
972     (save-excursion
973       (goto-char (point-min))
974       ;; iterate over all BCC: lines
975       (while (re-search-forward "^\\(RESENT-\\)?BCC:" header-end t)
976         (delete-region (match-beginning 0)
977                        (progn (forward-line 1) (point)))
978         ;; get rid of any continuation lines
979         (while (and (looking-at "^[ \t].*\n") (< (point) header-end))
980           (replace-match ""))))))
981
982
983 (provide 'smtpmail)
984
985 ;;; arch-tag: a76992df-6d71-43b7-9e72-4bacc6c05466
986 ;;; smtpmail.el ends here