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