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