/*
 * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the
 * License at http://www.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.mail;

// Java Core
import java.util.ArrayList;
import java.util.Iterator;

// JavaMail API
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;

/**
 * Bundles a number of messages and sends them all at once.
 * Saves the overhead of opening a separate connection to the SMTP
 * server for each individual message.
 *
 * @author Ron Henderson 
 * @version $Id: //core-platform/dev/src/com/arsdigita/mail/MailQueue.java#7 $
 */

public class MailQueue {

    public static final String versionId = "$Id: //core-platform/dev/src/com/arsdigita/mail/MailQueue.java#7 $ by $Author: dennis $, $DateTime: 2004/04/07 16:07:11 $";

    /**
     * A collection of Mail objects to send.
     */

    private ArrayList m_messages;

    /**
     * Creates an empty mail queue.
     */

    public MailQueue() {
        m_messages = new ArrayList();
    }

    /**
     * Adds a mail message to the queue.
     *
     * @param msg the message to add
     */

    public void addMail(Mail msg) {
        m_messages.add(msg);
    }

    /**
     * Gets the number of messages in the queue.
     * @return the number of messages in the queue
     */

    public int getCount() {
        return m_messages.size();
    }

    /**
     * Sends all messages.
     */

    public void send()
        throws MessagingException,
               SendFailedException
    {
        Iterator iter = m_messages.iterator();

        // Grab an instance of the appropriate Mail session.

        Session session = Mail.getSession();

        // Create a Transport for sending messages, connect to it, and
        // ship all of the message off.

        Transport transport = session.getTransport();
        transport.connect();

        while (iter.hasNext()) {
            ((Mail) iter.next()).send(transport);
        }

        transport.close();

        m_messages.clear();
    }
}
