Update copyright notices for 2013.
[bpt/emacs.git] / lisp / mail / smtpmail.el
CommitLineData
092af6d8 1;;; smtpmail.el --- simple SMTP protocol (RFC 821) for sending mail
24975917 2
ab422c4d 3;; Copyright (C) 1995-1996, 2001-2013 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 88(defcustom smtpmail-smtp-user nil
9f26dc24
GM
89 "User name to use when looking up credentials in the authinfo file.
90If non-nil, only consider credentials for the specified user."
e5f1c99e 91 :version "24.1"
f5e3c598
LMI
92 :type '(choice (const nil) string)
93 :group 'smtpmail)
94
00ed33e7 95(defcustom smtpmail-local-domain nil
0fc1e8fe 96 "Local domain name without a host name.
1429d866 97If the function `system-name' returns the full internet address,
00ed33e7
RS
98don't define this value."
99 :type '(choice (const nil) string)
100 :group 'smtpmail)
101
95f41d9a 102(defcustom smtpmail-stream-type nil
9f26dc24
GM
103 "Type of SMTP connections to use.
104This may be either nil (possibly upgraded to STARTTLS if possible),
105or `starttls' (refuse to send if STARTTLS isn't available), or `plain'
106\(never use STARTTLS), or `ssl' (to use TLS/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))
8ce192e3 203 (let ((from (mail-fetch-field "from")))
4c7e65bf 204 (and from
8ce192e3
LI
205 (cadr (mail-extract-address-components from))))
206 (smtpmail-user-mail-address)))
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 326 ;; buffer to encode outgoing messages on FCC files.
3f018d6d
EZ
327 (let ((coding-system-for-write
328 ;; mbox files must have Unix EOLs.
329 (coding-system-change-eol-conversion
330 smtpmail-code-conv-from 'unix)))
362e23e1 331 (mail-do-fcc delimline)))
24975917 332 (if mail-interactive
21bf0d6c 333 (with-current-buffer errbuf
24975917 334 (erase-buffer))))
b8d747b9
KH
335 ;; Encode the header according to RFC2047.
336 (mail-encode-header (point-min) delimline)
24975917 337 ;;
24975917
RS
338 (setq smtpmail-address-buffer (generate-new-buffer "*smtp-mail*"))
339 (setq smtpmail-recipient-address-list
75da36cc 340 (smtpmail-deduce-address-list tembuf (point-min) delimline))
24975917 341 (kill-buffer smtpmail-address-buffer)
a8ba4429 342
24975917 343 (smtpmail-do-bcc delimline)
75da36cc 344 ;; Send or queue
308bc5d8
RS
345 (if (not smtpmail-queue-mail)
346 (if (not (null smtpmail-recipient-address-list))
95f41d9a
LMI
347 (when (setq result
348 (smtpmail-via-smtp
349 smtpmail-recipient-address-list tembuf))
350 (error "Sending failed: %s" result))
308bc5d8 351 (error "Sending failed; no recipients"))
bf6e31bc
SJ
352 (let* ((file-data
353 (expand-file-name
354 (format "%s_%i"
b2364eaa 355 (format-time-string "%Y-%m-%d_%H:%M:%S")
bf6e31bc
SJ
356 (setq smtpmail-queue-counter
357 (1+ smtpmail-queue-counter)))
358 smtpmail-queue-dir))
359 (file-data (convert-standard-filename file-data))
360 (file-elisp (concat file-data ".el"))
308bc5d8
RS
361 (buffer-data (create-file-buffer file-data))
362 (buffer-elisp (create-file-buffer file-elisp))
363 (buffer-scratch "*queue-mail*"))
2fbc1118
JB
364 (unless (file-exists-p smtpmail-queue-dir)
365 (make-directory smtpmail-queue-dir t))
21bf0d6c 366 (with-current-buffer buffer-data
308bc5d8 367 (erase-buffer)
95e4cc85
EZ
368 (set-buffer-file-coding-system
369 ;; We will be reading the file with no-conversion in
370 ;; smtpmail-send-queued-mail below, so write it out
371 ;; with Unix EOLs.
372 (coding-system-change-eol-conversion
373 (or smtpmail-code-conv-from 'undecided)
374 'unix)
375 nil t)
b0aea09e 376 (insert-buffer-substring tembuf)
308bc5d8
RS
377 (write-file file-data)
378 (set-buffer buffer-elisp)
379 (erase-buffer)
380 (insert (concat
381 "(setq smtpmail-recipient-address-list '"
382 (prin1-to-string smtpmail-recipient-address-list)
a8ba4429 383 ")\n"))
308bc5d8
RS
384 (write-file file-elisp)
385 (set-buffer (generate-new-buffer buffer-scratch))
386 (insert (concat file-data "\n"))
a8ba4429
SS
387 (append-to-file (point-min)
388 (point-max)
0fc1e8fe
GM
389 (expand-file-name smtpmail-queue-index-file
390 smtpmail-queue-dir)))
308bc5d8
RS
391 (kill-buffer buffer-scratch)
392 (kill-buffer buffer-data)
393 (kill-buffer buffer-elisp))))
24975917
RS
394 (kill-buffer tembuf)
395 (if (bufferp errbuf)
396 (kill-buffer errbuf)))))
397
74f39ce9 398;;;###autoload
308bc5d8
RS
399(defun smtpmail-send-queued-mail ()
400 "Send mail that was queued as a result of setting `smtpmail-queue-mail'."
401 (interactive)
7e3fa9f5 402 (with-temp-buffer
75da36cc
RW
403 ;; Get index, get first mail, send it, update index, get second
404 ;; mail, send it, etc...
0fc1e8fe
GM
405 (let ((file-msg "")
406 (qfile (expand-file-name smtpmail-queue-index-file
95f41d9a
LMI
407 smtpmail-queue-dir))
408 result)
0fc1e8fe 409 (insert-file-contents qfile)
88f2c9ad 410 (goto-char (point-min))
308bc5d8 411 (while (not (eobp))
21bf0d6c 412 (setq file-msg (buffer-substring (point) (line-end-position)))
308bc5d8 413 (load file-msg)
19a0baf7
EZ
414 ;; Insert the message literally: it is already encoded as per
415 ;; the MIME headers, and code conversions might guess the
416 ;; encoding wrongly.
7e3fa9f5
EZ
417 (with-temp-buffer
418 (let ((coding-system-for-read 'no-conversion))
419 (insert-file-contents file-msg))
ff981226
GM
420 (let ((smtpmail-mail-address
421 (or (and mail-specify-envelope-from (mail-envelope-from))
422 user-mail-address)))
423 (if (not (null smtpmail-recipient-address-list))
95f41d9a
LMI
424 (when (setq result (smtpmail-via-smtp
425 smtpmail-recipient-address-list
426 (current-buffer)))
427 (error "Sending failed: %s" result))
ff981226 428 (error "Sending failed; no recipients"))))
308bc5d8
RS
429 (delete-file file-msg)
430 (delete-file (concat file-msg ".el"))
95754b9f 431 (delete-region (point-at-bol) (point-at-bol 2)))
0fc1e8fe 432 (write-region (point-min) (point-max) qfile))))
24975917 433
24975917
RS
434(defun smtpmail-fqdn ()
435 (if smtpmail-local-domain
436 (concat (system-name) "." smtpmail-local-domain)
437 (system-name)))
438
9056f1c9
RS
439(defsubst smtpmail-cred-server (cred)
440 (nth 0 cred))
441
442(defsubst smtpmail-cred-port (cred)
443 (nth 1 cred))
444
445(defsubst smtpmail-cred-key (cred)
446 (nth 2 cred))
447
448(defsubst smtpmail-cred-user (cred)
449 (nth 2 cred))
450
451(defsubst smtpmail-cred-cert (cred)
452 (nth 3 cred))
453
454(defsubst smtpmail-cred-passwd (cred)
455 (nth 3 cred))
456
457(defun smtpmail-find-credentials (cred server port)
458 (catch 'done
459 (let ((l cred) el)
460 (while (setq el (pop l))
461 (when (and (equal server (smtpmail-cred-server el))
462 (equal port (smtpmail-cred-port el)))
463 (throw 'done el))))))
464
2b5c7e03
GM
465(defun smtpmail-maybe-append-domain (recipient)
466 (if (or (not smtpmail-sendto-domain)
467 (string-match "@" recipient))
468 recipient
469 (concat recipient "@" smtpmail-sendto-domain)))
470
9056f1c9
RS
471(defun smtpmail-intersection (list1 list2)
472 (let ((result nil))
473 (dolist (el2 list2)
474 (when (memq el2 list1)
475 (push el2 result)))
476 (nreverse result)))
477
95f41d9a
LMI
478(defun smtpmail-command-or-throw (process string &optional code)
479 (let (ret)
480 (smtpmail-send-command process string)
481 (unless (smtpmail-ok-p (setq ret (smtpmail-read-response process))
482 code)
7d36ad46
LMI
483 (throw 'done (format "%s in response to %s"
484 (smtpmail-response-text ret)
485 string)))
95f41d9a
LMI
486 ret))
487
488(defun smtpmail-try-auth-methods (process supported-extensions host port
489 &optional ask-for-password)
97bb1093
LMI
490 (setq port
491 (if port
492 (format "%s" port)
493 "smtp"))
9056f1c9 494 (let* ((mechs (cdr-safe (assoc 'auth supported-extensions)))
9927d250 495 (mech (car (smtpmail-intersection mechs smtpmail-auth-supported)))
95f41d9a 496 (auth-source-creation-prompts
2784c434 497 '((user . "SMTP user name for %h: ")
95f41d9a
LMI
498 (secret . "SMTP password for %u@%h: ")))
499 (auth-info (car
ddb7ffee 500 (auth-source-search
ddb7ffee 501 :host host
97bb1093 502 :port port
f5e3c598 503 :user smtpmail-smtp-user
40098786 504 :max 1
ddb7ffee
LMI
505 :require (and ask-for-password
506 '(:user :secret))
507 :create ask-for-password)))
95f41d9a
LMI
508 (user (plist-get auth-info :user))
509 (password (plist-get auth-info :secret))
510 (save-function (and ask-for-password
511 (plist-get auth-info :save-function)))
9056f1c9 512 ret)
e7f2c178
LMI
513 (when (functionp password)
514 (setq password (funcall password)))
97bb1093
LMI
515 (when (and user
516 (not password))
517 ;; The user has stored the user name, but not the password, so
518 ;; ask for the password, even if we're not forcing that through
519 ;; `ask-for-password'.
520 (setq auth-info
521 (car
522 (auth-source-search
523 :max 1
524 :host host
525 :port port
f5e3c598 526 :user smtpmail-smtp-user
97bb1093
LMI
527 :require '(:user :secret)
528 :create t))
529 password (plist-get auth-info :secret)))
95f41d9a
LMI
530 (when (functionp password)
531 (setq password (funcall password)))
532 (cond
533 ((or (not mech)
534 (not user)
535 (not password))
536 ;; No mechanism, or no credentials.
537 mech)
538 ((eq mech 'cram-md5)
539 (setq ret (smtpmail-command-or-throw process "AUTH CRAM-MD5"))
540 (when (eq (car ret) 334)
541 (let* ((challenge (substring (cadr ret) 4))
542 (decoded (base64-decode-string challenge))
543 (hash (rfc2104-hash 'md5 64 16 password decoded))
544 (response (concat user " " hash))
545 ;; Osamu Yamane <yamane@green.ocn.ne.jp>:
546 ;; SMTP auth fails because the SMTP server identifies
547 ;; only the first part of the string (delimited by
548 ;; new line characters) as a response from the
549 ;; client, and the rest as distinct commands.
550
551 ;; In my case, the response string is 80 characters
552 ;; long. Without the no-line-break option for
553 ;; `base64-encode-string', only the first 76 characters
554 ;; are taken as a response to the server, and the
555 ;; authentication fails.
556 (encoded (base64-encode-string response t)))
557 (smtpmail-command-or-throw process encoded)
558 (when save-function
559 (funcall save-function)))))
560 ((eq mech 'login)
561 (smtpmail-command-or-throw process "AUTH LOGIN")
562 (smtpmail-command-or-throw
563 process (base64-encode-string user t))
564 (smtpmail-command-or-throw process (base64-encode-string password t))
565 (when save-function
566 (funcall save-function)))
567 ((eq mech 'plain)
568 ;; We used to send an empty initial request, and wait for an
569 ;; empty response, and then send the password, but this
570 ;; violate a SHOULD in RFC 2222 paragraph 5.1. Note that this
571 ;; is not sent if the server did not advertise AUTH PLAIN in
572 ;; the EHLO response. See RFC 2554 for more info.
573 (smtpmail-command-or-throw
574 process
575 (concat "AUTH PLAIN "
576 (base64-encode-string (concat "\0" user "\0" password) t))
577 235)
578 (when save-function
579 (funcall save-function)))
580 (t
581 (error "Mechanism %s not implemented" mech)))))
582
583(defun smtpmail-response-code (string)
584 (when string
585 (with-temp-buffer
586 (insert string)
587 (goto-char (point-min))
588 (and (re-search-forward "^\\([0-9]+\\) " nil t)
589 (string-to-number (match-string 1))))))
590
591(defun smtpmail-ok-p (response &optional code)
592 (and (car response)
593 (integerp (car response))
594 (< (car response) 400)
595 (or (null code)
596 (= code (car response)))))
597
598(defun smtpmail-response-text (response)
599 (mapconcat 'identity (cdr response) "\n"))
600
601(defun smtpmail-query-smtp-server ()
6546b134
GM
602 "Query for an SMTP server and try to contact it.
603If the contact succeeds, customizes and saves `smtpmail-smtp-server'
604and `smtpmail-smtp-service'. This tries standard SMTP ports, and if
605none works asks you to supply one. If you know that you need to use
606a non-standard port, you can set `smtpmail-smtp-service' in advance.
607Returns an error if the server cannot be contacted."
95f41d9a 608 (let ((server (read-string "Outgoing SMTP mail server: "))
d29b2b4c 609 (ports '(25 587))
835bdcba 610 stream port prompted)
d29b2b4c
LI
611 (when (and smtpmail-smtp-service
612 (not (member smtpmail-smtp-service ports)))
613 (push smtpmail-smtp-service ports))
95f41d9a
LMI
614 (while (and (not smtpmail-smtp-server)
615 (setq port (pop ports)))
835bdcba
LI
616 (if (not (setq stream (condition-case ()
617 (open-network-stream "smtp" nil server port)
618 (quit nil)
619 (error nil))))
6546b134 620 ;; We've used up the list of default ports, so query the user.
835bdcba
LI
621 (when (and (not ports)
622 (not prompted))
623 (push (read-number (format "Port number to use when contacting %s? "
624 server))
625 ports)
626 (setq prompted t))
9988520a
LMI
627 (customize-save-variable 'smtpmail-smtp-server server)
628 (customize-save-variable 'smtpmail-smtp-service port)
95f41d9a
LMI
629 (delete-process stream)))
630 (unless smtpmail-smtp-server
631 (error "Couldn't contact an SMTP server"))))
632
4c7e65bf
LI
633(defun smtpmail-user-mail-address ()
634 "Return `user-mail-address' if it's a valid email address."
635 (and user-mail-address
636 (let ((parts (split-string user-mail-address "@")))
637 (and (= (length parts) 2)
638 ;; There's a dot in the domain name.
639 (string-match "\\." (cadr parts))
640 user-mail-address))))
641
95f41d9a
LMI
642(defun smtpmail-via-smtp (recipient smtpmail-text-buffer
643 &optional ask-for-password)
644 (unless smtpmail-smtp-server
645 (smtpmail-query-smtp-server))
24975917 646 (let ((process nil)
f38d3514
KH
647 (host (or smtpmail-smtp-server
648 (error "`smtpmail-smtp-server' not defined")))
8805249b 649 (port smtpmail-smtp-service)
75da36cc 650 ;; `smtpmail-mail-address' should be set to the appropriate
ff981226 651 ;; buffer-local value by the caller, but in case not:
4c7e65bf
LI
652 (envelope-from
653 (or smtpmail-mail-address
654 (and mail-specify-envelope-from
655 (mail-envelope-from))
4c7e65bf
LI
656 (let ((from (mail-fetch-field "from")))
657 (and from
8ce192e3
LI
658 (cadr (mail-extract-address-components from))))
659 (smtpmail-user-mail-address)))
24975917 660 response-code
c50d5ce0 661 process-buffer
95f41d9a
LMI
662 result
663 auth-mechanisms
c50d5ce0 664 (supported-extensions '()))
24975917
RS
665 (unwind-protect
666 (catch 'done
667 ;; get or create the trace buffer
668 (setq process-buffer
95f41d9a
LMI
669 (get-buffer-create
670 (format "*trace of SMTP session to %s*" host)))
24975917
RS
671
672 ;; clear the trace buffer of old output
21bf0d6c 673 (with-current-buffer process-buffer
9cf328cc 674 (setq buffer-undo-list t)
24975917
RS
675 (erase-buffer))
676
677 ;; open the connection to the server
c65c9622
LMI
678 (let ((coding-system-for-read 'binary)
679 (coding-system-for-write 'binary))
680 (setq result
681 (open-network-stream
682 "smtpmail" process-buffer host port
683 :type smtpmail-stream-type
684 :return-list t
685 :capability-command (format "EHLO %s\r\n" (smtpmail-fqdn))
686 :end-of-command "^[0-9]+ .*\r\n"
687 :success "^2.*\n"
688 :always-query-capabilities t
689 :starttls-function
690 (lambda (capabilities)
85a16208 691 (and (string-match "[ -]STARTTLS" capabilities)
c65c9622
LMI
692 "STARTTLS\r\n"))
693 :client-certificate t
694 :use-starttls-if-possible t)))
95f41d9a
LMI
695
696 ;; If we couldn't access the server at all, we give up.
697 (unless (setq process (car result))
468d09d4
LMI
698 (throw 'done (if (plist-get (cdr result) :error)
699 (plist-get (cdr result) :error)
700 "Unable to contact server")))
24975917
RS
701
702 ;; set the send-filter
703 (set-process-filter process 'smtpmail-process-filter)
704
95f41d9a
LMI
705 (let* ((greeting (plist-get (cdr result) :greeting))
706 (code (smtpmail-response-code greeting)))
707 (unless code
708 (throw 'done (format "No greeting: %s" greeting)))
709 (when (>= code 400)
710 (throw 'done (format "Connection not allowed: %s" greeting))))
e5f1c99e 711
21bf0d6c 712 (with-current-buffer process-buffer
4b876894 713 (set-buffer-process-coding-system 'raw-text-unix 'raw-text-unix)
24975917
RS
714 (make-local-variable 'smtpmail-read-point)
715 (setq smtpmail-read-point (point-min))
716
95f41d9a
LMI
717 (let* ((capabilities (plist-get (cdr result) :capabilities))
718 (code (smtpmail-response-code capabilities)))
719 (if (or (null code)
720 (>= code 400))
721 ;; The server didn't accept EHLO, so we fall back on HELO.
722 (smtpmail-command-or-throw
723 process (format "HELO %s" (smtpmail-fqdn)))
724 ;; EHLO was successful, so we parse the extensions.
725 (dolist (line (delete
726 ""
727 (split-string
728 (plist-get (cdr result) :capabilities)
729 "\r\n")))
730 (let ((name
731 (with-case-table ascii-case-table
732 (mapcar (lambda (s) (intern (downcase s)))
733 (split-string (substring line 4) "[ ]")))))
734 (when (= (length name) 1)
735 (setq name (car name)))
736 (when name
737 (cond ((memq (if (consp name) (car name) name)
738 '(verb xvrb 8bitmime onex xone
739 expn size dsn etrn
740 enhancedstatuscodes
741 help xusr
742 auth=login auth starttls))
743 (setq supported-extensions
744 (cons name supported-extensions)))
745 (smtpmail-warn-about-unknown-extensions
746 (message "Unknown extension %s" name))))))))
747
748 (setq auth-mechanisms
749 (smtpmail-try-auth-methods
750 process supported-extensions host port
751 ask-for-password))
752
753 (when (or (member 'onex supported-extensions)
754 (member 'xone supported-extensions))
755 (smtpmail-command-or-throw process (format "ONEX")))
756
757 (when (and smtpmail-debug-verb
758 (or (member 'verb supported-extensions)
759 (member 'xvrb supported-extensions)))
760 (smtpmail-command-or-throw process (format "VERB")))
761
762 (when (member 'xusr supported-extensions)
763 (smtpmail-command-or-throw process (format "XUSR")))
e5f1c99e 764
a8df98fd 765 ;; MAIL FROM:<sender>
c50d5ce0 766 (let ((size-part
9056f1c9
RS
767 (if (or (member 'size supported-extensions)
768 (assoc 'size supported-extensions))
c50d5ce0 769 (format " SIZE=%d"
21bf0d6c 770 (with-current-buffer smtpmail-text-buffer
c50d5ce0
RS
771 ;; size estimate:
772 (+ (- (point-max) (point-min))
773 ;; Add one byte for each change-of-line
73921ac1
GM
774 ;; because of CR-LF representation:
775 (count-lines (point-min) (point-max)))))
c50d5ce0
RS
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 "")))
7d36ad46 794 (smtpmail-send-command
95f41d9a 795 process (format "MAIL FROM:<%s>%s%s"
7d36ad46
LMI
796 envelope-from size-part body-part))
797 (cond
798 ((smtpmail-ok-p (setq result (smtpmail-read-response process)))
799 ;; Success.
800 )
801 ((and auth-mechanisms
802 (not ask-for-password)
e5f1c99e 803 (eq (car result) 530))
7d36ad46
LMI
804 ;; We got a "530 auth required", so we close and try
805 ;; again, this time asking the user for a password.
5d5ac8ec
LMI
806 ;; We ignore any errors here, because some MTAs just
807 ;; close the connection immediately after giving the
808 ;; error message.
809 (ignore-errors
810 (smtpmail-send-command process "QUIT")
811 (smtpmail-read-response process))
7d36ad46 812 (delete-process process)
396f7c9d 813 (setq process nil)
7d36ad46
LMI
814 (throw 'done
815 (smtpmail-via-smtp recipient smtpmail-text-buffer t)))
816 (t
817 ;; Return the error code.
818 (throw 'done
819 (smtpmail-response-text result)))))
a8ba4429 820
a8df98fd 821 ;; RCPT TO:<recipient>
8805249b
RS
822 (let ((n 0))
823 (while (not (null (nth n recipient)))
95f41d9a
LMI
824 (smtpmail-send-command
825 process (format "RCPT TO:<%s>"
826 (smtpmail-maybe-append-domain
827 (nth n recipient))))
828 (cond
829 ((smtpmail-ok-p (setq result (smtpmail-read-response process)))
830 ;; Success.
831 nil)
832 ((and auth-mechanisms
833 (not ask-for-password)
e5f1c99e 834 (integerp (car result))
4e190b80
LMI
835 (>= (car result) 550)
836 (<= (car result) 554))
837 ;; We got a "550 relay not permitted" (or the like),
838 ;; and the server accepts credentials, so we try
839 ;; again, but ask for a password first.
95f41d9a
LMI
840 (smtpmail-send-command process "QUIT")
841 (smtpmail-read-response process)
842 (delete-process process)
396f7c9d 843 (setq process nil)
95f41d9a
LMI
844 (throw 'done
845 (smtpmail-via-smtp recipient smtpmail-text-buffer t)))
846 (t
847 ;; Return the error code.
848 (throw 'done
849 (smtpmail-response-text result))))
850 (setq n (1+ n))))
851
852 ;; Send the contents.
853 (smtpmail-command-or-throw process "DATA")
24975917 854 (smtpmail-send-data process smtpmail-text-buffer)
75da36cc 855 ;; DATA end "."
95f41d9a
LMI
856 (smtpmail-command-or-throw process ".")
857 ;; Return success.
858 nil))
859 (when (and process
860 (buffer-live-p process-buffer))
861 (with-current-buffer (process-buffer process)
862 (smtpmail-send-command process "QUIT")
863 (smtpmail-read-response process)
864 (delete-process process)
865 (unless smtpmail-debug-info
866 (kill-buffer process-buffer)))))))
24975917
RS
867
868
24975917 869(defun smtpmail-process-filter (process output)
21bf0d6c 870 (with-current-buffer (process-buffer process)
24975917 871 (goto-char (point-max))
65a046c4
LMI
872 (insert output)
873 (set-marker (process-mark process) (point))))
24975917 874
24975917
RS
875(defun smtpmail-read-response (process)
876 (let ((case-fold-search nil)
c50d5ce0 877 (response-strings nil)
24975917 878 (response-continue t)
c50d5ce0 879 (return-value '(nil ()))
24975917 880 match-end)
2ceed428
SJ
881 (catch 'done
882 (while response-continue
883 (goto-char smtpmail-read-point)
884 (while (not (search-forward "\r\n" nil t))
885 (unless (memq (process-status process) '(open run))
886 (throw 'done nil))
887 (accept-process-output process)
888 (goto-char smtpmail-read-point))
889
890 (setq match-end (point))
891 (setq response-strings
892 (cons (buffer-substring smtpmail-read-point (- match-end 2))
893 response-strings))
894
895 (goto-char smtpmail-read-point)
896 (if (looking-at "[0-9]+ ")
897 (let ((begin (match-beginning 0))
898 (end (match-end 0)))
899 (if smtpmail-debug-info
900 (message "%s" (car response-strings)))
901
902 (setq smtpmail-read-point match-end)
903
904 ;; ignore lines that start with "0"
905 (if (looking-at "0[0-9]+ ")
906 nil
907 (setq response-continue nil)
908 (setq return-value
027a4b6b 909 (cons (string-to-number
2ceed428
SJ
910 (buffer-substring begin end))
911 (nreverse response-strings)))))
912
913 (if (looking-at "[0-9]+-")
914 (progn (if smtpmail-debug-info
915 (message "%s" (car response-strings)))
916 (setq smtpmail-read-point match-end)
917 (setq response-continue t))
918 (progn
919 (setq smtpmail-read-point match-end)
c50d5ce0
RS
920 (setq response-continue nil)
921 (setq return-value
2ceed428
SJ
922 (cons nil (nreverse response-strings)))))))
923 (setq smtpmail-read-point match-end))
24975917
RS
924 return-value))
925
926
24975917
RS
927(defun smtpmail-send-command (process command)
928 (goto-char (point-max))
7520339c
LMI
929 (if (string-match "\\`AUTH [A-Z]+ " command)
930 (insert (match-string 0 command) "<omitted>\r\n")
24975917
RS
931 (insert command "\r\n"))
932 (setq smtpmail-read-point (point))
8633b1f4 933 (process-send-string process (concat command "\r\n")))
24975917 934
24975917
RS
935(defun smtpmail-send-data-1 (process data)
936 (goto-char (point-max))
937
83af570e
KH
938 (if (and (multibyte-string-p data)
939 smtpmail-code-conv-from)
940 (setq data (string-as-multibyte
941 (encode-coding-string data smtpmail-code-conv-from))))
a8ba4429 942
24975917
RS
943 (if smtpmail-debug-info
944 (insert data "\r\n"))
945
946 (setq smtpmail-read-point (point))
57810560
KH
947 ;; Escape "." at start of a line
948 (if (eq (string-to-char data) ?.)
24975917 949 (process-send-string process "."))
57810560 950 (process-send-string process data)
75da36cc 951 (process-send-string process "\r\n"))
24975917
RS
952
953(defun smtpmail-send-data (process buffer)
1257e755
SM
954 (let ((data-continue t) sending-data
955 (pr (with-current-buffer buffer
112a6592 956 (make-progress-reporter "Sending email "
1257e755 957 (point-min) (point-max)))))
21bf0d6c 958 (with-current-buffer buffer
24975917 959 (goto-char (point-min)))
24975917 960 (while data-continue
21bf0d6c 961 (with-current-buffer buffer
1257e755 962 (progress-reporter-update pr (point))
dd64e5e5
GM
963 (setq sending-data (buffer-substring (point-at-bol) (point-at-eol)))
964 (end-of-line 2)
965 (setq data-continue (not (eobp))))
1257e755
SM
966 (smtpmail-send-data-1 process sending-data))
967 (progress-reporter-done pr)))
24975917
RS
968
969(defun smtpmail-deduce-address-list (smtpmail-text-buffer header-start header-end)
970 "Get address list suitable for smtp RCPT TO: <address>."
1188dd37 971 (unwind-protect
21bf0d6c
SM
972 (with-current-buffer smtpmail-address-buffer
973 (erase-buffer)
75da36cc
RW
974 (let ((case-fold-search t)
975 (simple-address-list "")
976 this-line
977 this-line-end
978 addr-regexp)
24975917
RS
979 (insert-buffer-substring smtpmail-text-buffer header-start header-end)
980 (goto-char (point-min))
13f1d088
KH
981 ;; RESENT-* fields should stop processing of regular fields.
982 (save-excursion
21bf0d6c
SM
983 (setq addr-regexp
984 (if (re-search-forward "^Resent-\\(to\\|cc\\|bcc\\):"
985 header-end t)
986 "^Resent-\\(to\\|cc\\|bcc\\):"
987 "^\\(To:\\|Cc:\\|Bcc:\\)")))
13f1d088
KH
988
989 (while (re-search-forward addr-regexp header-end t)
24975917
RS
990 (replace-match "")
991 (setq this-line (match-beginning 0))
992 (forward-line 1)
993 ;; get any continuation lines
994 (while (and (looking-at "^[ \t]+") (< (point) header-end))
995 (forward-line 1))
996 (setq this-line-end (point-marker))
997 (setq simple-address-list
998 (concat simple-address-list " "
75da36cc 999 (mail-strip-quoted-names (buffer-substring this-line this-line-end)))))
24975917 1000 (erase-buffer)
92dfd10c 1001 (insert " " simple-address-list "\n")
75da36cc
RW
1002 (subst-char-in-region (point-min) (point-max) 10 ? t) ; newline --> blank
1003 (subst-char-in-region (point-min) (point-max) ?, ? t) ; comma --> blank
1004 (subst-char-in-region (point-min) (point-max) 9 ? t) ; tab --> blank
24975917
RS
1005
1006 (goto-char (point-min))
cd1181db 1007 ;; tidiness in case hook is not robust when it looks at this
24975917
RS
1008 (while (re-search-forward "[ \t]+" header-end t) (replace-match " "))
1009
1010 (goto-char (point-min))
8805249b 1011 (let (recipient-address-list)
e2f7c221 1012 (while (re-search-forward " \\([^ ]+\\) " (point-max) t)
8805249b 1013 (backward-char 1)
e2f7c221 1014 (setq recipient-address-list (cons (buffer-substring (match-beginning 1) (match-end 1))
75da36cc
RW
1015 recipient-address-list)))
1016 (setq smtpmail-recipient-address-list recipient-address-list))))))
24975917
RS
1017
1018(defun smtpmail-do-bcc (header-end)
5feeeae2 1019 "Delete [Resent-]BCC: and their continuation lines from the header area.
24975917
RS
1020There may be multiple BCC: lines, and each may have arbitrarily
1021many continuation lines."
1022 (let ((case-fold-search t))
067427f5
KH
1023 (save-excursion
1024 (goto-char (point-min))
1025 ;; iterate over all BCC: lines
1026 (while (re-search-forward "^\\(RESENT-\\)?BCC:" header-end t)
1027 (delete-region (match-beginning 0)
1028 (progn (forward-line 1) (point)))
1029 ;; get rid of any continuation lines
1030 (while (and (looking-at "^[ \t].*\n") (< (point) header-end))
1031 (replace-match ""))))))
24975917 1032
24975917
RS
1033(provide 'smtpmail)
1034
092af6d8 1035;;; smtpmail.el ends here