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