;;; cmail-multi-account.el -- use multi accounts

;; Author: ASANO Fumihisa <fasano@mva.biglobe.ne.jp>
;; Keywords: mail
;; Create date: 2001/03/02
;; $Id: cmail-multi-account.el,v 1.1 2002/07/20 23:09:58 tmp Exp $

;; This file is part of cmail (a mail utility for GNU Emacs)

;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published
;; by the Free Software Foundation; either version 2, or (at your
;; option) any later version.

;; This file is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;; General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.

;;; Commentary:
;; Installation:
;;	Put this line in your ~/.emacs
;;		(setq cmail-use-multi-account t
;;		      cmail-smtp-servers '(("foo" . "foo.smtp.server")
;;                                         ("bar" . "bar.smtp.server")))

;;; Code:
(eval-when-compile (require 'cmail-vars))

(require 'advice)
(require 'mail-utils)

(cmail-i18n-defcustom cmail-smtp-servers nil
  ((ja_JP . "*Fromと対応するsmtpサーバのリスト。

 ((<From> . <smtp server>) ... )
 Fromは正規表現で指定する。")
   (en_US . "*From and smtp server.

 ((<From> . <smtp server>) ... )
 From is specified with regexp."))
  :type 'sexp
  :group 'cmail-all-variables
  :group 'cmail-use-multi-account-group)

(defun cmail-select-smtp-server (from)
  "select smtp server.
select smtp server from \"cmail-smtp-servers\"."
  (let ((server nil)
	(result nil)
	(server-list cmail-smtp-servers))
    (setq server (car server-list))
    (setq server-list (cdr server-list))
    (while server
      (if (string-match (car server) from)
	  (setq result (cdr server)
		server nil
		server-list nil)
	(setq server (car server-list))
	(setq server-list (cdr server-list))))
    result))

(defadvice smtp-send-buffer (around cmail-setup-smtp act)
  "setup smtp server infomation before send mail."
  (let* ((from (mail-strip-quoted-names (mail-fetch-field "From")))
	 (server (cmail-select-smtp-server from)))
    (if from
	(setq user-mail-address from
	      sender user-mail-address))
    (if server
	(setq smtp-server server
	      smtp-local-domain server))
    (ad-set-arg 0 sender)
    ad-do-it))

;;;
(run-hooks 'cmail-multi-account-load-hook)
(provide 'cmail-multi-account)

;;; cmail-multi-account.el ends here
