Guest User

Untitled

a guest
Oct 15th, 2018
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.50 KB | None | 0 0
  1. import java.io.File;
  2. import java.util.Date;
  3. import java.util.Properties;
  4.  
  5. import javax.activation.CommandMap;
  6. import javax.activation.DataHandler;
  7. import javax.activation.DataSource;
  8. import javax.activation.FileDataSource;
  9. import javax.activation.MailcapCommandMap;
  10. import javax.mail.BodyPart;
  11. import javax.mail.Message;
  12. import javax.mail.MessagingException;
  13. import javax.mail.Multipart;
  14. import javax.mail.PasswordAuthentication;
  15. import javax.mail.Session;
  16. import javax.mail.Transport;
  17. import javax.mail.internet.InternetAddress;
  18. import javax.mail.internet.MimeBodyPart;
  19. import javax.mail.internet.MimeMessage;
  20. import javax.mail.internet.MimeMultipart;
  21.  
  22. /**
  23. * Created by Jesus on 24/11/2017.
  24. */
  25. public class Mail extends javax.mail.Authenticator {
  26.  
  27. // Variables
  28. private String user = ""; // username
  29. private String pass = ""; // password
  30. private boolean auth = true; // smtp authentication - default on
  31.  
  32. private String from = user; // correo electrónico enviado desde
  33. private String[] to; // Destinatario(s) principal(es) del mensaje
  34. private String[] bcc; // Destinatario al que se envía copia, pero sin que los demás destinatarios puedan verlo.
  35.  
  36. private String port = "465"; // default puerto smtp
  37. private String sport = "465"; // default puerto socketfactory
  38. private String host = "smtp.gmail.com"; // default servidor smtp
  39.  
  40. private String subject = ""; // email asunto
  41.  
  42. private Multipart multipart; // cuerpo del mensaje.
  43.  
  44. private boolean debuggable = false; // debug mode on or off - default off
  45.  
  46. // Constructor
  47. public Mail() {
  48. multipart = new MimeMultipart();
  49.  
  50. // Hay algo mal con MailCap, javamail no puede encontrar un
  51. // controlador para multipart/mixed part, por lo que este bit debe agregarse.
  52. MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
  53. mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
  54. mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
  55. mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
  56. mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
  57. mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
  58. CommandMap.setDefaultCommandMap(mc);
  59. }
  60.  
  61. public Mail(String user, String pass) {
  62. this();
  63. this.setUser(user);
  64. this.setPass(pass);
  65. }
  66.  
  67. private static void throwIfEmpty(String value, String msg) {
  68. if (value == null || value.isEmpty()) throw new RuntimeException(msg);
  69. }
  70.  
  71. private static void throwIfEmpty(String[] array, String msg) {
  72. if (array == null || array.length == 0) throw new RuntimeException(msg);
  73. }
  74.  
  75. /**
  76. * Envia el correo.
  77. *
  78. * @throws Exception
  79. */
  80. public void send() throws Exception {
  81. throwIfEmpty(user, "Especifica el remitente");
  82. throwIfEmpty(pass, "Se requiere de password");
  83. throwIfEmpty(from, "Especifica el remitente");
  84. throwIfEmpty(to, "Especifica al menos un destinatario.");
  85.  
  86. Properties props = getProperties();
  87. Session session = Session.getInstance(props, this);
  88.  
  89. // Mensaje:
  90. MimeMessage msg = new MimeMessage(session);
  91. msg.setFrom(new InternetAddress(from));
  92.  
  93. // Destinatario(s) principal(es) del mensaje:
  94. for (String address : to) {
  95. msg.addRecipient(Message.RecipientType.TO, new InternetAddress(address));
  96. }
  97. // Destinatario al que se envía copia, pero sin que los demás destinatarios puedan verlo.
  98. if (bcc != null) {
  99. for (String address : bcc) {
  100. msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(address));
  101. }
  102. }
  103.  
  104. msg.setSubject(subject);
  105. msg.setSentDate(new Date());
  106. msg.setHeader("X-Priority", "1");
  107. // Poner partes en mensaje
  108. msg.setContent(multipart);
  109.  
  110. // Envia el email
  111. Transport.send(msg);
  112.  
  113. // // Copia el mensaje a la carpeta "Elementos enviados" como leída
  114. // Store store = session.getStore("pop3");
  115. // store.connect(host, user, pass);
  116. // Folder folder = store.getFolder("INBOX");
  117. // folder.open(Folder.READ_WRITE);
  118. // msg.setFlag(Flags.Flag.SEEN, true);
  119. // folder.appendMessages(new MimeMessage[] {msg});
  120. // store.close();
  121. }
  122.  
  123. private Properties getProperties() {
  124. Properties props = new Properties();
  125. props.put("mail.smtp.host", host);
  126.  
  127. if (debuggable) props.put("mail.debug", "true");
  128.  
  129. if (auth) props.put("mail.smtp.auth", "true");
  130.  
  131. props.put("mail.smtp.starttls.enable", "true");//
  132. props.put("mail.smtp.port", port);
  133. props.put("mail.smtp.socketFactory.port", sport);
  134. props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  135. props.put("mail.smtp.socketFactory.fallback", "false");
  136.  
  137. return props;
  138. }
  139.  
  140. @Override public PasswordAuthentication getPasswordAuthentication() {
  141. return new PasswordAuthentication(user, pass);
  142. }
  143.  
  144.  
  145. /**
  146. * Email cuerpo de correo
  147. *
  148. * @param body Cuerpo del mensaje
  149. */
  150. public void addBody(Object body) {
  151. addBody(body, "text/html");
  152. }
  153.  
  154. /**
  155. * Email cuerpo de correo
  156. *
  157. * @param body Cuerpo del mensaje
  158. * @param contetType typo de contenido
  159. */
  160. public void addBody(Object body, String contetType) {
  161. try {
  162. BodyPart messageBodyPart = new MimeBodyPart();
  163. messageBodyPart.setContent(body, contetType);
  164. multipart.addBodyPart(messageBodyPart);
  165. } catch (MessagingException ignore) {
  166. }
  167. }
  168.  
  169. /**
  170. * Metodo para añadir un adjunto.
  171. * @param filename ruta del archivo a subir.
  172. */
  173. public void addAttachment(String filename) {
  174. addAttachment(new File(filename));
  175. }
  176.  
  177. /**
  178. * Metodo para añadir un archivo.
  179. * @param file archivo a subir.
  180. */
  181. public void addAttachment(java.io.File file) {
  182. try {
  183. BodyPart messageBodyPart = new MimeBodyPart();
  184. DataSource source = new FileDataSource(file);
  185. messageBodyPart.setDataHandler(new DataHandler(source));
  186. messageBodyPart.setFileName(file.getName());
  187.  
  188. multipart.addBodyPart(messageBodyPart);
  189. } catch (MessagingException ignore) {
  190. }
  191. }
  192.  
  193. // getters and setters
  194.  
  195. public String getUser() {
  196. return user;
  197. }
  198. public void setUser(String _user) {
  199. this.user = _user;
  200. setFrom(_user);
  201. }
  202.  
  203. public String getPass() {
  204. return pass;
  205. }
  206. public void setPass(String _pass) {
  207. this.pass = _pass;
  208. }
  209.  
  210. public String[] getTo() {
  211. return to;
  212. }
  213. public void setTo(String... _to) {
  214. this.to = _to;
  215. }
  216.  
  217. public String[] getBcc() {
  218. return bcc;
  219. }
  220. public void setBcc(String... bcc) {
  221. this.bcc = bcc;
  222. }
  223.  
  224. public String getFrom() {
  225. return from;
  226. }
  227. public void setFrom(String _from) {
  228. this.from = _from;
  229. }
  230.  
  231. public String getPort() {
  232. return port;
  233. }
  234. public void setPort(String _port) {
  235. this.port = _port;
  236. }
  237.  
  238. public String getSport() {
  239. return sport;
  240. }
  241. public void setSport(String _sport) {
  242. this.sport = _sport;
  243. }
  244.  
  245. public String getHost() {
  246. return host;
  247. }
  248. public void setHost(String _host) {
  249. this.host = _host;
  250. }
  251.  
  252. public String getSubject() {
  253. return subject;
  254. }
  255. public void setSubject(String _subject) {
  256. this.subject = _subject;
  257. }
  258.  
  259. public boolean isAuth() {
  260. return auth;
  261. }
  262. public void setAuth(boolean _auth) {
  263. this.auth = _auth;
  264. }
  265.  
  266. public boolean isDebuggable() {
  267. return debuggable;
  268. }
  269. public void setDebuggable(boolean _debuggable) {
  270. this.debuggable = _debuggable;
  271. }
  272.  
  273. public Multipart getMultipart() {
  274. return multipart;
  275. }
  276. public void setMultipart(Multipart _multipart) {
  277. this.multipart = _multipart;
  278. }
  279. }
Add Comment
Please, Sign In to add comment