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