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