Package com.utils

Source Code of com.utils.MailUtil

/**
*  Copyright 2011 Marco Berri - marcoberri@gmail.com
*
*  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.
**/
package com.utils;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

/**
*
* @author marco
*/
public class MailUtil {

    /**
     *
     * @param hostname
     * @param port
     * @param username
     * @param password
     * @param from
     * @param to
     * @param subject
     * @param text
     * @param html
     * @return
     */
    public static boolean sendMail(String hostname, int port, String username, String password, String from, String to, String subject, String text, String html) {
        try {
            if (hostname == null) {
                return false;
            }
            if (to == null) {
                return false;
            }
            String[] tos = to.split(";");
            if (from == null) {
                return false;
            }
            if (subject == null) {
                return false;
            }
            HtmlEmail mail = new HtmlEmail();
            mail.setHostName(hostname);
            if (port == -1) {
                port = 25;
            }

            if(username != null && password != null)
            mail.setAuthentication(username, password);

            mail.setSmtpPort(port);
            mail.setCharset(HtmlEmail.ISO_8859_1);
            for (String t : tos) {
                try {
                    mail.addTo(t, t);
                } catch (EmailException ex) {
                    System.err.print(ex);
                    return false;
                }
            }
            mail.setFrom(from);
            mail.setSubject(subject);
            if (html == null) {
                html = text;
            }

            mail.setHtmlMsg(html);
            mail.setTextMsg(text);
            mail.send();
            return true;
        } catch (EmailException ex) {
            System.err.print(ex);
            return false;
        }




    }
}
TOP

Related Classes of com.utils.MailUtil

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.