Enviar correo con Java Mail

Para efectos prácticos usaremos la forma mas sencilla (sin tantos parámetros) para enviar un correo con la librería JMail al correo de Gmail. La librería la pueden descargar aca

import java.util.ArrayList;
import java.util.Properties;
import javax.mail.AuthenticationFailedException;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author xm17007
 */
public class CorreoE {

    private String from = "";
    private ArrayList to = new ArrayList();
    private ArrayList cc = new ArrayList();
    private String host = "";
    private String port = "";
    private String subject = "";
    private String cuerpoMensaje = "";
    private String error="";

    public boolean enviarCorreo(String subject, String cuerpoMensaje) {
        boolean flag = true;
        setSubject(subject);
        setCuerpoMensaje(cuerpoMensaje);
        cargar();
        if (getTo().size() > 0) {
            try {
                // Propiedades de la conexión
                Properties props = new Properties();
                props.setProperty("mail.smtp.host", getHost());
                props.put("mail.smtp.port", getPort());
                props.setProperty("mail.smtp.user", getTo().get(0));
                props.put("mail.transport.protocol", "smtp");
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.debug", "true");

                Session session = Session.getDefaultInstance(props);
                // Construimos el mensaje
                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(getFrom()));
                for (int i = 0; i < getTo().size(); i++) {
                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(getTo().get(i)));
                }
                for (int i = 0; i < getCc().size(); i++) {
                    message.addRecipient(Message.RecipientType.CC, new InternetAddress(getCc().get(i)));
                }
                message.setSubject(getSubject());
                message.setText(getError());

                // Lo enviamos.
                Transport t = session.getTransport("smtp");
                t.connect();
                t.sendMessage(message, message.getAllRecipients());

                // Cierre.
                t.close();
            } catch (AuthenticationFailedException e) {
                flag = false;
                e.printStackTrace();
            } catch (Exception e) {
                flag = false;
                e.printStackTrace();
            }
        } else {
            flag = false;
        }

        return flag;
    }

    public static void main(String[] ergs) {
        new CorreoE().enviarCorreo("Prueba", "Mensaje de prueba");
    }

    public void cargar() {
        //Se cargan los valores de configuraciòn del correo
        setFrom("yo@yo.com");
        setHost("smtp.gmail.com");
        setPort("587");
        //Con copia
        getCc().add("Correo@otro.com");
        //Para:
        getTo().add("prueba@otro.com");
    }

    /**
     * @return the from
     */
    public String getFrom() {
        return from;
    }

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

    /**
     * @return the to
     */
    public ArrayList getTo() {
        return to;
    }

    /**
     * @param to the to to set
     */
    public void setTo(ArrayList to) {
        this.to = to;
    }

    /**
     * @return the cc
     */
    public ArrayList getCc() {
        return cc;
    }

    /**
     * @param cc the cc to set
     */
    public void setCc(ArrayList cc) {
        this.cc = cc;
    }

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

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

    /**
     * @return the port
     */
    public String getPort() {
        return port;
    }

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

    /**
     * @return the subject
     */
    public String getSubject() {
        return subject;
    }

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

    /**
     * @return the cuerpoMensaje
     */
    public String getCuerpoMensaje() {
        return cuerpoMensaje;
    }

    /**
     * @param cuerpoMensajethe cuerpoMensajeto set
     */
    public void setCuerpoMensaje(String cuerpoMensaje) {
        this.cuerpoMensaje = cuerpoMensaje;
    }
    /**
     * @param error
     */
    public void setError(String error) {
        this.error= error;
    }

    /**
     * @return the error     */
    public String getError() {
        return error;
    }
}

6 Comentarios

  1. Hola estimado, sabes he intentado correr tu clase, pero sabes hay un problema, el metodo getError() no existe, este lo utilizas el la linea 51. Ahora sería aún más genial se nos pudieras proveer de este metodo, desde ya muchas gracias.
    Bye.

    ResponderBorrar
  2. Listo solo falta agregar el atributo error.

    Saludoss!

    ResponderBorrar
  3. doc. sabes si hay alguna forma de enviar el correo sin la necesidad del password

    ResponderBorrar
  4. doc. sabes si hay alguna forma de enviar el correo sin la necesidad del password, en php se puede hacer eso, en java lo estoy intentando pero no encuentro la forma.

    saludos.

    ResponderBorrar
  5. como puedo enviar de otro servidor que no sea gmail,hotmal etc que se pueda enviar como de @itssmt.com.mx

    ResponderBorrar
  6. Tienes que poner la configuración del servidor de correos de ese dominio (itssmt)

    ResponderBorrar

Publicar un comentario

Artículo Anterior Artículo Siguiente