Skip to content

Instantly share code, notes, and snippets.

@jesusbmx
Last active August 6, 2019 22:22
Show Gist options
  • Save jesusbmx/bfeddd43180f83739be5f16884e841a0 to your computer and use it in GitHub Desktop.
Save jesusbmx/bfeddd43180f83739be5f16884e841a0 to your computer and use it in GitHub Desktop.
Envía correos con JavaMail
package com.post.movil.movilpost.librerias;
import java.io.File;
import java.util.Date;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
/**
* Created by Jesus on 24/11/2017.
*/
public class Mail extends javax.mail.Authenticator {
// Variables
private String pass = ""; // password
private boolean auth = true; // smtp authentication - default on
private InternetAddress from = new InternetAddress(); // correo electrónico enviado desde
private String[] to; // Destinatario(s) principal(es) del mensaje
private String[] bcc; // Destinatario al que se envía copia, pero sin que los demás destinatarios puedan verlo.
private String subject = ""; // email asunto
private String port = "465"; // default puerto smtp
private String sport = "465"; // default puerto socketfactory
private String host = "smtp.gmail.com"; // default servidor smtp
private Multipart multipart; // cuerpo del mensaje.
private boolean debuggable = false; // debug mode on or off - default off
static {
// Hay algo mal con MailCap, javamail no puede encontrar un
// controlador para multipart/mixed part, por lo que este bit debe agregarse.
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
}
// Constructor
public Mail() {
multipart = new MimeMultipart();
}
public Mail(String user, String pass) {
this();
this.setFrom(user);
this.setPass(pass);
}
private static void throwIfEmpty(String value, String msg) {
if (value == null || value.isEmpty()) throw new RuntimeException(msg);
}
private static void throwIfEmpty(String[] array, String msg) {
if (array == null || array.length == 0) throw new RuntimeException(msg);
}
public static Mail notificaciones() {
Mail m = new Mail();
//m.setDebuggable(true);
//m.setHost("mail.company.mx");
m.setHost("mail.company.com");
m.setFrom("notificaciones@company.com",
"Notificaciones company");
m.setPass("xxx");
return m;
}
/**
* Envia el correo.
*
* @throws Exception
*/
public void send() throws Exception {
throwIfEmpty(getFrom(), "Especifica el remitente");
throwIfEmpty(pass, "Se requiere de password");
throwIfEmpty(to, "Especifica al menos un destinatario.");
Properties props = getProperties();
Session session = Session.getInstance(props, this);
// Mensaje:
MimeMessage msg = new MimeMessage(session);
msg.setFrom(from);
// Destinatario(s) principal(es) del mensaje:
for (String address : to) {
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(address));
}
// Destinatario al que se envía copia, pero sin que los demás destinatarios puedan verlo.
if (bcc != null) {
for (String address : bcc) {
msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(address));
}
}
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setHeader("X-Priority", "1");
// Poner partes en mensaje
msg.setContent(multipart);
// Envia el email
Transport.send(msg);
}
private Properties getProperties() {
Properties props = new Properties();
props.put("mail.smtp.host", host);
if (debuggable) props.put("mail.debug", "true");
if (auth) props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");//
props.put("mail.smtp.port", port);
props.put("mail.smtp.socketFactory.port", sport);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
return props;
}
@Override public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(getFrom(), getPass());
}
public static BodyPart MIMEText(String body, String contetType) {
BodyPart part = new MimeBodyPart();
try {
part.setContent(body, contetType);
} catch (MessagingException ignore) {
}
return part;
}
public static BodyPart MIMEFile(File file) {
BodyPart part = new MimeBodyPart();
try {
DataSource src = new FileDataSource(file);
part.setDataHandler(new DataHandler(src));
part.setFileName(file.getName());
} catch (MessagingException ignore) {
}
return part;
}
public void attach(BodyPart part) {
try {
multipart.addBodyPart(part);
} catch (MessagingException ignore) {
}
}
/**
* Email cuerpo de correo
*
* @param body Cuerpo del mensaje
*/
public void attachText(String body) {
attach(MIMEText(body, "text/html"));
}
/**
* Metodo para añadir un archivo.
* @param file archivo a subir.
*/
public void attachFile(File file) {
attach(MIMEFile(file));
}
// getters and setters
public String getPass() {
return pass;
}
public void setPass(String _pass) {
pass = _pass;
}
public String[] getTo() {
return to;
}
public void setTo(String... _to) {
to = _to;
}
public String[] getBcc() {
return bcc;
}
public void setBcc(String... _bcc) {
bcc = _bcc;
}
public String getFrom() {
return from.getAddress();
}
public void setFrom(String _from) {
this.setFrom(_from, null);
}
public void setFrom(String address, String personal) {
try {
this.from.setAddress(address);
this.from.setPersonal(personal);
} catch(Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public String getPort() {
return port;
}
public void setPort(String _port) {
port = _port;
}
public String getSport() {
return sport;
}
public void setSport(String _sport) {
sport = _sport;
}
public String getHost() {
return host;
}
public void setHost(String _host) {
host = _host;
}
public String getSubject() {
return subject;
}
public void setSubject(String _subject) {
subject = _subject;
}
public boolean isAuth() {
return auth;
}
public void setAuth(boolean _auth) {
auth = _auth;
}
public boolean isDebuggable() {
return debuggable;
}
public void setDebuggable(boolean _debuggable) {
this.debuggable = _debuggable;
}
public Multipart getMultipart() {
return multipart;
}
public void setMultipart(Multipart _multipart) {
multipart = _multipart;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment