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