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