Merge from gnus--rel--5.10
[gnus] / contrib / 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 GNU Emacs.
16
17 ;; GNU Emacs 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 ;; GNU Emacs 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 GNU Emacs; 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 'message-make-date "message")
76 (autoload 'message-make-message-id "message")
77 (autoload 'rfc2104-hash "rfc2104")
78 (autoload 'netrc-parse "netrc")
79 (autoload 'netrc-machine "netrc")
80 (autoload 'netrc-get "netrc")
81
82 ;;;
83 (defgroup smtpmail nil
84   "SMTP protocol for sending mail."
85   :group 'mail)
86
87
88 (defcustom smtpmail-default-smtp-server nil
89   "*Specify default SMTP server.
90 This only has effect if you specify it before loading the smtpmail library."
91   :type '(choice (const nil) string)
92   :group 'smtpmail)
93
94 (defcustom smtpmail-smtp-server
95   (or (getenv "SMTPSERVER") smtpmail-default-smtp-server)
96   "*The name of the host running SMTP server."
97   :type '(choice (const nil) string)
98   :group 'smtpmail)
99
100 (defcustom smtpmail-smtp-service 25
101   "*SMTP service port number.
102 The default value would be \"smtp\" or 25 ."
103   :type '(choice (integer :tag "Port") (string :tag "Service"))
104   :group 'smtpmail)
105
106 (defcustom smtpmail-local-domain nil
107   "*Local domain name without a host name.
108 If the function (system-name) returns the full internet address,
109 don't define this value."
110   :type '(choice (const nil) string)
111   :group 'smtpmail)
112
113 (defcustom smtpmail-sendto-domain nil
114   "*Local domain name without a host name.
115 This is appended (with an @-sign) to any specified recipients which do
116 not include an @-sign, so that each RCPT TO address is fully qualified.
117 \(Some configurations of sendmail require this.)
118
119 Don't bother to set this unless you have get an error like:
120         Sending failed; SMTP protocol error
121 when sending mail, and the *trace of SMTP session to <somewhere>*
122 buffer includes an exchange like:
123         RCPT TO: <someone>
124         501 <someone>: recipient address must contain a domain
125 "
126   :type '(choice (const nil) string)
127   :group 'smtpmail)
128
129 (defcustom smtpmail-debug-info nil
130   "Whether to print info in buffer *trace of SMTP session to <somewhere>*.
131 See also `smtpmail-debug-verb' which determines if the SMTP protocol should
132 be verbose as well."
133   :type 'boolean
134   :group 'smtpmail)
135
136 (defcustom smtpmail-debug-verb nil
137   "Whether this library sends the SMTP VERB command or not.
138 The commands enables verbose information from the SMTP server."
139   :type 'boolean
140   :group 'smtpmail)
141
142 (defcustom smtpmail-code-conv-from nil ;; *junet*
143   "*smtpmail code convert from this code to *internal*..for tiny-mime.."
144   :type 'boolean
145   :group 'smtpmail)
146
147 (defcustom smtpmail-queue-mail nil
148   "*Specify if mail is queued (if t) or sent immediately (if nil).
149 If queued, it is stored in the directory `smtpmail-queue-dir'
150 and sent with `smtpmail-send-queued-mail'."
151   :type 'boolean
152   :group 'smtpmail)
153
154 (defcustom smtpmail-queue-dir "~/Mail/queued-mail/"
155   "*Directory where `smtpmail.el' stores queued mail."
156   :type 'directory
157   :group 'smtpmail)
158
159 (defcustom smtpmail-auth-credentials "~/.authinfo"
160   "Specify username and password for servers, directly or via .netrc file.
161 This variable can either be a filename pointing to a file in netrc(5)
162 format, or list of four-element lists that contain, in order,
163 `servername' (a string), `port' (an integer), `user' (a string) and
164 `password' (a string, or nil to query the user when needed).  If you
165 need to enter a `realm' too, add it to the user string, so that it
166 looks like `user@realm'."
167   :type '(choice file
168                  (repeat (list (string  :tag "Server")
169                        (integer :tag "Port")
170                        (string  :tag "Username")
171                        (choice (const :tag "Query when needed" nil)
172                                        (string  :tag "Password")))))
173   :version "22.1"
174   :group 'smtpmail)
175
176 (defcustom smtpmail-starttls-credentials '(("" 25 "" ""))
177   "Specify STARTTLS keys and certificates for servers.
178 This is a list of four-element list with `servername' (a string),
179 `port' (an integer), `key' (a filename) and `certificate' (a
180 filename).
181 If you do not have a certificate/key pair, leave the `key' and
182 `certificate' fields as `nil'.  A key/certificate pair is only
183 needed if you want to use X.509 client authenticated
184 connections."
185   :type '(repeat (list (string  :tag "Server")
186                        (integer :tag "Port")
187                        (file    :tag "Key")
188                        (file    :tag "Certificate")))
189   :version "21.1"
190   :group 'smtpmail)
191
192 (defcustom smtpmail-warn-about-unknown-extensions nil
193   "*If set, print warnings about unknown SMTP extensions.
194 This is mainly useful for development purposes, to learn about
195 new SMTP extensions that might be useful to support."
196   :type 'boolean
197   :version "21.1"
198   :group 'smtpmail)
199
200 (defvar smtpmail-queue-index-file "index"
201   "File name of queued mail index,
202 This is relative to `smtpmail-queue-dir'.")
203
204 (defvar smtpmail-address-buffer)
205 (defvar smtpmail-recipient-address-list)
206
207 (defvar smtpmail-queue-counter 0)
208
209 ;; Buffer-local variable.
210 (defvar smtpmail-read-point)
211
212 (defvar smtpmail-queue-index (concat smtpmail-queue-dir
213                                      smtpmail-queue-index-file))
214
215 (defconst smtpmail-auth-supported '(cram-md5 plain login)
216   "List of supported SMTP AUTH mechanisms.")
217
218 ;;;
219 ;;;
220 ;;;
221
222 (defvar smtpmail-mail-address nil
223   "Value to use for envelope-from address for mail from ambient buffer.")
224
225 ;;;###autoload
226 (defun smtpmail-send-it ()
227   (let ((errbuf (if mail-interactive
228                     (generate-new-buffer " smtpmail errors")
229                   0))
230         (tembuf (generate-new-buffer " smtpmail temp"))
231         (case-fold-search nil)
232         delimline
233         (mailbuf (current-buffer))
234         ;; Examine this variable now, so that
235         ;; local binding in the mail buffer will take effect.
236         (smtpmail-mail-address
237          (or (and mail-specify-envelope-from (mail-envelope-from))
238              user-mail-address))
239         (smtpmail-code-conv-from
240          (if enable-multibyte-characters
241              (let ((sendmail-coding-system smtpmail-code-conv-from))
242                (select-message-coding-system)))))
243     (unwind-protect
244         (save-excursion
245           (set-buffer tembuf)
246           (erase-buffer)
247           (insert-buffer-substring mailbuf)
248           (goto-char (point-max))
249           ;; require one newline at the end.
250           (or (= (preceding-char) ?\n)
251               (insert ?\n))
252           ;; Change header-delimiter to be what sendmail expects.
253           (mail-sendmail-undelimit-header)
254           (setq delimline (point-marker))
255 ;;        (sendmail-synch-aliases)
256           (if mail-aliases
257               (expand-mail-aliases (point-min) delimline))
258           (goto-char (point-min))
259           ;; ignore any blank lines in the header
260           (while (and (re-search-forward "\n\n\n*" delimline t)
261                       (< (point) delimline))
262             (replace-match "\n"))
263           (let ((case-fold-search t))
264             ;; We used to process Resent-... headers here,
265             ;; but it was not done properly, and the job
266             ;; is done correctly in smtpmail-deduce-address-list.
267             ;; Don't send out a blank subject line
268             (goto-char (point-min))
269             (if (re-search-forward "^Subject:\\([ \t]*\n\\)+\\b" delimline t)
270                 (replace-match "")
271               ;; This one matches a Subject just before the header delimiter.
272               (if (and (re-search-forward "^Subject:\\([ \t]*\n\\)+" delimline t)
273                        (= (match-end 0) delimline))
274                   (replace-match "")))
275             ;; Put the "From:" field in unless for some odd reason
276             ;; they put one in themselves.
277             (goto-char (point-min))
278             (if (not (re-search-forward "^From:" delimline t))
279                 (let* ((login smtpmail-mail-address)
280                        (fullname (user-full-name)))
281                   (cond ((eq mail-from-style 'angles)
282                          (insert "From: " fullname)
283                          (let ((fullname-start (+ (point-min) 6))
284                                (fullname-end (point-marker)))
285                            (goto-char fullname-start)
286                            ;; Look for a character that cannot appear unquoted
287                            ;; according to RFC 822.
288                            (if (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]"
289                                                   fullname-end 1)
290                                (progn
291                                  ;; Quote fullname, escaping specials.
292                                  (goto-char fullname-start)
293                                  (insert "\"")
294                                  (while (re-search-forward "[\"\\]"
295                                                            fullname-end 1)
296                                    (replace-match "\\\\\\&" t))
297                                  (insert "\""))))
298                          (insert " <" login ">\n"))
299                         ((eq mail-from-style 'parens)
300                          (insert "From: " login " (")
301                          (let ((fullname-start (point)))
302                            (insert fullname)
303                            (let ((fullname-end (point-marker)))
304                              (goto-char fullname-start)
305                              ;; RFC 822 says \ and nonmatching parentheses
306                              ;; must be escaped in comments.
307                              ;; Escape every instance of ()\ ...
308                              (while (re-search-forward "[()\\]" fullname-end 1)
309                                (replace-match "\\\\\\&" t))
310                              ;; ... then undo escaping of matching parentheses,
311                              ;; including matching nested parentheses.
312                              (goto-char fullname-start)
313                              (while (re-search-forward
314                                      "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
315                                      fullname-end 1)
316                                (replace-match "\\1(\\3)" t)
317                                (goto-char fullname-start))))
318                          (insert ")\n"))
319                         ((null mail-from-style)
320                          (insert "From: " login "\n")))))
321             ;; Insert a `Message-Id:' field if there isn't one yet.
322             (goto-char (point-min))
323             (unless (re-search-forward "^Message-Id:" delimline t)
324               (insert "Message-Id: " (message-make-message-id) "\n"))
325             ;; Insert a `Date:' field if there isn't one yet.
326             (goto-char (point-min))
327             (unless (re-search-forward "^Date:" delimline t)
328               (insert "Date: " (message-make-date) "\n"))
329             ;; Insert an extra newline if we need it to work around
330             ;; Sun's bug that swallows newlines.
331             (goto-char (1+ delimline))
332             (if (eval mail-mailer-swallows-blank-line)
333                 (newline))
334             ;; Find and handle any FCC fields.
335             (goto-char (point-min))
336             (if (re-search-forward "^FCC:" delimline t)
337                 (mail-do-fcc delimline))
338             (if mail-interactive
339                 (with-current-buffer errbuf
340                   (erase-buffer))))
341           ;;
342           ;;
343           ;;
344           (setq smtpmail-address-buffer (generate-new-buffer "*smtp-mail*"))
345           (setq smtpmail-recipient-address-list
346                     (smtpmail-deduce-address-list tembuf (point-min) delimline))
347           (kill-buffer smtpmail-address-buffer)
348
349           (smtpmail-do-bcc delimline)
350           ; Send or queue
351           (if (not smtpmail-queue-mail)
352               (if (not (null smtpmail-recipient-address-list))
353                   (if (not (smtpmail-via-smtp
354                             smtpmail-recipient-address-list tembuf))
355                       (error "Sending failed; SMTP protocol error"))
356                 (error "Sending failed; no recipients"))
357             (let* ((file-data
358                     (expand-file-name
359                      (format "%s_%i"
360                              (format-time-string "%Y-%m-%d_%H:%M:%S")
361                              (setq smtpmail-queue-counter
362                                    (1+ smtpmail-queue-counter)))
363                      smtpmail-queue-dir))
364                    (file-data (convert-standard-filename file-data))
365                    (file-elisp (concat file-data ".el"))
366                    (buffer-data (create-file-buffer file-data))
367                    (buffer-elisp (create-file-buffer file-elisp))
368                    (buffer-scratch "*queue-mail*"))
369               (unless (file-exists-p smtpmail-queue-dir)
370                 (make-directory smtpmail-queue-dir t))
371               (with-current-buffer buffer-data
372                 (erase-buffer)
373                 (insert-buffer-substring tembuf)
374                 (write-file file-data)
375                 (set-buffer buffer-elisp)
376                 (erase-buffer)
377                 (insert (concat
378                          "(setq smtpmail-recipient-address-list '"
379                          (prin1-to-string smtpmail-recipient-address-list)
380                          ")\n"))
381                 (write-file file-elisp)
382                 (set-buffer (generate-new-buffer buffer-scratch))
383                 (insert (concat file-data "\n"))
384                 (append-to-file (point-min)
385                                 (point-max)
386                                 smtpmail-queue-index)
387                 )
388               (kill-buffer buffer-scratch)
389               (kill-buffer buffer-data)
390               (kill-buffer buffer-elisp))))
391       (kill-buffer tembuf)
392       (if (bufferp errbuf)
393           (kill-buffer errbuf)))))
394
395 ;;;###autoload
396 (defun smtpmail-send-queued-mail ()
397   "Send mail that was queued as a result of setting `smtpmail-queue-mail'."
398   (interactive)
399   (with-temp-buffer
400     ;;; Get index, get first mail, send it, update index, get second
401     ;;; mail, send it, etc...
402     (let ((file-msg ""))
403       (insert-file-contents smtpmail-queue-index)
404       (goto-char (point-min))
405       (while (not (eobp))
406         (setq file-msg (buffer-substring (point) (line-end-position)))
407         (load file-msg)
408         ;; Insert the message literally: it is already encoded as per
409         ;; the MIME headers, and code conversions might guess the
410         ;; encoding wrongly.
411         (with-temp-buffer
412           (let ((coding-system-for-read 'no-conversion))
413             (insert-file-contents file-msg))
414           (let ((smtpmail-mail-address
415                  (or (and mail-specify-envelope-from (mail-envelope-from))
416                      user-mail-address)))
417             (if (not (null smtpmail-recipient-address-list))
418                 (if (not (smtpmail-via-smtp smtpmail-recipient-address-list
419                                             (current-buffer)))
420                     (error "Sending failed; SMTP protocol error"))
421               (error "Sending failed; no recipients"))))
422         (delete-file file-msg)
423         (delete-file (concat file-msg ".el"))
424         (delete-region (point-at-bol) (point-at-bol 2)))
425       (write-region (point-min) (point-max) smtpmail-queue-index))))
426
427 ;(defun smtpmail-via-smtp (host,port,sender,destination,smtpmail-text-buffer)
428
429 (defun smtpmail-fqdn ()
430   (if smtpmail-local-domain
431       (concat (system-name) "." smtpmail-local-domain)
432     (system-name)))
433
434 (defsubst smtpmail-cred-server (cred)
435   (nth 0 cred))
436
437 (defsubst smtpmail-cred-port (cred)
438   (nth 1 cred))
439
440 (defsubst smtpmail-cred-key (cred)
441   (nth 2 cred))
442
443 (defsubst smtpmail-cred-user (cred)
444   (nth 2 cred))
445
446 (defsubst smtpmail-cred-cert (cred)
447   (nth 3 cred))
448
449 (defsubst smtpmail-cred-passwd (cred)
450   (nth 3 cred))
451
452 (defun smtpmail-find-credentials (cred server port)
453   (catch 'done
454     (let ((l cred) el)
455       (while (setq el (pop l))
456         (when (and (equal server (smtpmail-cred-server el))
457                    (equal port (smtpmail-cred-port el)))
458           (throw 'done el))))))
459
460 (defun smtpmail-maybe-append-domain (recipient)
461   (if (or (not smtpmail-sendto-domain)
462           (string-match "@" recipient))
463       recipient
464     (concat recipient "@" smtpmail-sendto-domain)))
465
466 (defun smtpmail-intersection (list1 list2)
467   (let ((result nil))
468     (dolist (el2 list2)
469       (when (memq el2 list1)
470         (push el2 result)))
471     (nreverse result)))
472
473 (defvar starttls-extra-args)
474 (defvar starttls-extra-arguments)
475
476 (defun smtpmail-open-stream (process-buffer host port)
477   (let ((cred (smtpmail-find-credentials
478                smtpmail-starttls-credentials host port)))
479     (if (null (and cred (condition-case ()
480                             (with-no-warnings
481                               (require 'starttls)
482                               (call-process (if starttls-use-gnutls
483                                                 starttls-gnutls-program
484                                               starttls-program)))
485                           (error nil))))
486         ;; The normal case.
487         (open-network-stream "SMTP" process-buffer host port)
488       (let* ((cred-key (smtpmail-cred-key cred))
489              (cred-cert (smtpmail-cred-cert cred))
490              (starttls-extra-args
491               (append
492                starttls-extra-args
493                (when (and (stringp cred-key) (stringp cred-cert)
494                           (file-regular-p
495                            (setq cred-key (expand-file-name cred-key)))
496                           (file-regular-p
497                            (setq cred-cert (expand-file-name cred-cert))))
498                  (list "--key-file" cred-key "--cert-file" cred-cert))))
499              (starttls-extra-arguments
500               (append
501                starttls-extra-arguments
502                (when (and (stringp cred-key) (stringp cred-cert)
503                           (file-regular-p
504                            (setq cred-key (expand-file-name cred-key)))
505                           (file-regular-p
506                            (setq cred-cert (expand-file-name cred-cert))))
507                  (list "--x509keyfile" cred-key "--x509certfile" cred-cert)))))
508         (starttls-open-stream "SMTP" process-buffer host port)))))
509
510 (defun smtpmail-try-auth-methods (process supported-extensions host port)
511   (let* ((mechs (cdr-safe (assoc 'auth supported-extensions)))
512          (mech (car (smtpmail-intersection smtpmail-auth-supported mechs)))
513          (cred (if (stringp smtpmail-auth-credentials)
514                    (let* ((netrc (netrc-parse smtpmail-auth-credentials))
515                           (port-name (format "%s" (or port "smtp")))
516                           (hostentry (netrc-machine netrc host port-name
517                                                     port-name)))
518                      (when hostentry
519                        (list host port
520                              (netrc-get hostentry "login")
521                              (netrc-get hostentry "password"))))
522                  (smtpmail-find-credentials
523                   smtpmail-auth-credentials host port)))
524          (passwd (when cred
525                    (or (smtpmail-cred-passwd cred)
526                        (read-passwd
527                         (format "SMTP password for %s:%s: "
528                                 (smtpmail-cred-server cred)
529                                 (smtpmail-cred-port cred))))))
530          ret)
531     (when (and cred mech)
532       (cond
533        ((eq mech 'cram-md5)
534         (smtpmail-send-command process (upcase (format "AUTH %s" mech)))
535         (if (or (null (car (setq ret (smtpmail-read-response process))))
536                 (not (integerp (car ret)))
537                 (>= (car ret) 400))
538             (throw 'done nil))
539         (when (eq (car ret) 334)
540           (let* ((challenge (substring (cadr ret) 4))
541                  (decoded (base64-decode-string challenge))
542                  (hash (rfc2104-hash 'md5 64 16 passwd decoded))
543                  (response (concat (smtpmail-cred-user cred) " " hash))
544                  (encoded (base64-encode-string response t)))
545             (smtpmail-send-command process (format "%s" encoded))
546             (if (or (null (car (setq ret (smtpmail-read-response process))))
547                     (not (integerp (car ret)))
548                     (>= (car ret) 400))
549                 (throw 'done nil)))))
550        ((eq mech 'login)
551         (smtpmail-send-command process "AUTH LOGIN")
552         (if (or (null (car (setq ret (smtpmail-read-response process))))
553                 (not (integerp (car ret)))
554                 (>= (car ret) 400))
555             (throw 'done nil))
556         (smtpmail-send-command
557          process (base64-encode-string (smtpmail-cred-user cred) t))
558         (if (or (null (car (setq ret (smtpmail-read-response process))))
559                 (not (integerp (car ret)))
560                 (>= (car ret) 400))
561             (throw 'done nil))
562         (smtpmail-send-command process (base64-encode-string passwd t))
563         (if (or (null (car (setq ret (smtpmail-read-response process))))
564                 (not (integerp (car ret)))
565                 (>= (car ret) 400))
566             (throw 'done nil)))
567        ((eq mech 'plain)
568         ;; We used to send an empty initial request, and wait for an
569         ;; empty response, and then send the password, but this
570         ;; violate a SHOULD in RFC 2222 paragraph 5.1.  Note that this
571         ;; is not sent if the server did not advertise AUTH PLAIN in
572         ;; the EHLO response.  See RFC 2554 for more info.
573         (smtpmail-send-command process
574                                (concat "AUTH PLAIN "
575                                        (base64-encode-string
576                                         (concat "\0"
577                                                 (smtpmail-cred-user cred)
578                                                 "\0"
579                                                 passwd) t)))
580         (if (or (null (car (setq ret (smtpmail-read-response process))))
581                 (not (integerp (car ret)))
582                 (not (equal (car ret) 235)))
583             (throw 'done nil)))
584
585        (t
586         (error "Mechanism %s not implemented" mech)))
587       ;; Remember the password.
588       (when (and (not (stringp smtpmail-auth-credentials))
589                  (null (smtpmail-cred-passwd cred)))
590         (setcar (cdr (cdr (cdr cred))) passwd)))))
591
592 (defun smtpmail-via-smtp (recipient smtpmail-text-buffer)
593   (let ((process nil)
594         (host (or smtpmail-smtp-server
595                   (error "`smtpmail-smtp-server' not defined")))
596         (port smtpmail-smtp-service)
597         ;; smtpmail-mail-address should be set to the appropriate
598         ;; buffer-local value by the caller, but in case not:
599         (envelope-from (or smtpmail-mail-address
600                            (and mail-specify-envelope-from
601                                 (mail-envelope-from))
602                            user-mail-address))
603         response-code
604         greeting
605         process-buffer
606         (supported-extensions '()))
607     (unwind-protect
608         (catch 'done
609           ;; get or create the trace buffer
610           (setq process-buffer
611                 (get-buffer-create (format "*trace of SMTP session to %s*" host)))
612
613           ;; clear the trace buffer of old output
614           (with-current-buffer process-buffer
615             (setq buffer-undo-list t)
616             (erase-buffer))
617
618           ;; open the connection to the server
619           (setq process (smtpmail-open-stream process-buffer host port))
620           (and (null process) (throw 'done nil))
621
622           ;; set the send-filter
623           (set-process-filter process 'smtpmail-process-filter)
624
625           (with-current-buffer process-buffer
626             (set-buffer-process-coding-system 'raw-text-unix 'raw-text-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   (if (and (multibyte-string-p data)
883            smtpmail-code-conv-from)
884       (setq data (string-as-multibyte
885                   (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