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