enviocorreo.EnviadorCorreo.java Source code

Java tutorial

Introduction

Here is the source code for enviocorreo.EnviadorCorreo.java

Source

/*
BSD 3-Clause License
    
Copyright (c) 2016, Universidad de Costa Rica
All rights reserved.
    
Elaborado por Ing. Adrin Alvarado Ramrez, a.alvarado.r@gmail.com
    
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
    
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
    
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
    
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
    
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package enviocorreo;

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

/**
 * Clase que provee la funcionalidad para el envo de correo electrnico. Se usa
 * un SMTP de gmail o un SMTP de la empresa.
 *
 * @author Ing. Adrin Alvarado Ramrez.
 */
public class EnviadorCorreo {

    /**
     * Se utiliza para almacenar un mensaje generado durante el envo del
     * correo. Este atributo es de solo lectura.
     */
    private String mensaje;
    private String mensajeError;

    private String host;
    private String usuario;
    private String password;

    private int puerto;
    private boolean isGmail;

    public EnviadorCorreo(boolean usarSMTPGmail) {
        init(usarSMTPGmail);
    }

    /**
     *
     * Inicializacin por defecto del mdulo de correo. Se utilizan los datos de
     * la cuenta de la empresa.
     *
     */
    private void init(boolean usarSMTPGmail) {
        if (usarSMTPGmail) {
            host = "smtp.googlemail.com";
            usuario = "<usuario-correo>";
            password = "<contrasea>";
            puerto = 465;
            isGmail = true;
        } else {
            host = "<smtpalternativo";
            usuario = "<usuario-correo>";
            password = "<contrasea>";
            puerto = 25;
            isGmail = false;
        }
    }

    /**
     * Enva un correo electrnico. Utiliza la biblioteca Apache Commons Email,
     * accesible va <a href="https://commons.apache.org/proper/commons-email/">https://commons.apache.org/proper/commons-email/</a>
     *
     * @param destinatario
     * @param asunto
     * @param mensaje
     * @return
     */
    public boolean enviarCorreoE(String destinatario, String asunto, String mensaje) {
        boolean resultado = false;

        HtmlEmail email = new HtmlEmail();
        email.setHostName(host);
        email.setSmtpPort(puerto);
        email.setAuthenticator(new DefaultAuthenticator(usuario, password));

        if (isGmail) {
            email.setSSLOnConnect(true);
        } else {
            email.setStartTLSEnabled(true);
        }

        try {
            email.setFrom(usuario + "<dominio del correo>");
            email.setSubject(asunto);
            email.setHtmlMsg(mensaje);
            email.addTo(destinatario);
            email.send();
            resultado = true;
        } catch (EmailException eme) {
            mensaje = "Ocurri un error al hacer el envo de correo.";
            mensajeError = eme.toString();
        }

        return resultado;
    }

    public boolean testEnvioCorreo() {
        String mensajePrueba = null;

        if (isGmail) {
            mensajePrueba = "<p>Esto es una prueba usando el SMTP de Gmail.</p>";
        } else {
            mensajePrueba = "<p>Esto es una prueba usando el SMTP de la empresa</p>";
        }

        String destinatarioPrueba = "<correo electrnico de destinatario para prueba>";

        return enviarCorreoE(destinatarioPrueba, "Asunto de prueba", mensajePrueba);
    }

    /**
     * @return the mensaje
     */
    public String getMensaje() {
        return mensaje;
    }

    /**
     * @return the host
     */
    public String getHost() {
        return host;
    }

    /**
     * @param host the host to set
     */
    public void setHost(String host) {
        this.host = host;
    }

    /**
     * @return the usuario
     */
    public String getUsuario() {
        return usuario;
    }

    /**
     * @param usuario the usuario to set
     */
    public void setUsuario(String usuario) {
        this.usuario = usuario;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * @return the mensajeError
     */
    public String getMensajeError() {
        return mensajeError;
    }

}