* Makefile.in (GNULIB_MODULES): Change ftoastr to dtoastr.
[emacs.git] / lisp / mail / smtpmail.el
blob7aed6a549ef314c4fe59ed881c20c5da07148fe4
1 ;;; smtpmail.el --- simple SMTP protocol (RFC 821) for sending mail
3 ;; Copyright (C) 1995, 1996, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
4 ;; 2008, 2009, 2010 Free Software Foundation, Inc.
6 ;; Author: Tomoji Kagatani <kagatani@rbc.ncl.omron.co.jp>
7 ;; Maintainer: Simon Josefsson <simon@josefsson.org>
8 ;; w32 Maintainer: Brian D. Carlstrom <bdc@ai.mit.edu>
9 ;; ESMTP support: Simon Leinen <simon@switch.ch>
10 ;; Hacked by Mike Taylor, 11th October 1999 to add support for
11 ;; automatically appending a domain to RCPT TO: addresses.
12 ;; AUTH=LOGIN support: Stephen Cranefield <scranefield@infoscience.otago.ac.nz>
13 ;; Keywords: mail
15 ;; This file is part of GNU Emacs.
17 ;; GNU Emacs is free software: you can redistribute it and/or modify
18 ;; it under the terms of the GNU General Public License as published by
19 ;; the Free Software Foundation, either version 3 of the License, or
20 ;; (at your option) any later version.
22 ;; GNU Emacs is distributed in the hope that it will be useful,
23 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
24 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 ;; GNU General Public License for more details.
27 ;; You should have received a copy of the GNU General Public License
28 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
30 ;;; Commentary:
32 ;; Send Mail to smtp host from smtpmail temp buffer.
34 ;; Please add these lines in your .emacs(_emacs) or use customize.
36 ;;(setq send-mail-function 'smtpmail-send-it) ; if you use `mail'
37 ;;(setq message-send-mail-function 'smtpmail-send-it) ; if you use message/Gnus
38 ;;(setq smtpmail-default-smtp-server "YOUR SMTP HOST")
39 ;;(setq smtpmail-local-domain "YOUR DOMAIN NAME")
40 ;;(setq smtpmail-sendto-domain "YOUR DOMAIN NAME")
41 ;;(setq smtpmail-debug-info t) ; only to debug problems
42 ;;(setq smtpmail-auth-credentials ; or use ~/.authinfo
43 ;; '(("YOUR SMTP HOST" 25 "username" "password")))
44 ;;(setq smtpmail-starttls-credentials
45 ;; '(("YOUR SMTP HOST" 25 "~/.my_smtp_tls.key" "~/.my_smtp_tls.cert")))
46 ;; Where the 25 equals the value of `smtpmail-smtp-service', it can be an
47 ;; integer or a string, just as long as they match (eq).
49 ;; To queue mail, set `smtpmail-queue-mail' to t and use
50 ;; `smtpmail-send-queued-mail' to send.
52 ;; Modified by Stephen Cranefield <scranefield@infoscience.otago.ac.nz>,
53 ;; 22/6/99, to support SMTP Authentication by the AUTH=LOGIN mechanism.
54 ;; See http://help.netscape.com/products/server/messaging/3x/info/smtpauth.html
55 ;; Rewritten by Simon Josefsson to use same credential variable as AUTH
56 ;; support below.
58 ;; Modified by Simon Josefsson <jas@pdc.kth.se>, 22/2/99, to support SMTP
59 ;; Authentication by the AUTH mechanism.
60 ;; See http://www.ietf.org/rfc/rfc2554.txt
62 ;; Modified by Simon Josefsson <simon@josefsson.org>, 2000-10-07, to support
63 ;; STARTTLS. Requires external program
64 ;; ftp://ftp.opaopa.org/pub/elisp/starttls-*.tar.gz.
65 ;; See http://www.ietf.org/rfc/rfc2246.txt, http://www.ietf.org/rfc/rfc2487.txt
67 ;;; Code:
69 (require 'sendmail)
70 (autoload 'starttls-any-program-available "starttls")
71 (autoload 'starttls-open-stream "starttls")
72 (autoload 'starttls-negotiate "starttls")
73 (autoload 'mail-strip-quoted-names "mail-utils")
74 (autoload 'message-make-date "message")
75 (autoload 'message-make-message-id "message")
76 (autoload 'rfc2104-hash "rfc2104")
77 (autoload 'netrc-parse "netrc")
78 (autoload 'netrc-machine "netrc")
79 (autoload 'netrc-get "netrc")
80 (autoload 'password-read "password-cache")
81 (autoload 'auth-source-user-or-password "auth-source")
83 ;;;
84 (defgroup smtpmail nil
85 "SMTP protocol for sending mail."
86 :group 'mail)
89 (defcustom smtpmail-default-smtp-server nil
90 "Specify default SMTP server.
91 This only has effect if you specify it before loading the smtpmail library."
92 :type '(choice (const nil) string)
93 :group 'smtpmail)
95 (defcustom smtpmail-smtp-server
96 (or (getenv "SMTPSERVER") smtpmail-default-smtp-server)
97 "The name of the host running SMTP server."
98 :type '(choice (const nil) string)
99 :group 'smtpmail)
101 (defcustom smtpmail-smtp-service 25
102 "SMTP service port number.
103 The default value would be \"smtp\" or 25."
104 :type '(choice (integer :tag "Port") (string :tag "Service"))
105 :group 'smtpmail)
107 (defcustom smtpmail-local-domain nil
108 "Local domain name without a host name.
109 If the function `system-name' returns the full internet address,
110 don't define this value."
111 :type '(choice (const nil) string)
112 :group 'smtpmail)
114 (defcustom smtpmail-sendto-domain nil
115 "Local domain name without a host name.
116 This is appended (with an @-sign) to any specified recipients which do
117 not include an @-sign, so that each RCPT TO address is fully qualified.
118 \(Some configurations of sendmail require this.)
120 Don't bother to set this unless you have get an error like:
121 Sending failed; SMTP protocol error
122 when sending mail, and the *trace of SMTP session to <somewhere>*
123 buffer includes an exchange like:
124 RCPT TO: <someone>
125 501 <someone>: recipient address must contain a domain."
126 :type '(choice (const nil) string)
127 :group 'smtpmail)
129 (defcustom smtpmail-debug-info nil
130 "Whether to print info in buffer *trace of SMTP session to <somewhere>*.
131 See also `smtpmail-debug-verb' which determines if the SMTP protocol should
132 be verbose as well."
133 :type 'boolean
134 :group 'smtpmail)
136 (defcustom smtpmail-debug-verb nil
137 "Whether this library sends the SMTP VERB command or not.
138 The commands enables verbose information from the SMTP server."
139 :type 'boolean
140 :group 'smtpmail)
142 (defcustom smtpmail-code-conv-from nil
143 "Coding system for encoding outgoing mail.
144 Used for the value of `sendmail-coding-system' when
145 `select-message-coding-system' is called. "
146 :type 'coding-system
147 :group 'smtpmail)
149 (defcustom smtpmail-queue-mail nil
150 "Non-nil means mail is queued; otherwise it is sent immediately.
151 If queued, it is stored in the directory `smtpmail-queue-dir'
152 and sent with `smtpmail-send-queued-mail'."
153 :type 'boolean
154 :group 'smtpmail)
156 (defcustom smtpmail-queue-dir "~/Mail/queued-mail/"
157 "Directory where `smtpmail.el' stores queued mail."
158 :type 'directory
159 :group 'smtpmail)
161 (defcustom smtpmail-auth-credentials "~/.authinfo"
162 "Specify username and password for servers, directly or via .netrc file.
163 This variable can either be a filename pointing to a file in netrc(5)
164 format, or list of four-element lists that contain, in order,
165 `servername' (a string), `port' (an integer), `user' (a string) and
166 `password' (a string, or nil to query the user when needed). If you
167 need to enter a `realm' too, add it to the user string, so that it
168 looks like `user@realm'."
169 :type '(choice file
170 (repeat (list (string :tag "Server")
171 (integer :tag "Port")
172 (string :tag "Username")
173 (choice (const :tag "Query when needed" nil)
174 (string :tag "Password")))))
175 :version "22.1"
176 :group 'smtpmail)
178 (defcustom smtpmail-starttls-credentials '(("" 25 "" ""))
179 "Specify STARTTLS keys and certificates for servers.
180 This is a list of four-element list with `servername' (a string),
181 `port' (an integer), `key' (a filename) and `certificate' (a
182 filename).
183 If you do not have a certificate/key pair, leave the `key' and
184 `certificate' fields as `nil'. A key/certificate pair is only
185 needed if you want to use X.509 client authenticated
186 connections."
187 :type '(repeat (list (string :tag "Server")
188 (integer :tag "Port")
189 (file :tag "Key")
190 (file :tag "Certificate")))
191 :version "21.1"
192 :group 'smtpmail)
194 (defcustom smtpmail-warn-about-unknown-extensions nil
195 "If set, print warnings about unknown SMTP extensions.
196 This is mainly useful for development purposes, to learn about
197 new SMTP extensions that might be useful to support."
198 :type 'boolean
199 :version "21.1"
200 :group 'smtpmail)
202 (defcustom smtpmail-queue-index-file "index"
203 "File name of queued mail index.
204 This is relative to `smtpmail-queue-dir'."
205 :type 'string
206 :group 'smtpmail)
208 ;; End of customizable variables.
211 (defvar smtpmail-address-buffer)
212 (defvar smtpmail-recipient-address-list)
214 (defvar smtpmail-queue-counter 0)
216 ;; Buffer-local variable.
217 (defvar smtpmail-read-point)
219 (defconst smtpmail-auth-supported '(cram-md5 plain login)
220 "List of supported SMTP AUTH mechanisms.
221 The list is in preference order.")
223 (defvar smtpmail-mail-address nil
224 "Value to use for envelope-from address for mail from ambient buffer.")
226 ;;;###autoload
227 (defun smtpmail-send-it ()
228 (let ((errbuf (if mail-interactive
229 (generate-new-buffer " smtpmail errors")
231 (tembuf (generate-new-buffer " smtpmail temp"))
232 (case-fold-search nil)
233 delimline
234 (mailbuf (current-buffer))
235 ;; Examine this variable now, so that
236 ;; local binding in the mail buffer will take effect.
237 (smtpmail-mail-address
238 (or (and mail-specify-envelope-from (mail-envelope-from))
239 user-mail-address))
240 (smtpmail-code-conv-from
241 (if enable-multibyte-characters
242 (let ((sendmail-coding-system smtpmail-code-conv-from))
243 (select-message-coding-system)))))
244 (unwind-protect
245 (with-current-buffer tembuf
246 (erase-buffer)
247 ;; Use the same `buffer-file-coding-system' as in the mail
248 ;; buffer, otherwise any `write-region' invocations (e.g., in
249 ;; mail-do-fcc below) will annoy with asking for a suitable
250 ;; encoding.
251 (set-buffer-file-coding-system smtpmail-code-conv-from nil t)
252 (insert-buffer-substring mailbuf)
253 (goto-char (point-max))
254 ;; require one newline at the end.
255 (or (= (preceding-char) ?\n)
256 (insert ?\n))
257 ;; Change header-delimiter to be what sendmail expects.
258 (mail-sendmail-undelimit-header)
259 (setq delimline (point-marker))
260 ;; (sendmail-synch-aliases)
261 (if mail-aliases
262 (expand-mail-aliases (point-min) delimline))
263 (goto-char (point-min))
264 ;; ignore any blank lines in the header
265 (while (and (re-search-forward "\n\n\n*" delimline t)
266 (< (point) delimline))
267 (replace-match "\n"))
268 (let ((case-fold-search t))
269 ;; We used to process Resent-... headers here,
270 ;; but it was not done properly, and the job
271 ;; is done correctly in `smtpmail-deduce-address-list'.
272 ;; Don't send out a blank subject line
273 (goto-char (point-min))
274 (if (re-search-forward "^Subject:\\([ \t]*\n\\)+\\b" delimline t)
275 (replace-match "")
276 ;; This one matches a Subject just before the header delimiter.
277 (if (and (re-search-forward "^Subject:\\([ \t]*\n\\)+" delimline t)
278 (= (match-end 0) delimline))
279 (replace-match "")))
280 ;; Put the "From:" field in unless for some odd reason
281 ;; they put one in themselves.
282 (goto-char (point-min))
283 (if (not (re-search-forward "^From:" delimline t))
284 (let* ((login smtpmail-mail-address)
285 (fullname (user-full-name)))
286 (cond ((eq mail-from-style 'angles)
287 (insert "From: " fullname)
288 (let ((fullname-start (+ (point-min) 6))
289 (fullname-end (point-marker)))
290 (goto-char fullname-start)
291 ;; Look for a character that cannot appear unquoted
292 ;; according to RFC 822.
293 (if (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]"
294 fullname-end 1)
295 (progn
296 ;; Quote fullname, escaping specials.
297 (goto-char fullname-start)
298 (insert "\"")
299 (while (re-search-forward "[\"\\]"
300 fullname-end 1)
301 (replace-match "\\\\\\&" t))
302 (insert "\""))))
303 (insert " <" login ">\n"))
304 ((eq mail-from-style 'parens)
305 (insert "From: " login " (")
306 (let ((fullname-start (point)))
307 (insert fullname)
308 (let ((fullname-end (point-marker)))
309 (goto-char fullname-start)
310 ;; RFC 822 says \ and nonmatching parentheses
311 ;; must be escaped in comments.
312 ;; Escape every instance of ()\ ...
313 (while (re-search-forward "[()\\]" fullname-end 1)
314 (replace-match "\\\\\\&" t))
315 ;; ... then undo escaping of matching parentheses,
316 ;; including matching nested parentheses.
317 (goto-char fullname-start)
318 (while (re-search-forward
319 "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
320 fullname-end 1)
321 (replace-match "\\1(\\3)" t)
322 (goto-char fullname-start))))
323 (insert ")\n"))
324 ((null mail-from-style)
325 (insert "From: " login "\n")))))
326 ;; Insert a `Message-Id:' field if there isn't one yet.
327 (goto-char (point-min))
328 (unless (re-search-forward "^Message-Id:" delimline t)
329 (insert "Message-Id: " (message-make-message-id) "\n"))
330 ;; Insert a `Date:' field if there isn't one yet.
331 (goto-char (point-min))
332 (unless (re-search-forward "^Date:" delimline t)
333 (insert "Date: " (message-make-date) "\n"))
334 ;; Possibly add a MIME header for the current coding system
335 (let (charset)
336 (goto-char (point-min))
337 (and (eq mail-send-nonascii 'mime)
338 (not (re-search-forward "^MIME-version:" delimline t))
339 (progn (skip-chars-forward "\0-\177")
340 (/= (point) (point-max)))
341 smtpmail-code-conv-from
342 (setq charset
343 (coding-system-get smtpmail-code-conv-from
344 'mime-charset))
345 (goto-char delimline)
346 (insert "MIME-version: 1.0\n"
347 "Content-type: text/plain; charset="
348 (symbol-name charset)
349 "\nContent-Transfer-Encoding: 8bit\n")))
350 ;; Insert an extra newline if we need it to work around
351 ;; Sun's bug that swallows newlines.
352 (goto-char (1+ delimline))
353 (if (eval mail-mailer-swallows-blank-line)
354 (newline))
355 ;; Find and handle any FCC fields.
356 (goto-char (point-min))
357 (if (re-search-forward "^FCC:" delimline t)
358 ;; Force `mail-do-fcc' to use the encoding of the mail
359 ;; buffer to encode outgoing messages on FCC files.
360 (let ((coding-system-for-write smtpmail-code-conv-from))
361 (mail-do-fcc delimline)))
362 (if mail-interactive
363 (with-current-buffer errbuf
364 (erase-buffer))))
366 (setq smtpmail-address-buffer (generate-new-buffer "*smtp-mail*"))
367 (setq smtpmail-recipient-address-list
368 (smtpmail-deduce-address-list tembuf (point-min) delimline))
369 (kill-buffer smtpmail-address-buffer)
371 (smtpmail-do-bcc delimline)
372 ;; Send or queue
373 (if (not smtpmail-queue-mail)
374 (if (not (null smtpmail-recipient-address-list))
375 (if (not (smtpmail-via-smtp
376 smtpmail-recipient-address-list tembuf))
377 (error "Sending failed; SMTP protocol error"))
378 (error "Sending failed; no recipients"))
379 (let* ((file-data
380 (expand-file-name
381 (format "%s_%i"
382 (format-time-string "%Y-%m-%d_%H:%M:%S")
383 (setq smtpmail-queue-counter
384 (1+ smtpmail-queue-counter)))
385 smtpmail-queue-dir))
386 (file-data (convert-standard-filename file-data))
387 (file-elisp (concat file-data ".el"))
388 (buffer-data (create-file-buffer file-data))
389 (buffer-elisp (create-file-buffer file-elisp))
390 (buffer-scratch "*queue-mail*"))
391 (unless (file-exists-p smtpmail-queue-dir)
392 (make-directory smtpmail-queue-dir t))
393 (with-current-buffer buffer-data
394 (erase-buffer)
395 (set-buffer-file-coding-system
396 ;; We will be reading the file with no-conversion in
397 ;; smtpmail-send-queued-mail below, so write it out
398 ;; with Unix EOLs.
399 (coding-system-change-eol-conversion
400 (or smtpmail-code-conv-from 'undecided)
401 'unix)
402 nil t)
403 (insert-buffer-substring tembuf)
404 (write-file file-data)
405 (set-buffer buffer-elisp)
406 (erase-buffer)
407 (insert (concat
408 "(setq smtpmail-recipient-address-list '"
409 (prin1-to-string smtpmail-recipient-address-list)
410 ")\n"))
411 (write-file file-elisp)
412 (set-buffer (generate-new-buffer buffer-scratch))
413 (insert (concat file-data "\n"))
414 (append-to-file (point-min)
415 (point-max)
416 (expand-file-name smtpmail-queue-index-file
417 smtpmail-queue-dir)))
418 (kill-buffer buffer-scratch)
419 (kill-buffer buffer-data)
420 (kill-buffer buffer-elisp))))
421 (kill-buffer tembuf)
422 (if (bufferp errbuf)
423 (kill-buffer errbuf)))))
425 ;;;###autoload
426 (defun smtpmail-send-queued-mail ()
427 "Send mail that was queued as a result of setting `smtpmail-queue-mail'."
428 (interactive)
429 (with-temp-buffer
430 ;; Get index, get first mail, send it, update index, get second
431 ;; mail, send it, etc...
432 (let ((file-msg "")
433 (qfile (expand-file-name smtpmail-queue-index-file
434 smtpmail-queue-dir)))
435 (insert-file-contents qfile)
436 (goto-char (point-min))
437 (while (not (eobp))
438 (setq file-msg (buffer-substring (point) (line-end-position)))
439 (load file-msg)
440 ;; Insert the message literally: it is already encoded as per
441 ;; the MIME headers, and code conversions might guess the
442 ;; encoding wrongly.
443 (with-temp-buffer
444 (let ((coding-system-for-read 'no-conversion))
445 (insert-file-contents file-msg))
446 (let ((smtpmail-mail-address
447 (or (and mail-specify-envelope-from (mail-envelope-from))
448 user-mail-address)))
449 (if (not (null smtpmail-recipient-address-list))
450 (if (not (smtpmail-via-smtp smtpmail-recipient-address-list
451 (current-buffer)))
452 (error "Sending failed; SMTP protocol error"))
453 (error "Sending failed; no recipients"))))
454 (delete-file file-msg)
455 (delete-file (concat file-msg ".el"))
456 (delete-region (point-at-bol) (point-at-bol 2)))
457 (write-region (point-min) (point-max) qfile))))
459 ;; (defun smtpmail-via-smtp (host,port,sender,destination,smtpmail-text-buffer)
461 (defun smtpmail-fqdn ()
462 (if smtpmail-local-domain
463 (concat (system-name) "." smtpmail-local-domain)
464 (system-name)))
466 (defsubst smtpmail-cred-server (cred)
467 (nth 0 cred))
469 (defsubst smtpmail-cred-port (cred)
470 (nth 1 cred))
472 (defsubst smtpmail-cred-key (cred)
473 (nth 2 cred))
475 (defsubst smtpmail-cred-user (cred)
476 (nth 2 cred))
478 (defsubst smtpmail-cred-cert (cred)
479 (nth 3 cred))
481 (defsubst smtpmail-cred-passwd (cred)
482 (nth 3 cred))
484 (defun smtpmail-find-credentials (cred server port)
485 (catch 'done
486 (let ((l cred) el)
487 (while (setq el (pop l))
488 (when (and (equal server (smtpmail-cred-server el))
489 (equal port (smtpmail-cred-port el)))
490 (throw 'done el))))))
492 (defun smtpmail-maybe-append-domain (recipient)
493 (if (or (not smtpmail-sendto-domain)
494 (string-match "@" recipient))
495 recipient
496 (concat recipient "@" smtpmail-sendto-domain)))
498 (defun smtpmail-intersection (list1 list2)
499 (let ((result nil))
500 (dolist (el2 list2)
501 (when (memq el2 list1)
502 (push el2 result)))
503 (nreverse result)))
505 (defvar starttls-extra-args)
506 (defvar starttls-extra-arguments)
508 (defun smtpmail-open-stream (process-buffer host port)
509 (let ((cred (smtpmail-find-credentials
510 smtpmail-starttls-credentials host port)))
511 (if (null (and cred (starttls-any-program-available)))
512 ;; The normal case.
513 (open-network-stream "SMTP" process-buffer host port)
514 (let* ((cred-key (smtpmail-cred-key cred))
515 (cred-cert (smtpmail-cred-cert cred))
516 (starttls-extra-args
517 (append
518 starttls-extra-args
519 (when (and (stringp cred-key) (stringp cred-cert)
520 (file-regular-p
521 (setq cred-key (expand-file-name cred-key)))
522 (file-regular-p
523 (setq cred-cert (expand-file-name cred-cert))))
524 (list "--key-file" cred-key "--cert-file" cred-cert))))
525 (starttls-extra-arguments
526 (append
527 starttls-extra-arguments
528 (when (and (stringp cred-key) (stringp cred-cert)
529 (file-regular-p
530 (setq cred-key (expand-file-name cred-key)))
531 (file-regular-p
532 (setq cred-cert (expand-file-name cred-cert))))
533 (list "--x509keyfile" cred-key "--x509certfile" cred-cert)))))
534 (starttls-open-stream "SMTP" process-buffer host port)))))
536 ;; `password-read' autoloads password-cache.
537 (declare-function password-cache-add "password-cache" (key password))
539 (defun smtpmail-try-auth-methods (process supported-extensions host port)
540 (let* ((mechs (cdr-safe (assoc 'auth supported-extensions)))
541 (mech (car (smtpmail-intersection mechs smtpmail-auth-supported)))
542 (auth-user (auth-source-user-or-password
543 "login" host (or port "smtp")))
544 (auth-pass (auth-source-user-or-password
545 "password" host (or port "smtp")))
546 (cred (if (and auth-user auth-pass) ; try user-auth-* before netrc-*
547 (list host port auth-user auth-pass)
548 ;; else, if auth-source didn't return them...
549 (if (stringp smtpmail-auth-credentials)
550 (let* ((netrc (netrc-parse smtpmail-auth-credentials))
551 (port-name (format "%s" (or port "smtp")))
552 (hostentry (netrc-machine netrc host port-name
553 port-name)))
554 (when hostentry
555 (list host port
556 (netrc-get hostentry "login")
557 (netrc-get hostentry "password"))))
558 ;; else, try `smtpmail-find-credentials' since
559 ;; `smtpmail-auth-credentials' is not a string
560 (smtpmail-find-credentials
561 smtpmail-auth-credentials host port))))
562 (prompt (when cred (format "SMTP password for %s:%s: "
563 (smtpmail-cred-server cred)
564 (smtpmail-cred-port cred))))
565 (passwd (when cred
566 (or (smtpmail-cred-passwd cred)
567 (password-read prompt prompt))))
568 ret)
569 (when (and cred mech)
570 (cond
571 ((eq mech 'cram-md5)
572 (smtpmail-send-command process (upcase (format "AUTH %s" mech)))
573 (if (or (null (car (setq ret (smtpmail-read-response process))))
574 (not (integerp (car ret)))
575 (>= (car ret) 400))
576 (throw 'done nil))
577 (when (eq (car ret) 334)
578 (let* ((challenge (substring (cadr ret) 4))
579 (decoded (base64-decode-string challenge))
580 (hash (rfc2104-hash 'md5 64 16 passwd decoded))
581 (response (concat (smtpmail-cred-user cred) " " hash))
582 ;; Osamu Yamane <yamane@green.ocn.ne.jp>:
583 ;; SMTP auth fails because the SMTP server identifies
584 ;; only the first part of the string (delimited by
585 ;; new line characters) as a response from the
586 ;; client, and the rest as distinct commands.
588 ;; In my case, the response string is 80 characters
589 ;; long. Without the no-line-break option for
590 ;; `base64-encode-string', only the first 76 characters
591 ;; are taken as a response to the server, and the
592 ;; authentication fails.
593 (encoded (base64-encode-string response t)))
594 (smtpmail-send-command process (format "%s" encoded))
595 (if (or (null (car (setq ret (smtpmail-read-response process))))
596 (not (integerp (car ret)))
597 (>= (car ret) 400))
598 (throw 'done nil)))))
599 ((eq mech 'login)
600 (smtpmail-send-command process "AUTH LOGIN")
601 (if (or (null (car (setq ret (smtpmail-read-response process))))
602 (not (integerp (car ret)))
603 (>= (car ret) 400))
604 (throw 'done nil))
605 (smtpmail-send-command
606 process (base64-encode-string (smtpmail-cred-user cred) t))
607 (if (or (null (car (setq ret (smtpmail-read-response process))))
608 (not (integerp (car ret)))
609 (>= (car ret) 400))
610 (throw 'done nil))
611 (smtpmail-send-command process (base64-encode-string passwd t))
612 (if (or (null (car (setq ret (smtpmail-read-response process))))
613 (not (integerp (car ret)))
614 (>= (car ret) 400))
615 (throw 'done nil)))
616 ((eq mech 'plain)
617 ;; We used to send an empty initial request, and wait for an
618 ;; empty response, and then send the password, but this
619 ;; violate a SHOULD in RFC 2222 paragraph 5.1. Note that this
620 ;; is not sent if the server did not advertise AUTH PLAIN in
621 ;; the EHLO response. See RFC 2554 for more info.
622 (smtpmail-send-command process
623 (concat "AUTH PLAIN "
624 (base64-encode-string
625 (concat "\0"
626 (smtpmail-cred-user cred)
627 "\0"
628 passwd) t)))
629 (if (or (null (car (setq ret (smtpmail-read-response process))))
630 (not (integerp (car ret)))
631 (not (equal (car ret) 235)))
632 (throw 'done nil)))
635 (error "Mechanism %s not implemented" mech)))
636 ;; Remember the password.
637 (when (null (smtpmail-cred-passwd cred))
638 (password-cache-add prompt passwd)))))
640 (defun smtpmail-via-smtp (recipient smtpmail-text-buffer)
641 (let ((process nil)
642 (host (or smtpmail-smtp-server
643 (error "`smtpmail-smtp-server' not defined")))
644 (port smtpmail-smtp-service)
645 ;; `smtpmail-mail-address' should be set to the appropriate
646 ;; buffer-local value by the caller, but in case not:
647 (envelope-from (or smtpmail-mail-address
648 (and mail-specify-envelope-from
649 (mail-envelope-from))
650 user-mail-address))
651 response-code
652 greeting
653 process-buffer
654 (supported-extensions '()))
655 (unwind-protect
656 (catch 'done
657 ;; get or create the trace buffer
658 (setq process-buffer
659 (get-buffer-create (format "*trace of SMTP session to %s*" host)))
661 ;; clear the trace buffer of old output
662 (with-current-buffer process-buffer
663 (setq buffer-undo-list t)
664 (erase-buffer))
666 ;; open the connection to the server
667 (setq process (smtpmail-open-stream process-buffer host port))
668 (and (null process) (throw 'done nil))
670 ;; set the send-filter
671 (set-process-filter process 'smtpmail-process-filter)
673 (with-current-buffer process-buffer
674 (set-buffer-process-coding-system 'raw-text-unix 'raw-text-unix)
675 (make-local-variable 'smtpmail-read-point)
676 (setq smtpmail-read-point (point-min))
679 (if (or (null (car (setq greeting (smtpmail-read-response process))))
680 (not (integerp (car greeting)))
681 (>= (car greeting) 400))
682 (throw 'done nil))
684 (let ((do-ehlo t)
685 (do-starttls t))
686 (while do-ehlo
687 ;; EHLO
688 (smtpmail-send-command process (format "EHLO %s" (smtpmail-fqdn)))
690 (if (or (null (car (setq response-code
691 (smtpmail-read-response process))))
692 (not (integerp (car response-code)))
693 (>= (car response-code) 400))
694 (progn
695 ;; HELO
696 (smtpmail-send-command
697 process (format "HELO %s" (smtpmail-fqdn)))
699 (if (or (null (car (setq response-code
700 (smtpmail-read-response process))))
701 (not (integerp (car response-code)))
702 (>= (car response-code) 400))
703 (throw 'done nil)))
704 (dolist (line (cdr (cdr response-code)))
705 (let ((name
706 (with-case-table ascii-case-table
707 (mapcar (lambda (s) (intern (downcase s)))
708 (split-string (substring line 4) "[ ]")))))
709 (and (eq (length name) 1)
710 (setq name (car name)))
711 (and name
712 (cond ((memq (if (consp name) (car name) name)
713 '(verb xvrb 8bitmime onex xone
714 expn size dsn etrn
715 enhancedstatuscodes
716 help xusr
717 auth=login auth starttls))
718 (setq supported-extensions
719 (cons name supported-extensions)))
720 (smtpmail-warn-about-unknown-extensions
721 (message "Unknown extension %s" name)))))))
723 (if (and do-starttls
724 (smtpmail-find-credentials smtpmail-starttls-credentials host port)
725 (member 'starttls supported-extensions)
726 (numberp (process-id process)))
727 (progn
728 (smtpmail-send-command process (format "STARTTLS"))
729 (if (or (null (car (setq response-code (smtpmail-read-response process))))
730 (not (integerp (car response-code)))
731 (>= (car response-code) 400))
732 (throw 'done nil))
733 (starttls-negotiate process)
734 (setq do-starttls nil))
735 (setq do-ehlo nil))))
737 (smtpmail-try-auth-methods process supported-extensions host port)
739 (if (or (member 'onex supported-extensions)
740 (member 'xone supported-extensions))
741 (progn
742 (smtpmail-send-command process (format "ONEX"))
743 (if (or (null (car (setq response-code (smtpmail-read-response process))))
744 (not (integerp (car response-code)))
745 (>= (car response-code) 400))
746 (throw 'done nil))))
748 (if (and smtpmail-debug-verb
749 (or (member 'verb supported-extensions)
750 (member 'xvrb supported-extensions)))
751 (progn
752 (smtpmail-send-command process (format "VERB"))
753 (if (or (null (car (setq response-code (smtpmail-read-response process))))
754 (not (integerp (car response-code)))
755 (>= (car response-code) 400))
756 (throw 'done nil))))
758 (if (member 'xusr supported-extensions)
759 (progn
760 (smtpmail-send-command process (format "XUSR"))
761 (if (or (null (car (setq response-code (smtpmail-read-response process))))
762 (not (integerp (car response-code)))
763 (>= (car response-code) 400))
764 (throw 'done nil))))
766 ;; MAIL FROM:<sender>
767 (let ((size-part
768 (if (or (member 'size supported-extensions)
769 (assoc 'size supported-extensions))
770 (format " SIZE=%d"
771 (with-current-buffer smtpmail-text-buffer
772 ;; size estimate:
773 (+ (- (point-max) (point-min))
774 ;; Add one byte for each change-of-line
775 ;; because of CR-LF representation:
776 (count-lines (point-min) (point-max)))))
777 ""))
778 (body-part
779 (if (member '8bitmime supported-extensions)
780 ;; FIXME:
781 ;; Code should be added here that transforms
782 ;; the contents of the message buffer into
783 ;; something the receiving SMTP can handle.
784 ;; For a receiver that supports 8BITMIME, this
785 ;; may mean converting BINARY to BASE64, or
786 ;; adding Content-Transfer-Encoding and the
787 ;; other MIME headers. The code should also
788 ;; return an indication of what encoding the
789 ;; message buffer is now, i.e. ASCII or
790 ;; 8BITMIME.
791 (if nil
792 " BODY=8BITMIME"
794 "")))
795 ;; (smtpmail-send-command process (format "MAIL FROM:%s@%s" (user-login-name) (smtpmail-fqdn)))
796 (smtpmail-send-command process (format "MAIL FROM:<%s>%s%s"
797 envelope-from
798 size-part
799 body-part))
801 (if (or (null (car (setq response-code (smtpmail-read-response process))))
802 (not (integerp (car response-code)))
803 (>= (car response-code) 400))
804 (throw 'done nil)))
806 ;; RCPT TO:<recipient>
807 (let ((n 0))
808 (while (not (null (nth n recipient)))
809 (smtpmail-send-command process (format "RCPT TO:<%s>" (smtpmail-maybe-append-domain (nth n recipient))))
810 (setq n (1+ n))
812 (setq response-code (smtpmail-read-response process))
813 (if (or (null (car response-code))
814 (not (integerp (car response-code)))
815 (>= (car response-code) 400))
816 (throw 'done nil))))
818 ;; DATA
819 (smtpmail-send-command process "DATA")
821 (if (or (null (car (setq response-code (smtpmail-read-response process))))
822 (not (integerp (car response-code)))
823 (>= (car response-code) 400))
824 (throw 'done nil))
826 ;; Mail contents
827 (smtpmail-send-data process smtpmail-text-buffer)
829 ;; DATA end "."
830 (smtpmail-send-command process ".")
832 (if (or (null (car (setq response-code (smtpmail-read-response process))))
833 (not (integerp (car response-code)))
834 (>= (car response-code) 400))
835 (throw 'done nil))
837 ;; QUIT
838 ;; (smtpmail-send-command process "QUIT")
839 ;; (and (null (car (smtpmail-read-response process)))
840 ;; (throw 'done nil))
842 (if process
843 (with-current-buffer (process-buffer process)
844 (smtpmail-send-command process "QUIT")
845 (smtpmail-read-response process)
847 ;; (if (or (null (car (setq response-code (smtpmail-read-response process))))
848 ;; (not (integerp (car response-code)))
849 ;; (>= (car response-code) 400))
850 ;; (throw 'done nil))
851 (delete-process process)
852 (unless smtpmail-debug-info
853 (kill-buffer process-buffer)))))))
856 (defun smtpmail-process-filter (process output)
857 (with-current-buffer (process-buffer process)
858 (goto-char (point-max))
859 (insert output)))
861 (defun smtpmail-read-response (process)
862 (let ((case-fold-search nil)
863 (response-strings nil)
864 (response-continue t)
865 (return-value '(nil ()))
866 match-end)
867 (catch 'done
868 (while response-continue
869 (goto-char smtpmail-read-point)
870 (while (not (search-forward "\r\n" nil t))
871 (unless (memq (process-status process) '(open run))
872 (throw 'done nil))
873 (accept-process-output process)
874 (goto-char smtpmail-read-point))
876 (setq match-end (point))
877 (setq response-strings
878 (cons (buffer-substring smtpmail-read-point (- match-end 2))
879 response-strings))
881 (goto-char smtpmail-read-point)
882 (if (looking-at "[0-9]+ ")
883 (let ((begin (match-beginning 0))
884 (end (match-end 0)))
885 (if smtpmail-debug-info
886 (message "%s" (car response-strings)))
888 (setq smtpmail-read-point match-end)
890 ;; ignore lines that start with "0"
891 (if (looking-at "0[0-9]+ ")
893 (setq response-continue nil)
894 (setq return-value
895 (cons (string-to-number
896 (buffer-substring begin end))
897 (nreverse response-strings)))))
899 (if (looking-at "[0-9]+-")
900 (progn (if smtpmail-debug-info
901 (message "%s" (car response-strings)))
902 (setq smtpmail-read-point match-end)
903 (setq response-continue t))
904 (progn
905 (setq smtpmail-read-point match-end)
906 (setq response-continue nil)
907 (setq return-value
908 (cons nil (nreverse response-strings)))))))
909 (setq smtpmail-read-point match-end))
910 return-value))
913 (defun smtpmail-send-command (process command)
914 (goto-char (point-max))
915 (if (= (aref command 0) ?P)
916 (insert "PASS <omitted>\r\n")
917 (insert command "\r\n"))
918 (setq smtpmail-read-point (point))
919 (process-send-string process command)
920 (process-send-string process "\r\n"))
922 (defun smtpmail-send-data-1 (process data)
923 (goto-char (point-max))
925 (if (and (multibyte-string-p data)
926 smtpmail-code-conv-from)
927 (setq data (string-as-multibyte
928 (encode-coding-string data smtpmail-code-conv-from))))
930 (if smtpmail-debug-info
931 (insert data "\r\n"))
933 (setq smtpmail-read-point (point))
934 ;; Escape "." at start of a line
935 (if (eq (string-to-char data) ?.)
936 (process-send-string process "."))
937 (process-send-string process data)
938 (process-send-string process "\r\n"))
940 (defun smtpmail-send-data (process buffer)
941 (let ((data-continue t) sending-data)
942 (with-current-buffer buffer
943 (goto-char (point-min)))
944 (while data-continue
945 (with-current-buffer buffer
946 (setq sending-data (buffer-substring (point-at-bol) (point-at-eol)))
947 (end-of-line 2)
948 (setq data-continue (not (eobp))))
949 (smtpmail-send-data-1 process sending-data))))
951 (defun smtpmail-deduce-address-list (smtpmail-text-buffer header-start header-end)
952 "Get address list suitable for smtp RCPT TO: <address>."
953 (unwind-protect
954 (with-current-buffer smtpmail-address-buffer
955 (erase-buffer)
956 (let ((case-fold-search t)
957 (simple-address-list "")
958 this-line
959 this-line-end
960 addr-regexp)
961 (insert-buffer-substring smtpmail-text-buffer header-start header-end)
962 (goto-char (point-min))
963 ;; RESENT-* fields should stop processing of regular fields.
964 (save-excursion
965 (setq addr-regexp
966 (if (re-search-forward "^Resent-\\(to\\|cc\\|bcc\\):"
967 header-end t)
968 "^Resent-\\(to\\|cc\\|bcc\\):"
969 "^\\(To:\\|Cc:\\|Bcc:\\)")))
971 (while (re-search-forward addr-regexp header-end t)
972 (replace-match "")
973 (setq this-line (match-beginning 0))
974 (forward-line 1)
975 ;; get any continuation lines
976 (while (and (looking-at "^[ \t]+") (< (point) header-end))
977 (forward-line 1))
978 (setq this-line-end (point-marker))
979 (setq simple-address-list
980 (concat simple-address-list " "
981 (mail-strip-quoted-names (buffer-substring this-line this-line-end)))))
982 (erase-buffer)
983 (insert " " simple-address-list "\n")
984 (subst-char-in-region (point-min) (point-max) 10 ? t) ; newline --> blank
985 (subst-char-in-region (point-min) (point-max) ?, ? t) ; comma --> blank
986 (subst-char-in-region (point-min) (point-max) 9 ? t) ; tab --> blank
988 (goto-char (point-min))
989 ;; tidyness in case hook is not robust when it looks at this
990 (while (re-search-forward "[ \t]+" header-end t) (replace-match " "))
992 (goto-char (point-min))
993 (let (recipient-address-list)
994 (while (re-search-forward " \\([^ ]+\\) " (point-max) t)
995 (backward-char 1)
996 (setq recipient-address-list (cons (buffer-substring (match-beginning 1) (match-end 1))
997 recipient-address-list)))
998 (setq smtpmail-recipient-address-list recipient-address-list))))))
1000 (defun smtpmail-do-bcc (header-end)
1001 "Delete [Resent-]BCC: and their continuation lines from the header area.
1002 There may be multiple BCC: lines, and each may have arbitrarily
1003 many continuation lines."
1004 (let ((case-fold-search t))
1005 (save-excursion
1006 (goto-char (point-min))
1007 ;; iterate over all BCC: lines
1008 (while (re-search-forward "^\\(RESENT-\\)?BCC:" header-end t)
1009 (delete-region (match-beginning 0)
1010 (progn (forward-line 1) (point)))
1011 ;; get rid of any continuation lines
1012 (while (and (looking-at "^[ \t].*\n") (< (point) header-end))
1013 (replace-match ""))))))
1015 (provide 'smtpmail)
1017 ;;; smtpmail.el ends here