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