package org.apache.maven.announcement;

import java.io.PrintWriter;
import java.io.Writer;
import java.util.StringTokenizer;

import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
import org.apache.commons.net.smtp.SimpleSMTPHeader;

/* ====================================================================
 *   Copyright 2004 The Apache Software Foundation.
 *
 *   Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 * ====================================================================
 */

/**
 * Send an email message using Jakarta Commons Net
 * 
 * @author Felipe Leme
 * 
 * @version $Id$
 */
public class MailUtils
{
    private static final String ADDRESS_SEPARATOR = ",";

    public static String sendMail(String server, String client,
        String from, String to, String subject, String msg)
    {
        // Check arguments
        if (server == null)
        {
            return "no smtp server configured";
        }
        if (client == null)
        {
            return "no smtp client configured";
        }
        if (to == null)
        {
            return "no to address specified";
        }
        if (from == null)
        {
            return "no from address specified";
        }
        if (msg == null)
        {
            return "no message specified";
        }
        if (subject == null)
        {
            return "no subject specified";
        }

        // create a SMTP connection
        SMTPClient smtpClient = new SMTPClient();
        System.out.println("Connecting to SMTP Server [" + server + "]");
        try
        {
            smtpClient.connect(server);
            // checks the server reply
            int reply = smtpClient.getReplyCode();
            if (!SMTPReply.isPositiveCompletion(reply))
            {
                smtpClient.disconnect();
                return "SMTP server [" + server + "] refused connection.";
            }
            // Login
            smtpClient.login(client);
            // Set the sender and recipient(s)
            smtpClient.setSender(from);
            // parse out the to addresses
            StringTokenizer st = new StringTokenizer(to.toString(),
                    ADDRESS_SEPARATOR);
            while (st.hasMoreTokens())
            {
                smtpClient.addRecipient(st.nextToken().trim());
            }

            System.out.println("Sending message from [" + from + "] to [" 
                + to + "]");

            // Use the SimpleSMTPHeader class to build the header
            Writer clientWriter = smtpClient.sendMessageData();
            if (clientWriter == null)
            {
                return "Could not send data to the SMTP server";
            }
            PrintWriter writer = new PrintWriter(clientWriter);
            SimpleSMTPHeader header = new SimpleSMTPHeader(from, to, subject);

            //NOTE: if would be nice to add some Maven info here
            //            header.addHeaderField("Organization", "xxx");

            // Write the header to the SMTP Server
            writer.write(header.toString());

            // Write the body of the message
            writer.write(msg);

            // Close the writer
            writer.close();
            if (!smtpClient.completePendingCommand())
            {
                return "Could not send the SMTP message";
            }

            // Logout from the e-mail server (QUIT)
            smtpClient.logout();

            // Close the connection
            smtpClient.disconnect();

            // everything is fine
            return "ok";
        } 
        catch (Exception e)
        {
            e.printStackTrace();
            return e.getMessage();
        }
    }

}