Merge from emacs--devo--0
[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, 2007, 2008 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, 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 ;; This version of `smtpmail.el' should only be used with Emacs 21.
72 (if (featurep 'xemacs)
73     (error "Please use `smtpmail.el' from the mail-lib package.")
74   (when (>= emacs-major-version 22)
75     (error "Please use `smtpmail.el' bundled with Emacs.")))
76
77 (require 'sendmail)
78 (autoload 'starttls-open-stream "starttls")
79 (autoload 'starttls-negotiate "starttls")
80 (autoload 'mail-strip-quoted-names "mail-utils")
81 (autoload 'message-make-date "message")
82 (autoload 'message-make-message-id "message")
83 (autoload 'rfc2104-hash "rfc2104")
84 (autoload 'netrc-parse "netrc")
85 (autoload 'netrc-machine "netrc")
86 (autoload 'netrc-get "netrc")
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
224 ;;;
225 ;;;
226 ;;;
227
228 (defvar smtpmail-mail-address nil
229   "Value to use for envelope-from address for mail from ambient buffer.")
230
231 ;;;###autoload
232 (defun smtpmail-send-it ()
233   (let ((errbuf (if mail-interactive
234                     (generate-new-buffer " smtpmail errors")
235                   0))
236         (tembuf (generate-new-buffer " smtpmail temp"))
237         (case-fold-search nil)
238         delimline
239         (mailbuf (current-buffer))
240         ;; Examine this variable now, so that
241         ;; local binding in the mail buffer will take effect.
242         (smtpmail-mail-address
243          (or (and mail-specify-envelope-from (mail-envelope-from))
244              user-mail-address))
245         (smtpmail-code-conv-from
246          (if enable-multibyte-characters
247              (let ((sendmail-coding-system smtpmail-code-conv-from))
248                (select-message-coding-system)))))
249     (unwind-protect
250         (save-excursion
251           (set-buffer tembuf)
252           (erase-buffer)
253           ;; Use the same buffer-file-coding-system as in the mail
254           ;; buffer, otherwise any write-region invocations (e.g., in
255           ;; mail-do-fcc below) will annoy with asking for a suitable
256           ;; encoding.
257           ;;
258           ;; This file (`gnus/contrib/smtpmail.el') is only useful for Emacs
259           ;; which doesn't support the third argument (NOMODIFY) of
260           ;; `set-buffer-file-coding-system'.
261           (set-buffer-file-coding-system smtpmail-code-conv-from nil)
262           (set-buffer-modified-p nil)
263           (force-mode-line-update)
264           (insert-buffer-substring mailbuf)
265           (goto-char (point-max))
266           ;; require one newline at the end.
267           (or (= (preceding-char) ?\n)
268               (insert ?\n))
269           ;; Change header-delimiter to be what sendmail expects.
270           (mail-sendmail-undelimit-header)
271           (setq delimline (point-marker))
272 ;;        (sendmail-synch-aliases)
273           (if mail-aliases
274               (expand-mail-aliases (point-min) delimline))
275           (goto-char (point-min))
276           ;; ignore any blank lines in the header
277           (while (and (re-search-forward "\n\n\n*" delimline t)
278                       (< (point) delimline))
279             (replace-match "\n"))
280           (let ((case-fold-search t))
281             ;; We used to process Resent-... headers here,
282             ;; but it was not done properly, and the job
283             ;; is done correctly in smtpmail-deduce-address-list.
284             ;; Don't send out a blank subject line
285             (goto-char (point-min))
286             (if (re-search-forward "^Subject:\\([ \t]*\n\\)+\\b" delimline t)
287                 (replace-match "")
288               ;; This one matches a Subject just before the header delimiter.
289               (if (and (re-search-forward "^Subject:\\([ \t]*\n\\)+" delimline t)
290                        (= (match-end 0) delimline))
291                   (replace-match "")))
292             ;; Put the "From:" field in unless for some odd reason
293             ;; they put one in themselves.
294             (goto-char (point-min))
295             (if (not (re-search-forward "^From:" delimline t))
296                 (let* ((login smtpmail-mail-address)
297                        (fullname (user-full-name)))
298                   (cond ((eq mail-from-style 'angles)
299                          (insert "From: " fullname)
300                          (let ((fullname-start (+ (point-min) 6))
301                                (fullname-end (point-marker)))
302                            (goto-char fullname-start)
303                            ;; Look for a character that cannot appear unquoted
304                            ;; according to RFC 822.
305                            (if (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]"
306                                                   fullname-end 1)
307                                (progn
308                                  ;; Quote fullname, escaping specials.
309                                  (goto-char fullname-start)
310                                  (insert "\"")
311                                  (while (re-search-forward "[\"\\]"
312                                                            fullname-end 1)
313                                    (replace-match "\\\\\\&" t))
314                                  (insert "\""))))
315                          (insert " <" login ">\n"))
316                         ((eq mail-from-style 'parens)
317                          (insert "From: " login " (")
318                          (let ((fullname-start (point)))
319                            (insert fullname)
320                            (let ((fullname-end (point-marker)))
321                              (goto-char fullname-start)
322                              ;; RFC 822 says \ and nonmatching parentheses
323                              ;; must be escaped in comments.
324                              ;; Escape every instance of ()\ ...
325                              (while (re-search-forward "[()\\]" fullname-end 1)
326                                (replace-match "\\\\\\&" t))
327                              ;; ... then undo escaping of matching parentheses,
328                              ;; including matching nested parentheses.
329                              (goto-char fullname-start)
330                              (while (re-search-forward
331                                      "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
332                                      fullname-end 1)
333                                (replace-match "\\1(\\3)" t)
334                                (goto-char fullname-start))))
335                          (insert ")\n"))
336                         ((null mail-from-style)
337                          (insert "From: " login "\n")))))
338             ;; Insert a `Message-Id:' field if there isn't one yet.
339             (goto-char (point-min))
340             (unless (re-search-forward "^Message-Id:" delimline t)
341               (insert "Message-Id: " (message-make-message-id) "\n"))
342             ;; Insert a `Date:' field if there isn't one yet.
343             (goto-char (point-min))
344             (unless (re-search-forward "^Date:" delimline t)
345               (insert "Date: " (message-make-date) "\n"))
346             ;; Possibly add a MIME header for the current coding system
347             (let (charset)
348               (goto-char (point-min))
349               (and (eq mail-send-nonascii 'mime)
350                    (not (re-search-forward "^MIME-version:" delimline t))
351                    (progn (skip-chars-forward "\0-\177")
352                           (/= (point) (point-max)))
353                    smtpmail-code-conv-from
354                    (setq charset
355                          (coding-system-get smtpmail-code-conv-from
356                                             'mime-charset))
357                    (goto-char delimline)
358                    (insert "MIME-version: 1.0\n"
359                            "Content-type: text/plain; charset="
360                            (symbol-name charset)
361                            "\nContent-Transfer-Encoding: 8bit\n")))
362             ;; Insert an extra newline if we need it to work around
363             ;; Sun's bug that swallows newlines.
364             (goto-char (1+ delimline))
365             (if (eval mail-mailer-swallows-blank-line)
366                 (newline))
367             ;; Find and handle any FCC fields.
368             (goto-char (point-min))
369             (if (re-search-forward "^FCC:" delimline t)
370                 ;; Force mail-do-fcc to use the encoding of the mail
371                 ;; buffer to encode outgoing messages on FCC files.
372                 (let ((coding-system-for-write smtpmail-code-conv-from))
373                   (mail-do-fcc delimline)))
374             (if mail-interactive
375                 (with-current-buffer errbuf
376                   (erase-buffer))))
377           ;;
378           ;;
379           ;;
380           (setq smtpmail-address-buffer (generate-new-buffer "*smtp-mail*"))
381           (setq smtpmail-recipient-address-list
382                     (smtpmail-deduce-address-list tembuf (point-min) delimline))
383           (kill-buffer smtpmail-address-buffer)
384
385           (smtpmail-do-bcc delimline)
386           ; Send or queue
387           (if (not smtpmail-queue-mail)
388               (if (not (null smtpmail-recipient-address-list))
389                   (if (not (smtpmail-via-smtp
390                             smtpmail-recipient-address-list tembuf))
391                       (error "Sending failed; SMTP protocol error"))
392                 (error "Sending failed; no recipients"))
393             (let* ((file-data
394                     (expand-file-name
395                      (format "%s_%i"
396                              (format-time-string "%Y-%m-%d_%H:%M:%S")
397                              (setq smtpmail-queue-counter
398                                    (1+ smtpmail-queue-counter)))
399                      smtpmail-queue-dir))
400                    (file-data (convert-standard-filename file-data))
401                    (file-elisp (concat file-data ".el"))
402                    (buffer-data (create-file-buffer file-data))
403                    (buffer-elisp (create-file-buffer file-elisp))
404                    (buffer-scratch "*queue-mail*"))
405               (unless (file-exists-p smtpmail-queue-dir)
406                 (make-directory smtpmail-queue-dir t))
407               (with-current-buffer buffer-data
408                 (erase-buffer)
409                 (set-buffer-file-coding-system smtpmail-code-conv-from nil)
410                 (insert-buffer-substring tembuf)
411                 (write-file file-data)
412                 (set-buffer buffer-elisp)
413                 (erase-buffer)
414                 (insert (concat
415                          "(setq smtpmail-recipient-address-list '"
416                          (prin1-to-string smtpmail-recipient-address-list)
417                          ")\n"))
418                 (write-file file-elisp)
419                 (set-buffer (generate-new-buffer buffer-scratch))
420                 (insert (concat file-data "\n"))
421                 (append-to-file (point-min)
422                                 (point-max)
423                                 smtpmail-queue-index)
424                 )
425               (kill-buffer buffer-scratch)
426               (kill-buffer buffer-data)
427               (kill-buffer buffer-elisp))))
428       (kill-buffer tembuf)
429       (if (bufferp errbuf)
430           (kill-buffer errbuf)))))
431
432 ;;;###autoload
433 (defun smtpmail-send-queued-mail ()
434   "Send mail that was queued as a result of setting `smtpmail-queue-mail'."
435   (interactive)
436   (with-temp-buffer
437     ;;; Get index, get first mail, send it, update index, get second
438     ;;; mail, send it, etc...
439     (let ((file-msg ""))
440       (insert-file-contents smtpmail-queue-index)
441       (goto-char (point-min))
442       (while (not (eobp))
443         (setq file-msg (buffer-substring (point) (line-end-position)))
444         (load file-msg)
445         ;; Insert the message literally: it is already encoded as per
446         ;; the MIME headers, and code conversions might guess the
447         ;; encoding wrongly.
448         (with-temp-buffer
449           (let ((coding-system-for-read 'no-conversion))
450             (insert-file-contents file-msg))
451           (let ((smtpmail-mail-address
452                  (or (and mail-specify-envelope-from (mail-envelope-from))
453                      user-mail-address)))
454             (if (not (null smtpmail-recipient-address-list))
455                 (if (not (smtpmail-via-smtp smtpmail-recipient-address-list
456                                             (current-buffer)))
457                     (error "Sending failed; SMTP protocol error"))
458               (error "Sending failed; no recipients"))))
459         (delete-file file-msg)
460         (delete-file (concat file-msg ".el"))
461         (delete-region (point-at-bol) (point-at-bol 2)))
462       (write-region (point-min) (point-max) smtpmail-queue-index))))
463
464 ;(defun smtpmail-via-smtp (host,port,sender,destination,smtpmail-text-buffer)
465
466 (defun smtpmail-fqdn ()
467   (if smtpmail-local-domain
468       (concat (system-name) "." smtpmail-local-domain)
469     (system-name)))
470
471 (defsubst smtpmail-cred-server (cred)
472   (nth 0 cred))
473
474 (defsubst smtpmail-cred-port (cred)
475   (nth 1 cred))
476
477 (defsubst smtpmail-cred-key (cred)
478   (nth 2 cred))
479
480 (defsubst smtpmail-cred-user (cred)
481   (nth 2 cred))
482
483 (defsubst smtpmail-cred-cert (cred)
484   (nth 3 cred))
485
486 (defsubst smtpmail-cred-passwd (cred)
487   (nth 3 cred))
488
489 (defun smtpmail-find-credentials (cred server port)
490   (catch 'done
491     (let ((l cred) el)
492       (while (setq el (pop l))
493         (when (and (equal server (smtpmail-cred-server el))
494                    (equal port (smtpmail-cred-port el)))
495           (throw 'done el))))))
496
497 (defun smtpmail-maybe-append-domain (recipient)
498   (if (or (not smtpmail-sendto-domain)
499           (string-match "@" recipient))
500       recipient
501     (concat recipient "@" smtpmail-sendto-domain)))
502
503 (defun smtpmail-intersection (list1 list2)
504   (let ((result nil))
505     (dolist (el2 list2)
506       (when (memq el2 list1)
507         (push el2 result)))
508     (nreverse result)))
509
510 (defvar starttls-extra-args)
511 (defvar starttls-extra-arguments)
512
513 (defun smtpmail-open-stream (process-buffer host port)
514   (let ((cred (smtpmail-find-credentials
515                smtpmail-starttls-credentials host port)))
516     (if (null (and cred (condition-case ()
517                             (with-no-warnings
518                               (require 'starttls)
519                               (call-process (if starttls-use-gnutls
520                                                 starttls-gnutls-program
521                                               starttls-program)))
522                           (error nil))))
523         ;; The normal case.
524         (open-network-stream "SMTP" process-buffer host port)
525       (let* ((cred-key (smtpmail-cred-key cred))
526              (cred-cert (smtpmail-cred-cert cred))
527              (starttls-extra-args
528               (append
529                starttls-extra-args
530                (when (and (stringp cred-key) (stringp cred-cert)
531                           (file-regular-p
532                            (setq cred-key (expand-file-name cred-key)))
533                           (file-regular-p
534                            (setq cred-cert (expand-file-name cred-cert))))
535                  (list "--key-file" cred-key "--cert-file" cred-cert))))
536              (starttls-extra-arguments
537               (append
538                starttls-extra-arguments
539                (when (and (stringp cred-key) (stringp cred-cert)
540                           (file-regular-p
541                            (setq cred-key (expand-file-name cred-key)))
542                           (file-regular-p
543                            (setq cred-cert (expand-file-name cred-cert))))
544                  (list "--x509keyfile" cred-key "--x509certfile" cred-cert)))))
545         (starttls-open-stream "SMTP" process-buffer host port)))))
546
547 (defun smtpmail-try-auth-methods (process supported-extensions host port)
548   (let* ((mechs (cdr-safe (assoc 'auth supported-extensions)))
549          (mech (car (smtpmail-intersection smtpmail-auth-supported mechs)))
550          (cred (if (stringp smtpmail-auth-credentials)
551                    (let* ((netrc (netrc-parse smtpmail-auth-credentials))
552                           (port-name (format "%s" (or port "smtp")))
553                           (hostentry (netrc-machine netrc host port-name
554                                                     port-name)))
555                      (when hostentry
556                        (list host port
557                              (netrc-get hostentry "login")
558                              (netrc-get hostentry "password"))))
559                  (smtpmail-find-credentials
560                   smtpmail-auth-credentials host port)))
561          (passwd (when cred
562                    (or (smtpmail-cred-passwd cred)
563                        (read-passwd
564                         (format "SMTP password for %s:%s: "
565                                 (smtpmail-cred-server cred)
566                                 (smtpmail-cred-port cred))))))
567          ret)
568     (when (and cred mech)
569       (cond
570        ((eq mech 'cram-md5)
571         (smtpmail-send-command process (upcase (format "AUTH %s" mech)))
572         (if (or (null (car (setq ret (smtpmail-read-response process))))
573                 (not (integerp (car ret)))
574                 (>= (car ret) 400))
575             (throw 'done nil))
576         (when (eq (car ret) 334)
577           (let* ((challenge (substring (cadr ret) 4))
578                  (decoded (base64-decode-string challenge))
579                  (hash (rfc2104-hash 'md5 64 16 passwd decoded))
580                  (response (concat (smtpmail-cred-user cred) " " hash))
581                  ;; Osamu Yamane <yamane@green.ocn.ne.jp>:
582                  ;; SMTP auth fails because the SMTP server identifies
583                  ;; only the first part of the string (delimited by
584                  ;; new line characters) as a response from the
585                  ;; client, and the rest as distinct commands.
586
587                  ;; In my case, the response string is 80 characters
588                  ;; long.  Without the no-line-break option for
589                  ;; base64-encode-sting, only the first 76 characters
590                  ;; are taken as a response to the server, and the
591                  ;; authentication fails.
592                  (encoded (base64-encode-string response t)))
593             (smtpmail-send-command process (format "%s" encoded))
594             (if (or (null (car (setq ret (smtpmail-read-response process))))
595                     (not (integerp (car ret)))
596                     (>= (car ret) 400))
597                 (throw 'done nil)))))
598        ((eq mech 'login)
599         (smtpmail-send-command process "AUTH LOGIN")
600         (if (or (null (car (setq ret (smtpmail-read-response process))))
601                 (not (integerp (car ret)))
602                 (>= (car ret) 400))
603             (throw 'done nil))
604         (smtpmail-send-command
605          process (base64-encode-string (smtpmail-cred-user cred) t))
606         (if (or (null (car (setq ret (smtpmail-read-response process))))
607                 (not (integerp (car ret)))
608                 (>= (car ret) 400))
609             (throw 'done nil))
610         (smtpmail-send-command process (base64-encode-string passwd t))
611         (if (or (null (car (setq ret (smtpmail-read-response process))))
612                 (not (integerp (car ret)))
613                 (>= (car ret) 400))
614             (throw 'done nil)))
615        ((eq mech 'plain)
616         ;; We used to send an empty initial request, and wait for an
617         ;; empty response, and then send the password, but this
618         ;; violate a SHOULD in RFC 2222 paragraph 5.1.  Note that this
619         ;; is not sent if the server did not advertise AUTH PLAIN in
620         ;; the EHLO response.  See RFC 2554 for more info.
621         (smtpmail-send-command process
622                                (concat "AUTH PLAIN "
623                                        (base64-encode-string
624                                         (concat "\0"
625                                                 (smtpmail-cred-user cred)
626                                                 "\0"
627                                                 passwd) t)))
628         (if (or (null (car (setq ret (smtpmail-read-response process))))
629                 (not (integerp (car ret)))
630                 (not (equal (car ret) 235)))
631             (throw 'done nil)))
632
633        (t
634         (error "Mechanism %s not implemented" mech)))
635       ;; Remember the password.
636       (when (and (not (stringp smtpmail-auth-credentials))
637                  (null (smtpmail-cred-passwd cred)))
638         (setcar (cdr (cdr (cdr cred))) passwd)))))
639
640 (defun smtpmail-via-smtp (recipient smtpmail-text-buffer)
641   (let ((process nil)
642         (host (or smtpmail-smtp-server
643                   (error "`smtpmail-smtp-server' not defined")))
644         (port smtpmail-smtp-service)
645         ;; smtpmail-mail-address should be set to the appropriate
646         ;; buffer-local value by the caller, but in case not:
647         (envelope-from (or smtpmail-mail-address
648                            (and mail-specify-envelope-from
649                                 (mail-envelope-from))
650                            user-mail-address))
651         response-code
652         greeting
653         process-buffer
654         (supported-extensions '()))
655     (unwind-protect
656         (catch 'done
657           ;; get or create the trace buffer
658           (setq process-buffer
659                 (get-buffer-create (format "*trace of SMTP session to %s*" host)))
660
661           ;; clear the trace buffer of old output
662           (with-current-buffer process-buffer
663             (setq buffer-undo-list t)
664             (erase-buffer))
665
666           ;; open the connection to the server
667           (setq process (smtpmail-open-stream process-buffer host port))
668           (and (null process) (throw 'done nil))
669
670           ;; set the send-filter
671           (set-process-filter process 'smtpmail-process-filter)
672
673           (with-current-buffer process-buffer
674             (set-buffer-process-coding-system 'raw-text-unix 'raw-text-unix)
675             (make-local-variable 'smtpmail-read-point)
676             (setq smtpmail-read-point (point-min))
677
678
679             (if (or (null (car (setq greeting (smtpmail-read-response process))))
680                     (not (integerp (car greeting)))
681                     (>= (car greeting) 400))
682                 (throw 'done nil)
683               )
684
685             (let ((do-ehlo t)
686                   (do-starttls t))
687               (while do-ehlo
688             ;; EHLO
689             (smtpmail-send-command process (format "EHLO %s" (smtpmail-fqdn)))
690
691             (if (or (null (car (setq response-code
692                                      (smtpmail-read-response process))))
693                     (not (integerp (car response-code)))
694                     (>= (car response-code) 400))
695                 (progn
696                   ;; HELO
697                   (smtpmail-send-command
698                    process (format "HELO %s" (smtpmail-fqdn)))
699
700                   (if (or (null (car (setq response-code
701                                            (smtpmail-read-response process))))
702                           (not (integerp (car response-code)))
703                           (>= (car response-code) 400))
704                       (throw 'done nil)))
705               (dolist (line (cdr (cdr response-code)))
706                 (let ((name (mapcar (lambda (s) (intern (downcase s)))
707                                     (split-string (substring line 4) "[ ]"))))
708                   (and (eq (length name) 1)
709                        (setq name (car name)))
710                     (and name
711                        (cond ((memq (if (consp name) (car name) name)
712                                     '(verb xvrb 8bitmime onex xone
713                                                   expn size dsn etrn
714                                       enhancedstatuscodes
715                                       help xusr
716                                       auth=login auth starttls))
717                                 (setq supported-extensions
718                                       (cons name supported-extensions)))
719                                (smtpmail-warn-about-unknown-extensions
720                               (message "Unknown extension %s" name)))))))
721
722             (if (and do-starttls
723                      (smtpmail-find-credentials smtpmail-starttls-credentials host port)
724                      (member 'starttls supported-extensions)
725                      (numberp (process-id process)))
726                 (progn
727                   (smtpmail-send-command process (format "STARTTLS"))
728                   (if (or (null (car (setq response-code (smtpmail-read-response process))))
729                           (not (integerp (car response-code)))
730                           (>= (car response-code) 400))
731                       (throw 'done nil))
732                   (starttls-negotiate process)
733                   (setq do-starttls nil))
734               (setq do-ehlo nil))))
735
736             (smtpmail-try-auth-methods process supported-extensions host port)
737
738             (if (or (member 'onex supported-extensions)
739                     (member 'xone supported-extensions))
740                 (progn
741                   (smtpmail-send-command process (format "ONEX"))
742                   (if (or (null (car (setq response-code (smtpmail-read-response process))))
743                           (not (integerp (car response-code)))
744                           (>= (car response-code) 400))
745                       (throw 'done nil))))
746
747             (if (and smtpmail-debug-verb
748                      (or (member 'verb supported-extensions)
749                          (member 'xvrb supported-extensions)))
750                 (progn
751                   (smtpmail-send-command process (format "VERB"))
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             (if (member 'xusr supported-extensions)
758                 (progn
759                   (smtpmail-send-command process (format "XUSR"))
760                   (if (or (null (car (setq response-code (smtpmail-read-response process))))
761                           (not (integerp (car response-code)))
762                           (>= (car response-code) 400))
763                       (throw 'done nil))))
764
765             ;; MAIL FROM:<sender>
766             (let ((size-part
767                    (if (or (member 'size supported-extensions)
768                            (assoc 'size supported-extensions))
769                        (format " SIZE=%d"
770                                (with-current-buffer smtpmail-text-buffer
771                                  ;; size estimate:
772                                  (+ (- (point-max) (point-min))
773                                     ;; Add one byte for each change-of-line
774                                     ;; because of CR-LF representation:
775                                     (count-lines (point-min) (point-max)))))
776                      ""))
777                   (body-part
778                    (if (member '8bitmime supported-extensions)
779                        ;; FIXME:
780                        ;; Code should be added here that transforms
781                        ;; the contents of the message buffer into
782                        ;; something the receiving SMTP can handle.
783                        ;; For a receiver that supports 8BITMIME, this
784                        ;; may mean converting BINARY to BASE64, or
785                        ;; adding Content-Transfer-Encoding and the
786                        ;; other MIME headers.  The code should also
787                        ;; return an indication of what encoding the
788                        ;; message buffer is now, i.e. ASCII or
789                        ;; 8BITMIME.
790                        (if nil
791                            " BODY=8BITMIME"
792                          "")
793                      "")))
794 ;             (smtpmail-send-command process (format "MAIL FROM:%s@%s" (user-login-name) (smtpmail-fqdn)))
795               (smtpmail-send-command process (format "MAIL FROM:<%s>%s%s"
796                                                      envelope-from
797                                                      size-part
798                                                      body-part))
799
800               (if (or (null (car (setq response-code (smtpmail-read-response process))))
801                       (not (integerp (car response-code)))
802                       (>= (car response-code) 400))
803                   (throw 'done nil)
804                 ))
805
806             ;; RCPT TO:<recipient>
807             (let ((n 0))
808               (while (not (null (nth n recipient)))
809                 (smtpmail-send-command process (format "RCPT TO:<%s>" (smtpmail-maybe-append-domain (nth n recipient))))
810                 (setq n (1+ n))
811
812                 (setq response-code (smtpmail-read-response process))
813                 (if (or (null (car response-code))
814                         (not (integerp (car response-code)))
815                         (>= (car response-code) 400))
816                     (throw 'done nil)
817                   )
818                 ))
819
820             ;; DATA
821             (smtpmail-send-command process "DATA")
822
823             (if (or (null (car (setq response-code (smtpmail-read-response process))))
824                     (not (integerp (car response-code)))
825                     (>= (car response-code) 400))
826                 (throw 'done nil)
827               )
828
829             ;; Mail contents
830             (smtpmail-send-data process smtpmail-text-buffer)
831
832             ;;DATA end "."
833             (smtpmail-send-command process ".")
834
835             (if (or (null (car (setq response-code (smtpmail-read-response process))))
836                     (not (integerp (car response-code)))
837                     (>= (car response-code) 400))
838                 (throw 'done nil)
839               )
840
841             ;;QUIT
842 ;           (smtpmail-send-command process "QUIT")
843 ;           (and (null (car (smtpmail-read-response process)))
844 ;                (throw 'done nil))
845             t ))
846       (if process
847           (with-current-buffer (process-buffer process)
848             (smtpmail-send-command process "QUIT")
849             (smtpmail-read-response process)
850
851 ;           (if (or (null (car (setq response-code (smtpmail-read-response process))))
852 ;                   (not (integerp (car response-code)))
853 ;                   (>= (car response-code) 400))
854 ;               (throw 'done nil)
855 ;             )
856             (delete-process process)
857             (unless smtpmail-debug-info
858               (kill-buffer process-buffer)))))))
859
860
861 (defun smtpmail-process-filter (process output)
862   (with-current-buffer (process-buffer process)
863     (goto-char (point-max))
864     (insert output)))
865
866 (defun smtpmail-read-response (process)
867   (let ((case-fold-search nil)
868         (response-strings nil)
869         (response-continue t)
870         (return-value '(nil ()))
871         match-end)
872     (catch 'done
873       (while response-continue
874         (goto-char smtpmail-read-point)
875         (while (not (search-forward "\r\n" nil t))
876           (unless (memq (process-status process) '(open run))
877             (throw 'done nil))
878           (accept-process-output process)
879           (goto-char smtpmail-read-point))
880
881         (setq match-end (point))
882         (setq response-strings
883               (cons (buffer-substring smtpmail-read-point (- match-end 2))
884                     response-strings))
885
886         (goto-char smtpmail-read-point)
887         (if (looking-at "[0-9]+ ")
888             (let ((begin (match-beginning 0))
889                   (end (match-end 0)))
890               (if smtpmail-debug-info
891                   (message "%s" (car response-strings)))
892
893               (setq smtpmail-read-point match-end)
894
895               ;; ignore lines that start with "0"
896               (if (looking-at "0[0-9]+ ")
897                   nil
898                 (setq response-continue nil)
899                 (setq return-value
900                       (cons (string-to-number
901                              (buffer-substring begin end))
902                             (nreverse response-strings)))))
903
904           (if (looking-at "[0-9]+-")
905               (progn (if smtpmail-debug-info
906                          (message "%s" (car response-strings)))
907                      (setq smtpmail-read-point match-end)
908                      (setq response-continue t))
909             (progn
910               (setq smtpmail-read-point match-end)
911               (setq response-continue nil)
912               (setq return-value
913                     (cons nil (nreverse response-strings)))))))
914       (setq smtpmail-read-point match-end))
915     return-value))
916
917
918 (defun smtpmail-send-command (process command)
919   (goto-char (point-max))
920   (if (= (aref command 0) ?P)
921       (insert "PASS <omitted>\r\n")
922     (insert command "\r\n"))
923   (setq smtpmail-read-point (point))
924   (process-send-string process command)
925   (process-send-string process "\r\n"))
926
927 (defun smtpmail-send-data-1 (process data)
928   (goto-char (point-max))
929
930   (if (and (multibyte-string-p data)
931            smtpmail-code-conv-from)
932       (setq data (string-as-multibyte
933                   (encode-coding-string data smtpmail-code-conv-from))))
934
935   (if smtpmail-debug-info
936       (insert data "\r\n"))
937
938   (setq smtpmail-read-point (point))
939   ;; Escape "." at start of a line
940   (if (eq (string-to-char data) ?.)
941       (process-send-string process "."))
942   (process-send-string process data)
943   (process-send-string process "\r\n")
944   )
945
946 (defun smtpmail-send-data (process buffer)
947   (let ((data-continue t) sending-data)
948     (with-current-buffer buffer
949       (goto-char (point-min)))
950     (while data-continue
951       (with-current-buffer buffer
952         (setq sending-data (buffer-substring (point-at-bol) (point-at-eol)))
953         (end-of-line 2)
954         (setq data-continue (not (eobp))))
955       (smtpmail-send-data-1 process sending-data))))
956
957 (defun smtpmail-deduce-address-list (smtpmail-text-buffer header-start header-end)
958   "Get address list suitable for smtp RCPT TO: <address>."
959   (unwind-protect
960       (with-current-buffer smtpmail-address-buffer
961         (erase-buffer)
962         (let
963             ((case-fold-search t)
964              (simple-address-list "")
965              this-line
966              this-line-end
967              addr-regexp)
968           (insert-buffer-substring smtpmail-text-buffer header-start header-end)
969           (goto-char (point-min))
970           ;; RESENT-* fields should stop processing of regular fields.
971           (save-excursion
972             (setq addr-regexp
973                   (if (re-search-forward "^Resent-\\(to\\|cc\\|bcc\\):"
974                                          header-end t)
975                       "^Resent-\\(to\\|cc\\|bcc\\):"
976                     "^\\(To:\\|Cc:\\|Bcc:\\)")))
977
978           (while (re-search-forward addr-regexp header-end t)
979             (replace-match "")
980             (setq this-line (match-beginning 0))
981             (forward-line 1)
982             ;; get any continuation lines
983             (while (and (looking-at "^[ \t]+") (< (point) header-end))
984               (forward-line 1))
985             (setq this-line-end (point-marker))
986             (setq simple-address-list
987                   (concat simple-address-list " "
988                           (mail-strip-quoted-names (buffer-substring this-line this-line-end))))
989             )
990           (erase-buffer)
991           (insert " " simple-address-list "\n")
992           (subst-char-in-region (point-min) (point-max) 10 ?  t);; newline --> blank
993           (subst-char-in-region (point-min) (point-max) ?, ?  t);; comma   --> blank
994           (subst-char-in-region (point-min) (point-max)  9 ?  t);; tab     --> blank
995
996           (goto-char (point-min))
997           ;; tidyness in case hook is not robust when it looks at this
998           (while (re-search-forward "[ \t]+" header-end t) (replace-match " "))
999
1000           (goto-char (point-min))
1001           (let (recipient-address-list)
1002             (while (re-search-forward " \\([^ ]+\\) " (point-max) t)
1003               (backward-char 1)
1004               (setq recipient-address-list (cons (buffer-substring (match-beginning 1) (match-end 1))
1005                                                  recipient-address-list))
1006               )
1007             (setq smtpmail-recipient-address-list recipient-address-list))
1008
1009           )
1010         )
1011     )
1012   )
1013
1014
1015 (defun smtpmail-do-bcc (header-end)
1016   "Delete [Resent-]BCC: and their continuation lines from the header area.
1017 There may be multiple BCC: lines, and each may have arbitrarily
1018 many continuation lines."
1019   (let ((case-fold-search t))
1020     (save-excursion
1021       (goto-char (point-min))
1022       ;; iterate over all BCC: lines
1023       (while (re-search-forward "^\\(RESENT-\\)?BCC:" header-end t)
1024         (delete-region (match-beginning 0)
1025                        (progn (forward-line 1) (point)))
1026         ;; get rid of any continuation lines
1027         (while (and (looking-at "^[ \t].*\n") (< (point) header-end))
1028           (replace-match ""))))))
1029
1030
1031 (provide 'smtpmail)
1032
1033 ;;; arch-tag: a76992df-6d71-43b7-9e72-4bacc6c05466
1034 ;;; smtpmail.el ends here