#! /usr/bin/env python
#
# Copyright (C) 1998 by the Free Software Foundation, Inc.
#
# This program 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
# of the License, or (at your option) any later version.
# 
# This program 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 this program; if not, write to the Free Software 
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

"""Send a message via local SMTP, or queue it if SMTP port is not responding.

The script takes the following protocol on stdin:

 line [1]: sender
 line [2:n+1]: n recipients
 line [n+2]: <empty> - delimiting end of recipients
 line [n+3:]: message content
"""

import sys, os
import paths

from Mailman import mm_cfg
from Mailman import Utils
from Mailman import OutgoingQueue

from Mailman.mm_cfg import SMTP_MAX_RCPTS
from Mailman.Logging.Utils import LogStdErr

LogStdErr("error", "contact_transport")

from_addr = sys.stdin.readline()[:-1]
to_addrs  = []
while 1:
    l = sys.stdin.readline()[:-1]
    if not l:
        break
    to_addrs.append(l)
text = sys.stdin.read()

#
# make sure that not more than SMTP_MAX_RCPTS goes into
# a single smtp delivery
#
addr_chunks = Utils.chunkify(to_addrs, SMTP_MAX_RCPTS)

for to_addrs in addr_chunks:
    try:	
        queue_id = OutgoingQueue.enqueueMessage(from_addr, to_addrs, text)
    except IOError:
        # Log the error event and reraise the exception.
        (exc, exc_msg, exc_tb) = sys.exc_info()
        sys.stderr.write("IOError writing outgoing queue\n\t%s/%s\n"
                         % (str(exc), str(exc_msg)))
        sys.stderr.flush()
        raise exc, exc_msg, exc_tb
    Utils.TrySMTPDelivery(to_addrs, from_addr, text, queue_id)



