* src/alloc.c: Avoid O(N²) complexity when unchaining markers (bug#24548).
[emacs.git] / lisp / mail / smtpmail.el
blob403a5c355187424dd6bc021731a0af4568df81c1
1 ;;; smtpmail.el --- simple SMTP protocol (RFC 821) for sending mail -*- lexical-binding:t -*-
3 ;; Copyright (C) 1995-1996, 2001-2018 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 <https://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 (defvar smtpmail-auth-supported '(cram-md5 plain login)
183 "List of supported SMTP AUTH mechanisms.
184 The list is in preference order.
185 Every element should have a matching `cl-defmethod' for
186 for `smtpmail-try-auth-method'.")
188 (defvar smtpmail-mail-address nil
189 "Value to use for envelope-from address for mail from ambient buffer.")
191 ;;;###autoload
192 (defun smtpmail-send-it ()
193 (let ((errbuf (if mail-interactive
194 (generate-new-buffer " smtpmail errors")
196 (tembuf (generate-new-buffer " smtpmail temp"))
197 (case-fold-search nil)
198 delimline
199 result
200 (mailbuf (current-buffer))
201 ;; Examine this variable now, so that
202 ;; local binding in the mail buffer will take effect.
203 (smtpmail-mail-address
204 (or (and mail-specify-envelope-from (mail-envelope-from))
205 (let ((from (mail-fetch-field "from")))
206 (and from
207 (cadr (mail-extract-address-components from))))
208 (smtpmail-user-mail-address)))
209 (smtpmail-code-conv-from
210 (if enable-multibyte-characters
211 (let ((sendmail-coding-system smtpmail-code-conv-from))
212 (select-message-coding-system)))))
213 (unwind-protect
214 (with-current-buffer tembuf
215 (erase-buffer)
216 ;; Use the same `buffer-file-coding-system' as in the mail
217 ;; buffer, otherwise any `write-region' invocations (e.g., in
218 ;; mail-do-fcc below) will annoy with asking for a suitable
219 ;; encoding.
220 (set-buffer-file-coding-system smtpmail-code-conv-from nil t)
221 (insert-buffer-substring mailbuf)
222 (goto-char (point-max))
223 ;; require one newline at the end.
224 (or (= (preceding-char) ?\n)
225 (insert ?\n))
226 ;; Change header-delimiter to be what sendmail expects.
227 (mail-sendmail-undelimit-header)
228 (setq delimline (point-marker))
229 ;; (sendmail-synch-aliases)
230 (if mail-aliases
231 (expand-mail-aliases (point-min) delimline))
232 (goto-char (point-min))
233 ;; ignore any blank lines in the header
234 (while (and (re-search-forward "\n\n\n*" delimline t)
235 (< (point) delimline))
236 (replace-match "\n"))
237 (let ((case-fold-search t))
238 ;; We used to process Resent-... headers here,
239 ;; but it was not done properly, and the job
240 ;; is done correctly in `smtpmail-deduce-address-list'.
241 ;; Don't send out a blank subject line
242 (goto-char (point-min))
243 (if (re-search-forward "^Subject:\\([ \t]*\n\\)+\\b" delimline t)
244 (replace-match "")
245 ;; This one matches a Subject just before the header delimiter.
246 (if (and (re-search-forward "^Subject:\\([ \t]*\n\\)+" delimline t)
247 (= (match-end 0) delimline))
248 (replace-match "")))
249 ;; Put the "From:" field in unless for some odd reason
250 ;; they put one in themselves.
251 (goto-char (point-min))
252 (if (not (re-search-forward "^From:" delimline t))
253 (let* ((login smtpmail-mail-address)
254 (fullname (user-full-name)))
255 (cond ((eq mail-from-style 'angles)
256 (insert "From: " fullname)
257 (let ((fullname-start (+ (point-min) 6))
258 (fullname-end (point-marker)))
259 (goto-char fullname-start)
260 ;; Look for a character that cannot appear unquoted
261 ;; according to RFC 822.
262 (if (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]"
263 fullname-end 1)
264 (progn
265 ;; Quote fullname, escaping specials.
266 (goto-char fullname-start)
267 (insert "\"")
268 (while (re-search-forward "[\"\\]"
269 fullname-end 1)
270 (replace-match "\\\\\\&" t))
271 (insert "\""))))
272 (insert " <" login ">\n"))
273 ((eq mail-from-style 'parens)
274 (insert "From: " login " (")
275 (let ((fullname-start (point)))
276 (insert fullname)
277 (let ((fullname-end (point-marker)))
278 (goto-char fullname-start)
279 ;; RFC 822 says \ and nonmatching parentheses
280 ;; must be escaped in comments.
281 ;; Escape every instance of ()\ ...
282 (while (re-search-forward "[()\\]" fullname-end 1)
283 (replace-match "\\\\\\&" t))
284 ;; ... then undo escaping of matching parentheses,
285 ;; including matching nested parentheses.
286 (goto-char fullname-start)
287 (while (re-search-forward
288 "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
289 fullname-end 1)
290 (replace-match "\\1(\\3)" t)
291 (goto-char fullname-start))))
292 (insert ")\n"))
293 ((null mail-from-style)
294 (insert "From: " login "\n")))))
295 ;; Insert a `Message-Id:' field if there isn't one yet.
296 (goto-char (point-min))
297 (unless (re-search-forward "^Message-Id:" delimline t)
298 (insert "Message-Id: " (message-make-message-id) "\n"))
299 ;; Insert a `Date:' field if there isn't one yet.
300 (goto-char (point-min))
301 (unless (re-search-forward "^Date:" delimline t)
302 (insert "Date: " (message-make-date) "\n"))
303 ;; Possibly add a MIME header for the current coding system
304 (let (charset)
305 (goto-char (point-min))
306 (and (eq mail-send-nonascii 'mime)
307 (not (re-search-forward "^MIME-version:" delimline t))
308 (progn (skip-chars-forward "\0-\177")
309 (/= (point) (point-max)))
310 smtpmail-code-conv-from
311 (setq charset
312 (coding-system-get smtpmail-code-conv-from
313 'mime-charset))
314 (goto-char delimline)
315 (insert "MIME-version: 1.0\n"
316 "Content-type: text/plain; charset="
317 (symbol-name charset)
318 "\nContent-Transfer-Encoding: 8bit\n")))
319 ;; Insert an extra newline if we need it to work around
320 ;; Sun's bug that swallows newlines.
321 (goto-char (1+ delimline))
322 (if (eval mail-mailer-swallows-blank-line)
323 (newline))
324 ;; Find and handle any FCC fields.
325 (goto-char (point-min))
326 (if (re-search-forward "^FCC:" delimline t)
327 ;; Force `mail-do-fcc' to use the encoding of the mail
328 ;; buffer to encode outgoing messages on FCC files.
329 (let ((coding-system-for-write
330 ;; mbox files must have Unix EOLs.
331 (coding-system-change-eol-conversion
332 smtpmail-code-conv-from 'unix)))
333 (mail-do-fcc delimline)))
334 (if mail-interactive
335 (with-current-buffer errbuf
336 (erase-buffer))))
337 ;; Encode the header according to RFC2047.
338 (mail-encode-header (point-min) delimline)
340 (setq smtpmail-address-buffer (generate-new-buffer "*smtp-mail*"))
341 (setq smtpmail-recipient-address-list
342 (smtpmail-deduce-address-list tembuf (point-min) delimline))
343 (kill-buffer smtpmail-address-buffer)
345 (smtpmail-do-bcc delimline)
346 ;; Send or queue
347 (if (not smtpmail-queue-mail)
348 (if (not (null smtpmail-recipient-address-list))
349 (when (setq result
350 (smtpmail-via-smtp
351 smtpmail-recipient-address-list tembuf))
352 (error "Sending failed: %s" result))
353 (error "Sending failed; no recipients"))
354 (let* ((file-data
355 (expand-file-name
356 (format "%s_%i"
357 (format-time-string "%Y-%m-%d_%H:%M:%S")
358 (setq smtpmail-queue-counter
359 (1+ smtpmail-queue-counter)))
360 smtpmail-queue-dir))
361 (file-data (convert-standard-filename file-data))
362 (file-elisp (concat file-data ".el"))
363 (buffer-data (create-file-buffer file-data))
364 (buffer-elisp (create-file-buffer file-elisp))
365 (buffer-scratch "*queue-mail*"))
366 (unless (file-exists-p smtpmail-queue-dir)
367 (make-directory smtpmail-queue-dir t))
368 (with-current-buffer buffer-data
369 (erase-buffer)
370 (set-buffer-file-coding-system
371 ;; We will be reading the file with no-conversion in
372 ;; smtpmail-send-queued-mail below, so write it out
373 ;; with Unix EOLs.
374 (coding-system-change-eol-conversion
375 (or smtpmail-code-conv-from 'undecided)
376 'unix)
377 nil t)
378 (insert-buffer-substring tembuf)
379 (write-file file-data)
380 (set-buffer buffer-elisp)
381 (erase-buffer)
382 (insert (concat
383 "(setq smtpmail-recipient-address-list '"
384 (prin1-to-string smtpmail-recipient-address-list)
385 ")\n"))
386 (write-file file-elisp)
387 (set-buffer (generate-new-buffer buffer-scratch))
388 (insert (concat file-data "\n"))
389 (append-to-file (point-min)
390 (point-max)
391 (expand-file-name smtpmail-queue-index-file
392 smtpmail-queue-dir)))
393 (kill-buffer buffer-scratch)
394 (kill-buffer buffer-data)
395 (kill-buffer buffer-elisp))))
396 (kill-buffer tembuf)
397 (if (bufferp errbuf)
398 (kill-buffer errbuf)))))
400 ;;;###autoload
401 (defun smtpmail-send-queued-mail ()
402 "Send mail that was queued as a result of setting `smtpmail-queue-mail'."
403 (interactive)
404 (with-temp-buffer
405 ;; Get index, get first mail, send it, update index, get second
406 ;; mail, send it, etc...
407 (let ((file-msg "")
408 (qfile (expand-file-name smtpmail-queue-index-file
409 smtpmail-queue-dir))
410 result)
411 (insert-file-contents qfile)
412 (goto-char (point-min))
413 (while (not (eobp))
414 (setq file-msg (buffer-substring (point) (line-end-position)))
415 (load file-msg)
416 ;; Insert the message literally: it is already encoded as per
417 ;; the MIME headers, and code conversions might guess the
418 ;; encoding wrongly.
419 (with-temp-buffer
420 (let ((coding-system-for-read 'no-conversion))
421 (insert-file-contents file-msg))
422 (let ((smtpmail-mail-address
423 (or (and mail-specify-envelope-from (mail-envelope-from))
424 user-mail-address)))
425 (if (not (null smtpmail-recipient-address-list))
426 (when (setq result (smtpmail-via-smtp
427 smtpmail-recipient-address-list
428 (current-buffer)))
429 (error "Sending failed: %s" result))
430 (error "Sending failed; no recipients"))))
431 (delete-file file-msg)
432 (delete-file (concat file-msg ".el"))
433 (delete-region (point-at-bol) (point-at-bol 2)))
434 (write-region (point-min) (point-max) qfile))))
436 (defun smtpmail-fqdn ()
437 (if smtpmail-local-domain
438 (concat (system-name) "." smtpmail-local-domain)
439 (system-name)))
441 (defsubst smtpmail-cred-server (cred)
442 (nth 0 cred))
444 (defsubst smtpmail-cred-port (cred)
445 (nth 1 cred))
447 (defsubst smtpmail-cred-key (cred)
448 (nth 2 cred))
450 (defsubst smtpmail-cred-user (cred)
451 (nth 2 cred))
453 (defsubst smtpmail-cred-cert (cred)
454 (nth 3 cred))
456 (defsubst smtpmail-cred-passwd (cred)
457 (nth 3 cred))
459 (defun smtpmail-find-credentials (cred server port)
460 (catch 'done
461 (let ((l cred) el)
462 (while (setq el (pop l))
463 (when (and (equal server (smtpmail-cred-server el))
464 (equal port (smtpmail-cred-port el)))
465 (throw 'done el))))))
467 (defun smtpmail-maybe-append-domain (recipient)
468 (if (or (not smtpmail-sendto-domain)
469 (string-match "@" recipient))
470 recipient
471 (concat recipient "@" smtpmail-sendto-domain)))
473 (defun smtpmail-intersection (list1 list2)
474 (let ((result nil))
475 (dolist (el2 list2)
476 (when (memq el2 list1)
477 (push el2 result)))
478 (nreverse result)))
480 (defun smtpmail-command-or-throw (process string &optional code)
481 (let (ret)
482 (smtpmail-send-command process string)
483 (unless (smtpmail-ok-p (setq ret (smtpmail-read-response process))
484 code)
485 (throw 'done (format "%s in response to %s"
486 (smtpmail-response-text ret)
487 string)))
488 ret))
490 (defun smtpmail-try-auth-methods (process supported-extensions host port
491 &optional ask-for-password)
492 (setq port
493 (if port
494 (format "%s" port)
495 "smtp"))
496 (let* ((mechs (cdr-safe (assoc 'auth supported-extensions)))
497 (mech (car (smtpmail-intersection mechs smtpmail-auth-supported)))
498 (auth-source-creation-prompts
499 '((user . "SMTP user name for %h: ")
500 (secret . "SMTP password for %u@%h: ")))
501 (auth-info (car
502 (auth-source-search
503 :host host
504 :port port
505 :user smtpmail-smtp-user
506 :max 1
507 :require (and ask-for-password
508 '(:user :secret))
509 :create ask-for-password)))
510 (user (plist-get auth-info :user))
511 (password (plist-get auth-info :secret))
512 (save-function (and ask-for-password
513 (plist-get auth-info :save-function))))
514 (when (functionp password)
515 (setq password (funcall password)))
516 (when (and user
517 (not password))
518 ;; The user has stored the user name, but not the password, so
519 ;; ask for the password, even if we're not forcing that through
520 ;; `ask-for-password'.
521 (setq auth-info
522 (car
523 (auth-source-search
524 :max 1
525 :host host
526 :port port
527 :user smtpmail-smtp-user
528 :require '(:user :secret)
529 :create t))
530 password (plist-get auth-info :secret)))
531 (when (functionp password)
532 (setq password (funcall password)))
533 (let ((result (catch 'done
534 (if (and mech user password)
535 (smtpmail-try-auth-method process mech user password)
536 ;; No mechanism, or no credentials.
537 mech))))
538 (if (stringp result)
539 (progn
540 (auth-source-forget+ :host host :port port)
541 (throw 'done result))
542 (when save-function
543 (funcall save-function))
544 result))))
546 (cl-defgeneric smtpmail-try-auth-method (_process mech _user _password)
547 "Perform authentication of type MECH for USER with PASSWORD.
548 MECH should be one of the values in `smtpmail-auth-supported'.
549 USER and PASSWORD should be non-nil."
550 (error "Mechanism %S not implemented" mech))
552 (cl-defmethod smtpmail-try-auth-method
553 (process (_mech (eql cram-md5)) user password)
554 (let ((ret (smtpmail-command-or-throw process "AUTH CRAM-MD5")))
555 (when (eq (car ret) 334)
556 (let* ((challenge (substring (cadr ret) 4))
557 (decoded (base64-decode-string challenge))
558 (hash (rfc2104-hash 'md5 64 16 password decoded))
559 (response (concat user " " hash))
560 ;; Osamu Yamane <yamane@green.ocn.ne.jp>:
561 ;; SMTP auth fails because the SMTP server identifies
562 ;; only the first part of the string (delimited by
563 ;; new line characters) as a response from the
564 ;; client, and the rest as distinct commands.
566 ;; In my case, the response string is 80 characters
567 ;; long. Without the no-line-break option for
568 ;; `base64-encode-string', only the first 76 characters
569 ;; are taken as a response to the server, and the
570 ;; authentication fails.
571 (encoded (base64-encode-string response t)))
572 (smtpmail-command-or-throw process encoded)))))
574 (cl-defmethod smtpmail-try-auth-method
575 (process (_mech (eql login)) user password)
576 (smtpmail-command-or-throw process "AUTH LOGIN")
577 (smtpmail-command-or-throw process (base64-encode-string user t))
578 (smtpmail-command-or-throw process (base64-encode-string password t)))
580 (cl-defmethod smtpmail-try-auth-method
581 (process (_mech (eql plain)) user password)
582 ;; We used to send an empty initial request, and wait for an
583 ;; empty response, and then send the password, but this
584 ;; violate a SHOULD in RFC 2222 paragraph 5.1. Note that this
585 ;; is not sent if the server did not advertise AUTH PLAIN in
586 ;; the EHLO response. See RFC 2554 for more info.
587 (smtpmail-command-or-throw
588 process
589 (concat "AUTH PLAIN "
590 (base64-encode-string (concat "\0" user "\0" password) t))
591 235))
593 (defun smtpmail-response-code (string)
594 (when string
595 (with-temp-buffer
596 (insert string)
597 (goto-char (point-min))
598 (and (re-search-forward "^\\([0-9]+\\) " nil t)
599 (string-to-number (match-string 1))))))
601 (defun smtpmail-ok-p (response &optional code)
602 (and (car response)
603 (integerp (car response))
604 (< (car response) 400)
605 (or (null code)
606 (= code (car response)))))
608 (defun smtpmail-response-text (response)
609 (mapconcat 'identity (cdr response) "\n"))
611 (defun smtpmail-query-smtp-server ()
612 "Query for an SMTP server and try to contact it.
613 If the contact succeeds, customizes and saves `smtpmail-smtp-server'
614 and `smtpmail-smtp-service'. This tries standard SMTP ports, and if
615 none works asks you to supply one. If you know that you need to use
616 a non-standard port, you can set `smtpmail-smtp-service' in advance.
617 Returns an error if the server cannot be contacted."
618 (let ((server (read-string "Outgoing SMTP mail server: "))
619 (ports '(25 587))
620 stream port prompted)
621 (when (and smtpmail-smtp-service
622 (not (member smtpmail-smtp-service ports)))
623 (push smtpmail-smtp-service ports))
624 (while (and (not smtpmail-smtp-server)
625 (setq port (pop ports)))
626 (if (not (setq stream (condition-case ()
627 (open-network-stream "smtp" nil server port)
628 (quit nil)
629 (error nil))))
630 ;; We've used up the list of default ports, so query the user.
631 (when (and (not ports)
632 (not prompted))
633 (push (read-number (format "Port number to use when contacting %s? "
634 server))
635 ports)
636 (setq prompted t))
637 (customize-save-variable 'smtpmail-smtp-server server)
638 (customize-save-variable 'smtpmail-smtp-service port)
639 (delete-process stream)))
640 (unless smtpmail-smtp-server
641 (error "Couldn't contact an SMTP server"))))
643 (defun smtpmail-user-mail-address ()
644 "Return `user-mail-address' if it's a valid email address."
645 (and user-mail-address
646 (let ((parts (split-string user-mail-address "@")))
647 (and (= (length parts) 2)
648 ;; There's a dot in the domain name.
649 (string-match "\\." (cadr parts))
650 user-mail-address))))
652 (defun smtpmail-via-smtp (recipient smtpmail-text-buffer
653 &optional ask-for-password)
654 (unless smtpmail-smtp-server
655 (smtpmail-query-smtp-server))
656 (let ((process nil)
657 (host (or smtpmail-smtp-server
658 (error "`smtpmail-smtp-server' not defined")))
659 (port smtpmail-smtp-service)
660 ;; `smtpmail-mail-address' should be set to the appropriate
661 ;; buffer-local value by the caller, but in case not:
662 (envelope-from
663 (or smtpmail-mail-address
664 (and mail-specify-envelope-from
665 (mail-envelope-from))
666 (let ((from (mail-fetch-field "from")))
667 (and from
668 (cadr (mail-extract-address-components from))))
669 (smtpmail-user-mail-address)))
670 process-buffer
671 result
672 auth-mechanisms
673 (supported-extensions '()))
674 (unwind-protect
675 (catch 'done
676 ;; get or create the trace buffer
677 (setq process-buffer
678 (get-buffer-create
679 (format "*trace of SMTP session to %s*" host)))
681 ;; clear the trace buffer of old output
682 (with-current-buffer process-buffer
683 (setq buffer-undo-list t)
684 (erase-buffer))
686 ;; Open the connection to the server.
687 ;; FIXME: Should we use raw-text-dos coding system to handle the r\n
688 ;; for us?
689 (let ((coding-system-for-read 'binary)
690 (coding-system-for-write 'binary))
691 (setq result
692 (open-network-stream
693 "smtpmail" process-buffer host port
694 :type smtpmail-stream-type
695 :return-list t
696 :warn-unless-encrypted ask-for-password
697 :capability-command (format "EHLO %s\r\n" (smtpmail-fqdn))
698 :end-of-command "^[0-9]+ .*\r\n"
699 :success "^2.*\n"
700 :always-query-capabilities t
701 :starttls-function
702 (lambda (capabilities)
703 (and (string-match "[ -]STARTTLS" capabilities)
704 "STARTTLS\r\n"))
705 :client-certificate t
706 :use-starttls-if-possible t)))
708 ;; If we couldn't access the server at all, we give up.
709 (unless (setq process (car result))
710 (throw 'done (if (plist-get (cdr result) :error)
711 (plist-get (cdr result) :error)
712 "Unable to contact server")))
714 ;; set the send-filter
715 (set-process-filter process 'smtpmail-process-filter)
717 (let* ((greeting (plist-get (cdr result) :greeting))
718 (code (smtpmail-response-code greeting)))
719 (unless code
720 (throw 'done (format "No greeting: %s" greeting)))
721 (when (>= code 400)
722 (throw 'done (format "Connection not allowed: %s" greeting))))
724 (with-current-buffer process-buffer
725 (set-process-coding-system process 'raw-text-unix 'raw-text-unix)
726 (setq-local smtpmail-read-point (point-min))
728 (let* ((capabilities (plist-get (cdr result) :capabilities))
729 (code (smtpmail-response-code capabilities)))
730 (if (or (null code)
731 (>= code 400))
732 ;; The server didn't accept EHLO, so we fall back on HELO.
733 (smtpmail-command-or-throw
734 process (format "HELO %s" (smtpmail-fqdn)))
735 ;; EHLO was successful, so we parse the extensions.
736 (dolist (line (delete
738 (split-string
739 (plist-get (cdr result) :capabilities)
740 "\r\n")))
741 (let ((name
742 (with-case-table ascii-case-table ;FIXME: Why?
743 (mapcar (lambda (s) (intern (downcase s)))
744 (split-string (substring line 4) "[ ]")))))
745 (when (= (length name) 1)
746 (setq name (car name)))
747 (when name
748 (cond ((memq (if (consp name) (car name) name)
749 '(verb xvrb 8bitmime onex xone
750 expn size dsn etrn
751 enhancedstatuscodes
752 help xusr
753 auth=login auth starttls))
754 (setq supported-extensions
755 (cons name supported-extensions)))
756 (smtpmail-warn-about-unknown-extensions
757 (message "Unknown extension %s" name))))))))
759 (setq auth-mechanisms
760 (smtpmail-try-auth-methods
761 process supported-extensions host port
762 ask-for-password))
764 (when (or (member 'onex supported-extensions)
765 (member 'xone supported-extensions))
766 (smtpmail-command-or-throw process (format "ONEX")))
768 (when (and smtpmail-debug-verb
769 (or (member 'verb supported-extensions)
770 (member 'xvrb supported-extensions)))
771 (smtpmail-command-or-throw process (format "VERB")))
773 (when (member 'xusr supported-extensions)
774 (smtpmail-command-or-throw process (format "XUSR")))
776 ;; MAIL FROM:<sender>
777 (let ((size-part
778 (if (or (member 'size supported-extensions)
779 (assoc 'size supported-extensions))
780 (format " SIZE=%d"
781 (with-current-buffer smtpmail-text-buffer
782 ;; size estimate:
783 (+ (- (point-max) (point-min))
784 ;; Add one byte for each change-of-line
785 ;; because of CR-LF representation:
786 (count-lines (point-min) (point-max)))))
787 ""))
788 (body-part
789 (if (member '8bitmime supported-extensions)
790 ;; FIXME:
791 ;; Code should be added here that transforms
792 ;; the contents of the message buffer into
793 ;; something the receiving SMTP can handle.
794 ;; For a receiver that supports 8BITMIME, this
795 ;; may mean converting BINARY to BASE64, or
796 ;; adding Content-Transfer-Encoding and the
797 ;; other MIME headers. The code should also
798 ;; return an indication of what encoding the
799 ;; message buffer is now, i.e. ASCII or
800 ;; 8BITMIME.
801 (if nil
802 " BODY=8BITMIME"
804 "")))
805 (smtpmail-send-command
806 process (format "MAIL FROM:<%s>%s%s"
807 envelope-from size-part body-part))
808 (cond
809 ((smtpmail-ok-p (setq result (smtpmail-read-response process)))
810 ;; Success.
812 ((and auth-mechanisms
813 (not ask-for-password)
814 (eq (car result) 530))
815 ;; We got a "530 auth required", so we close and try
816 ;; again, this time asking the user for a password.
817 ;; We ignore any errors here, because some MTAs just
818 ;; close the connection immediately after giving the
819 ;; error message.
820 (ignore-errors
821 (smtpmail-send-command process "QUIT")
822 (smtpmail-read-response process))
823 (delete-process process)
824 (setq process nil)
825 (throw 'done
826 (smtpmail-via-smtp recipient smtpmail-text-buffer t)))
828 ;; Return the error code.
829 (throw 'done
830 (smtpmail-response-text result)))))
832 ;; RCPT TO:<recipient>
833 (let ((n 0))
834 (while (not (null (nth n recipient)))
835 (smtpmail-send-command
836 process (format "RCPT TO:<%s>"
837 (smtpmail-maybe-append-domain
838 (nth n recipient))))
839 (cond
840 ((smtpmail-ok-p (setq result (smtpmail-read-response process)))
841 ;; Success.
842 nil)
843 ((and auth-mechanisms
844 (not ask-for-password)
845 (integerp (car result))
846 (>= (car result) 550)
847 (<= (car result) 554))
848 ;; We got a "550 relay not permitted" (or the like),
849 ;; and the server accepts credentials, so we try
850 ;; again, but ask for a password first.
851 (smtpmail-send-command process "QUIT")
852 (smtpmail-read-response process)
853 (delete-process process)
854 (setq process nil)
855 (throw 'done
856 (smtpmail-via-smtp recipient smtpmail-text-buffer t)))
858 ;; Return the error code.
859 (throw 'done
860 (smtpmail-response-text result))))
861 (setq n (1+ n))))
863 ;; Send the contents.
864 (smtpmail-command-or-throw process "DATA")
865 (smtpmail-send-data process smtpmail-text-buffer)
866 ;; Return success.
867 nil))
868 (when (and process
869 (buffer-live-p process-buffer))
870 (with-current-buffer (process-buffer process)
871 (smtpmail-send-command process "QUIT")
872 (smtpmail-read-response process)
873 (delete-process process)
874 (unless smtpmail-debug-info
875 (kill-buffer process-buffer)))))))
878 (defun smtpmail-process-filter (process output)
879 (with-current-buffer (process-buffer process)
880 (goto-char (point-max))
881 (insert output)
882 (set-marker (process-mark process) (point))))
884 (defun smtpmail-read-response (process)
885 (let ((case-fold-search nil)
886 (response-strings nil)
887 (response-continue t)
888 (return-value '(nil ()))
889 match-end)
890 (catch 'done
891 (while response-continue
892 (goto-char smtpmail-read-point)
893 (while (not (search-forward "\r\n" nil t))
894 (unless (memq (process-status process) '(open run))
895 (throw 'done nil))
896 (accept-process-output process)
897 (goto-char smtpmail-read-point))
899 (setq match-end (point))
900 (setq response-strings
901 (cons (buffer-substring smtpmail-read-point (- match-end 2))
902 response-strings))
904 (goto-char smtpmail-read-point)
905 (if (looking-at "[0-9]+ ")
906 (let ((begin (match-beginning 0))
907 (end (match-end 0)))
908 (if smtpmail-debug-info
909 (message "%s" (car response-strings)))
911 (setq smtpmail-read-point match-end)
913 ;; ignore lines that start with "0"
914 (if (looking-at "0[0-9]+ ")
916 (setq response-continue nil)
917 (setq return-value
918 (cons (string-to-number
919 (buffer-substring begin end))
920 (nreverse response-strings)))))
922 (if (looking-at "[0-9]+-")
923 (progn (if smtpmail-debug-info
924 (message "%s" (car response-strings)))
925 (setq smtpmail-read-point match-end)
926 (setq response-continue t))
927 (progn
928 (setq smtpmail-read-point match-end)
929 (setq response-continue nil)
930 (setq return-value
931 (cons nil (nreverse response-strings)))))))
932 (setq smtpmail-read-point match-end))
933 return-value))
936 (defun smtpmail-send-command (process command)
937 (goto-char (point-max))
938 (if (string-match "\\`AUTH [A-Z]+ " command)
939 (insert (match-string 0 command) "<omitted>\r\n")
940 (insert command "\r\n"))
941 (setq smtpmail-read-point (point))
942 (process-send-string process (concat command "\r\n")))
944 (defun smtpmail-send-data-1 (process data)
945 (goto-char (point-max))
947 (if (and (multibyte-string-p data)
948 smtpmail-code-conv-from)
949 (setq data (encode-coding-string data smtpmail-code-conv-from)))
951 (if smtpmail-debug-info
952 (insert data "\r\n"))
954 (setq smtpmail-read-point (point))
955 ;; Escape "." at start of a line
956 (if (eq (string-to-char data) ?.)
957 (process-send-string process "."))
958 (process-send-string process data)
959 (process-send-string process "\r\n"))
961 (defun smtpmail-send-data (process buffer)
962 (let ((data-continue t)
963 (pr (with-current-buffer buffer
964 (make-progress-reporter "Sending email "
965 (point-min) (point-max))))
966 sending-data)
967 (with-current-buffer buffer
968 (goto-char (point-min)))
969 (while data-continue
970 (with-current-buffer buffer
971 (progress-reporter-update pr (point))
972 (setq sending-data (buffer-substring (point-at-bol) (point-at-eol)))
973 (end-of-line 2)
974 (setq data-continue (not (eobp))))
975 (smtpmail-send-data-1 process sending-data))
976 ;; DATA end "."
977 (smtpmail-command-or-throw process ".")
978 (progress-reporter-done pr)))
980 (defun smtpmail-deduce-address-list (smtpmail-text-buffer header-start header-end)
981 "Get address list suitable for smtp RCPT TO: <address>."
982 (unwind-protect
983 (with-current-buffer smtpmail-address-buffer
984 (erase-buffer)
985 (let ((case-fold-search t)
986 (simple-address-list "")
987 this-line
988 this-line-end
989 addr-regexp)
990 (insert-buffer-substring smtpmail-text-buffer header-start header-end)
991 (goto-char (point-min))
992 ;; RESENT-* fields should stop processing of regular fields.
993 (save-excursion
994 (setq addr-regexp
995 (if (re-search-forward "^Resent-\\(to\\|cc\\|bcc\\):"
996 header-end t)
997 "^Resent-\\(to\\|cc\\|bcc\\):"
998 "^\\(To:\\|Cc:\\|Bcc:\\)")))
1000 (while (re-search-forward addr-regexp header-end t)
1001 (replace-match "")
1002 (setq this-line (match-beginning 0))
1003 (forward-line 1)
1004 ;; get any continuation lines
1005 (while (and (looking-at "^[ \t]+") (< (point) header-end))
1006 (forward-line 1))
1007 (setq this-line-end (point-marker))
1008 (setq simple-address-list
1009 (concat simple-address-list " "
1010 (mail-strip-quoted-names (buffer-substring this-line this-line-end)))))
1011 (erase-buffer)
1012 (insert " " simple-address-list "\n")
1013 (subst-char-in-region (point-min) (point-max) 10 ? t) ; newline --> blank
1014 (subst-char-in-region (point-min) (point-max) ?, ? t) ; comma --> blank
1015 (subst-char-in-region (point-min) (point-max) 9 ? t) ; tab --> blank
1017 (goto-char (point-min))
1018 ;; tidiness in case hook is not robust when it looks at this
1019 (while (re-search-forward "[ \t]+" header-end t) (replace-match " "))
1021 (goto-char (point-min))
1022 (let (recipient-address-list)
1023 (while (re-search-forward " \\([^ ]+\\) " (point-max) t)
1024 (backward-char 1)
1025 (setq recipient-address-list (cons (buffer-substring (match-beginning 1) (match-end 1))
1026 recipient-address-list)))
1027 (setq smtpmail-recipient-address-list recipient-address-list))))))
1029 (defun smtpmail-do-bcc (header-end)
1030 "Delete [Resent-]BCC: and their continuation lines from the header area.
1031 There may be multiple BCC: lines, and each may have arbitrarily
1032 many continuation lines."
1033 (let ((case-fold-search t))
1034 (save-excursion
1035 (goto-char (point-min))
1036 ;; iterate over all BCC: lines
1037 (while (re-search-forward "^\\(RESENT-\\)?BCC:" header-end t)
1038 (delete-region (match-beginning 0)
1039 (progn (forward-line 1) (point)))
1040 ;; get rid of any continuation lines
1041 (while (and (looking-at "^[ \t].*\n") (< (point) header-end))
1042 (replace-match ""))))))
1044 (provide 'smtpmail)
1046 ;;; smtpmail.el ends here