(spam-report-gmane-max-requests): New constant.
[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  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
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 (starttls-any-program-available)))
517         ;; The normal case.
518         (open-network-stream "SMTP" process-buffer host port)
519       (let* ((cred-key (smtpmail-cred-key cred))
520              (cred-cert (smtpmail-cred-cert cred))
521              (starttls-extra-args
522               (append
523                starttls-extra-args
524                (when (and (stringp cred-key) (stringp cred-cert)
525                           (file-regular-p
526                            (setq cred-key (expand-file-name cred-key)))
527                           (file-regular-p
528                            (setq cred-cert (expand-file-name cred-cert))))
529                  (list "--key-file" cred-key "--cert-file" cred-cert))))
530              (starttls-extra-arguments
531               (append
532                starttls-extra-arguments
533                (when (and (stringp cred-key) (stringp cred-cert)
534                           (file-regular-p
535                            (setq cred-key (expand-file-name cred-key)))
536                           (file-regular-p
537                            (setq cred-cert (expand-file-name cred-cert))))
538                  (list "--x509keyfile" cred-key "--x509certfile" cred-cert)))))
539         (starttls-open-stream "SMTP" process-buffer host port)))))
540
541 (defun smtpmail-try-auth-methods (process supported-extensions host port)
542   (let* ((mechs (cdr-safe (assoc 'auth supported-extensions)))
543          (mech (car (smtpmail-intersection smtpmail-auth-supported mechs)))
544          (auth-user (auth-source-user-or-password
545                      "login" host (or port "smtp")))
546          (auth-pass (auth-source-user-or-password
547                      "password" host (or port "smtp")))
548          (cred (if (and auth-user auth-pass) ; try user-auth-* before netrc-*
549                    (list host port auth-user auth-pass)
550                  ;; else, if auth-source didn't return them...
551                  (if (stringp smtpmail-auth-credentials)
552                      (let* ((netrc (netrc-parse smtpmail-auth-credentials))
553                             (port-name (format "%s" (or port "smtp")))
554                             (hostentry (netrc-machine netrc host port-name
555                                                       port-name)))
556                        (when hostentry
557                          (list host port
558                                (netrc-get hostentry "login")
559                                (netrc-get hostentry "password"))))
560                    ;; else, try smtpmail-find-credentials since
561                    ;; smtpmail-auth-credentials is not a string
562                    (smtpmail-find-credentials
563                     smtpmail-auth-credentials host port))))
564          (prompt (when cred (format "SMTP password for %s:%s: "
565                                     (smtpmail-cred-server cred)
566                                     (smtpmail-cred-port cred))))
567          (passwd (when cred
568                    (or (smtpmail-cred-passwd cred)
569                        (read-passwd
570                         (format "SMTP password for %s:%s: "
571                                 (smtpmail-cred-server cred)
572                                 (smtpmail-cred-port cred))))))
573          ret)
574     (when (and cred mech)
575       (cond
576        ((eq mech 'cram-md5)
577         (smtpmail-send-command process (upcase (format "AUTH %s" mech)))
578         (if (or (null (car (setq ret (smtpmail-read-response process))))
579                 (not (integerp (car ret)))
580                 (>= (car ret) 400))
581             (throw 'done nil))
582         (when (eq (car ret) 334)
583           (let* ((challenge (substring (cadr ret) 4))
584                  (decoded (base64-decode-string challenge))
585                  (hash (rfc2104-hash 'md5 64 16 passwd decoded))
586                  (response (concat (smtpmail-cred-user cred) " " hash))
587                  ;; Osamu Yamane <yamane@green.ocn.ne.jp>:
588                  ;; SMTP auth fails because the SMTP server identifies
589                  ;; only the first part of the string (delimited by
590                  ;; new line characters) as a response from the
591                  ;; client, and the rest as distinct commands.
592
593                  ;; In my case, the response string is 80 characters
594                  ;; long.  Without the no-line-break option for
595                  ;; base64-encode-sting, only the first 76 characters
596                  ;; are taken as a response to the server, and the
597                  ;; authentication fails.
598                  (encoded (base64-encode-string response t)))
599             (smtpmail-send-command process (format "%s" encoded))
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        ((eq mech 'login)
605         (smtpmail-send-command process "AUTH LOGIN")
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
611          process (base64-encode-string (smtpmail-cred-user cred) t))
612         (if (or (null (car (setq ret (smtpmail-read-response process))))
613                 (not (integerp (car ret)))
614                 (>= (car ret) 400))
615             (throw 'done nil))
616         (smtpmail-send-command process (base64-encode-string passwd t))
617         (if (or (null (car (setq ret (smtpmail-read-response process))))
618                 (not (integerp (car ret)))
619                 (>= (car ret) 400))
620             (throw 'done nil)))
621        ((eq mech 'plain)
622         ;; We used to send an empty initial request, and wait for an
623         ;; empty response, and then send the password, but this
624         ;; violate a SHOULD in RFC 2222 paragraph 5.1.  Note that this
625         ;; is not sent if the server did not advertise AUTH PLAIN in
626         ;; the EHLO response.  See RFC 2554 for more info.
627         (smtpmail-send-command process
628                                (concat "AUTH PLAIN "
629                                        (base64-encode-string
630                                         (concat "\0"
631                                                 (smtpmail-cred-user cred)
632                                                 "\0"
633                                                 passwd) t)))
634         (if (or (null (car (setq ret (smtpmail-read-response process))))
635                 (not (integerp (car ret)))
636                 (not (equal (car ret) 235)))
637             (throw 'done nil)))
638
639        (t
640         (error "Mechanism %s not implemented" mech)))
641       ;; Remember the password.
642       (when (and (not (stringp smtpmail-auth-credentials))
643                  (null (smtpmail-cred-passwd cred)))
644         (setcar (cdr (cdr (cdr cred))) passwd)))))
645
646 (defun smtpmail-via-smtp (recipient smtpmail-text-buffer)
647   (let ((process nil)
648         (host (or smtpmail-smtp-server
649                   (error "`smtpmail-smtp-server' not defined")))
650         (port smtpmail-smtp-service)
651         ;; smtpmail-mail-address should be set to the appropriate
652         ;; buffer-local value by the caller, but in case not:
653         (envelope-from (or smtpmail-mail-address
654                            (and mail-specify-envelope-from
655                                 (mail-envelope-from))
656                            user-mail-address))
657         response-code
658         greeting
659         process-buffer
660         (supported-extensions '()))
661     (unwind-protect
662         (catch 'done
663           ;; get or create the trace buffer
664           (setq process-buffer
665                 (get-buffer-create (format "*trace of SMTP session to %s*" host)))
666
667           ;; clear the trace buffer of old output
668           (with-current-buffer process-buffer
669             (setq buffer-undo-list t)
670             (erase-buffer))
671
672           ;; open the connection to the server
673           (setq process (smtpmail-open-stream process-buffer host port))
674           (and (null process) (throw 'done nil))
675
676           ;; set the send-filter
677           (set-process-filter process 'smtpmail-process-filter)
678
679           (with-current-buffer process-buffer
680             (set-buffer-process-coding-system 'raw-text-unix 'raw-text-unix)
681             (make-local-variable 'smtpmail-read-point)
682             (setq smtpmail-read-point (point-min))
683
684
685             (if (or (null (car (setq greeting (smtpmail-read-response process))))
686                     (not (integerp (car greeting)))
687                     (>= (car greeting) 400))
688                 (throw 'done nil)
689               )
690
691             (let ((do-ehlo t)
692                   (do-starttls t))
693               (while do-ehlo
694             ;; EHLO
695             (smtpmail-send-command process (format "EHLO %s" (smtpmail-fqdn)))
696
697             (if (or (null (car (setq response-code
698                                      (smtpmail-read-response process))))
699                     (not (integerp (car response-code)))
700                     (>= (car response-code) 400))
701                 (progn
702                   ;; HELO
703                   (smtpmail-send-command
704                    process (format "HELO %s" (smtpmail-fqdn)))
705
706                   (if (or (null (car (setq response-code
707                                            (smtpmail-read-response process))))
708                           (not (integerp (car response-code)))
709                           (>= (car response-code) 400))
710                       (throw 'done nil)))
711               (dolist (line (cdr (cdr response-code)))
712                 (let ((name (mapcar (lambda (s) (intern (downcase s)))
713                                     (split-string (substring line 4) "[ ]"))))
714                   (and (eq (length name) 1)
715                        (setq name (car name)))
716                     (and name
717                        (cond ((memq (if (consp name) (car name) name)
718                                     '(verb xvrb 8bitmime onex xone
719                                                   expn size dsn etrn
720                                       enhancedstatuscodes
721                                       help xusr
722                                       auth=login auth starttls))
723                                 (setq supported-extensions
724                                       (cons name supported-extensions)))
725                                (smtpmail-warn-about-unknown-extensions
726                               (message "Unknown extension %s" name)))))))
727
728             (if (and do-starttls
729                      (smtpmail-find-credentials smtpmail-starttls-credentials host port)
730                      (member 'starttls supported-extensions)
731                      (numberp (process-id process)))
732                 (progn
733                   (smtpmail-send-command process (format "STARTTLS"))
734                   (if (or (null (car (setq response-code (smtpmail-read-response process))))
735                           (not (integerp (car response-code)))
736                           (>= (car response-code) 400))
737                       (throw 'done nil))
738                   (starttls-negotiate process)
739                   (setq do-starttls nil))
740               (setq do-ehlo nil))))
741
742             (smtpmail-try-auth-methods process supported-extensions host port)
743
744             (if (or (member 'onex supported-extensions)
745                     (member 'xone supported-extensions))
746                 (progn
747                   (smtpmail-send-command process (format "ONEX"))
748                   (if (or (null (car (setq response-code (smtpmail-read-response process))))
749                           (not (integerp (car response-code)))
750                           (>= (car response-code) 400))
751                       (throw 'done nil))))
752
753             (if (and smtpmail-debug-verb
754                      (or (member 'verb supported-extensions)
755                          (member 'xvrb supported-extensions)))
756                 (progn
757                   (smtpmail-send-command process (format "VERB"))
758                   (if (or (null (car (setq response-code (smtpmail-read-response process))))
759                           (not (integerp (car response-code)))
760                           (>= (car response-code) 400))
761                       (throw 'done nil))))
762
763             (if (member 'xusr supported-extensions)
764                 (progn
765                   (smtpmail-send-command process (format "XUSR"))
766                   (if (or (null (car (setq response-code (smtpmail-read-response process))))
767                           (not (integerp (car response-code)))
768                           (>= (car response-code) 400))
769                       (throw 'done nil))))
770
771             ;; MAIL FROM:<sender>
772             (let ((size-part
773                    (if (or (member 'size supported-extensions)
774                            (assoc 'size supported-extensions))
775                        (format " SIZE=%d"
776                                (with-current-buffer smtpmail-text-buffer
777                                  ;; size estimate:
778                                  (+ (- (point-max) (point-min))
779                                     ;; Add one byte for each change-of-line
780                                     ;; because of CR-LF representation:
781                                     (count-lines (point-min) (point-max)))))
782                      ""))
783                   (body-part
784                    (if (member '8bitmime supported-extensions)
785                        ;; FIXME:
786                        ;; Code should be added here that transforms
787                        ;; the contents of the message buffer into
788                        ;; something the receiving SMTP can handle.
789                        ;; For a receiver that supports 8BITMIME, this
790                        ;; may mean converting BINARY to BASE64, or
791                        ;; adding Content-Transfer-Encoding and the
792                        ;; other MIME headers.  The code should also
793                        ;; return an indication of what encoding the
794                        ;; message buffer is now, i.e. ASCII or
795                        ;; 8BITMIME.
796                        (if nil
797                            " BODY=8BITMIME"
798                          "")
799                      "")))
800 ;             (smtpmail-send-command process (format "MAIL FROM:%s@%s" (user-login-name) (smtpmail-fqdn)))
801               (smtpmail-send-command process (format "MAIL FROM:<%s>%s%s"
802                                                      envelope-from
803                                                      size-part
804                                                      body-part))
805
806               (if (or (null (car (setq response-code (smtpmail-read-response process))))
807                       (not (integerp (car response-code)))
808                       (>= (car response-code) 400))
809                   (throw 'done nil)
810                 ))
811
812             ;; RCPT TO:<recipient>
813             (let ((n 0))
814               (while (not (null (nth n recipient)))
815                 (smtpmail-send-command process (format "RCPT TO:<%s>" (smtpmail-maybe-append-domain (nth n recipient))))
816                 (setq n (1+ n))
817
818                 (setq response-code (smtpmail-read-response process))
819                 (if (or (null (car response-code))
820                         (not (integerp (car response-code)))
821                         (>= (car response-code) 400))
822                     (throw 'done nil)
823                   )
824                 ))
825
826             ;; DATA
827             (smtpmail-send-command process "DATA")
828
829             (if (or (null (car (setq response-code (smtpmail-read-response process))))
830                     (not (integerp (car response-code)))
831                     (>= (car response-code) 400))
832                 (throw 'done nil)
833               )
834
835             ;; Mail contents
836             (smtpmail-send-data process smtpmail-text-buffer)
837
838             ;;DATA end "."
839             (smtpmail-send-command process ".")
840
841             (if (or (null (car (setq response-code (smtpmail-read-response process))))
842                     (not (integerp (car response-code)))
843                     (>= (car response-code) 400))
844                 (throw 'done nil)
845               )
846
847             ;;QUIT
848 ;           (smtpmail-send-command process "QUIT")
849 ;           (and (null (car (smtpmail-read-response process)))
850 ;                (throw 'done nil))
851             t ))
852       (if process
853           (with-current-buffer (process-buffer process)
854             (smtpmail-send-command process "QUIT")
855             (smtpmail-read-response process)
856
857 ;           (if (or (null (car (setq response-code (smtpmail-read-response process))))
858 ;                   (not (integerp (car response-code)))
859 ;                   (>= (car response-code) 400))
860 ;               (throw 'done nil)
861 ;             )
862             (delete-process process)
863             (unless smtpmail-debug-info
864               (kill-buffer process-buffer)))))))
865
866
867 (defun smtpmail-process-filter (process output)
868   (with-current-buffer (process-buffer process)
869     (goto-char (point-max))
870     (insert output)))
871
872 (defun smtpmail-read-response (process)
873   (let ((case-fold-search nil)
874         (response-strings nil)
875         (response-continue t)
876         (return-value '(nil ()))
877         match-end)
878     (catch 'done
879       (while response-continue
880         (goto-char smtpmail-read-point)
881         (while (not (search-forward "\r\n" nil t))
882           (unless (memq (process-status process) '(open run))
883             (throw 'done nil))
884           (accept-process-output process)
885           (goto-char smtpmail-read-point))
886
887         (setq match-end (point))
888         (setq response-strings
889               (cons (buffer-substring smtpmail-read-point (- match-end 2))
890                     response-strings))
891
892         (goto-char smtpmail-read-point)
893         (if (looking-at "[0-9]+ ")
894             (let ((begin (match-beginning 0))
895                   (end (match-end 0)))
896               (if smtpmail-debug-info
897                   (message "%s" (car response-strings)))
898
899               (setq smtpmail-read-point match-end)
900
901               ;; ignore lines that start with "0"
902               (if (looking-at "0[0-9]+ ")
903                   nil
904                 (setq response-continue nil)
905                 (setq return-value
906                       (cons (string-to-number
907                              (buffer-substring begin end))
908                             (nreverse response-strings)))))
909
910           (if (looking-at "[0-9]+-")
911               (progn (if smtpmail-debug-info
912                          (message "%s" (car response-strings)))
913                      (setq smtpmail-read-point match-end)
914                      (setq response-continue t))
915             (progn
916               (setq smtpmail-read-point match-end)
917               (setq response-continue nil)
918               (setq return-value
919                     (cons nil (nreverse response-strings)))))))
920       (setq smtpmail-read-point match-end))
921     return-value))
922
923
924 (defun smtpmail-send-command (process command)
925   (goto-char (point-max))
926   (if (= (aref command 0) ?P)
927       (insert "PASS <omitted>\r\n")
928     (insert command "\r\n"))
929   (setq smtpmail-read-point (point))
930   (process-send-string process command)
931   (process-send-string process "\r\n"))
932
933 (defun smtpmail-send-data-1 (process data)
934   (goto-char (point-max))
935
936   (if (and (multibyte-string-p data)
937            smtpmail-code-conv-from)
938       (setq data (string-as-multibyte
939                   (encode-coding-string data smtpmail-code-conv-from))))
940
941   (if smtpmail-debug-info
942       (insert data "\r\n"))
943
944   (setq smtpmail-read-point (point))
945   ;; Escape "." at start of a line
946   (if (eq (string-to-char data) ?.)
947       (process-send-string process "."))
948   (process-send-string process data)
949   (process-send-string process "\r\n")
950   )
951
952 (defun smtpmail-send-data (process buffer)
953   (let ((data-continue t) sending-data)
954     (with-current-buffer buffer
955       (goto-char (point-min)))
956     (while data-continue
957       (with-current-buffer buffer
958         (setq sending-data (buffer-substring (point-at-bol) (point-at-eol)))
959         (end-of-line 2)
960         (setq data-continue (not (eobp))))
961       (smtpmail-send-data-1 process sending-data))))
962
963 (defun smtpmail-deduce-address-list (smtpmail-text-buffer header-start header-end)
964   "Get address list suitable for smtp RCPT TO: <address>."
965   (unwind-protect
966       (with-current-buffer smtpmail-address-buffer
967         (erase-buffer)
968         (let
969             ((case-fold-search t)
970              (simple-address-list "")
971              this-line
972              this-line-end
973              addr-regexp)
974           (insert-buffer-substring smtpmail-text-buffer header-start header-end)
975           (goto-char (point-min))
976           ;; RESENT-* fields should stop processing of regular fields.
977           (save-excursion
978             (setq addr-regexp
979                   (if (re-search-forward "^Resent-\\(to\\|cc\\|bcc\\):"
980                                          header-end t)
981                       "^Resent-\\(to\\|cc\\|bcc\\):"
982                     "^\\(To:\\|Cc:\\|Bcc:\\)")))
983
984           (while (re-search-forward addr-regexp header-end t)
985             (replace-match "")
986             (setq this-line (match-beginning 0))
987             (forward-line 1)
988             ;; get any continuation lines
989             (while (and (looking-at "^[ \t]+") (< (point) header-end))
990               (forward-line 1))
991             (setq this-line-end (point-marker))
992             (setq simple-address-list
993                   (concat simple-address-list " "
994                           (mail-strip-quoted-names (buffer-substring this-line this-line-end))))
995             )
996           (erase-buffer)
997           (insert " " simple-address-list "\n")
998           (subst-char-in-region (point-min) (point-max) 10 ?  t);; newline --> blank
999           (subst-char-in-region (point-min) (point-max) ?, ?  t);; comma   --> blank
1000           (subst-char-in-region (point-min) (point-max)  9 ?  t);; tab     --> blank
1001
1002           (goto-char (point-min))
1003           ;; tidyness in case hook is not robust when it looks at this
1004           (while (re-search-forward "[ \t]+" header-end t) (replace-match " "))
1005
1006           (goto-char (point-min))
1007           (let (recipient-address-list)
1008             (while (re-search-forward " \\([^ ]+\\) " (point-max) t)
1009               (backward-char 1)
1010               (setq recipient-address-list (cons (buffer-substring (match-beginning 1) (match-end 1))
1011                                                  recipient-address-list))
1012               )
1013             (setq smtpmail-recipient-address-list recipient-address-list))
1014
1015           )
1016         )
1017     )
1018   )
1019
1020
1021 (defun smtpmail-do-bcc (header-end)
1022   "Delete [Resent-]BCC: and their continuation lines from the header area.
1023 There may be multiple BCC: lines, and each may have arbitrarily
1024 many continuation lines."
1025   (let ((case-fold-search t))
1026     (save-excursion
1027       (goto-char (point-min))
1028       ;; iterate over all BCC: lines
1029       (while (re-search-forward "^\\(RESENT-\\)?BCC:" header-end t)
1030         (delete-region (match-beginning 0)
1031                        (progn (forward-line 1) (point)))
1032         ;; get rid of any continuation lines
1033         (while (and (looking-at "^[ \t].*\n") (< (point) header-end))
1034           (replace-match ""))))))
1035
1036
1037 (provide 'smtpmail)
1038
1039 ;; arch-tag: a76992df-6d71-43b7-9e72-4bacc6c05466
1040 ;;; smtpmail.el ends here