Advertisement
Guest User

Untitled

a guest
Jan 18th, 2018
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.87 KB | None | 0 0
  1. package br.net.eds.integracao.mail.util;
  2.  
  3. import java.io.ByteArrayInputStream;
  4. import java.io.ByteArrayOutputStream;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. import java.io.OutputStream;
  10.  
  11. import java.util.List;
  12.  
  13. import javax.activation.DataHandler;
  14. import javax.activation.DataSource;
  15. import javax.activation.MimetypesFileTypeMap;
  16.  
  17. import javax.mail.Address;
  18. import javax.mail.Message;
  19. import javax.mail.Multipart;
  20. import javax.mail.Session;
  21. import javax.mail.Transport;
  22. import javax.mail.internet.InternetAddress;
  23. import javax.mail.internet.MimeBodyPart;
  24. import javax.mail.internet.MimeMessage;
  25. import javax.mail.internet.MimeMultipart;
  26. import javax.mail.internet.MimeUtility;
  27.  
  28. public class MailSender {
  29.  
  30. /**
  31. * Envia email
  32. *
  33. * @param mailSession javax.mail.Session
  34. * @param to destinatários
  35. * @param subject assunto
  36. * @param message mensagem em formato text/html
  37. * @param attachments
  38. * lista de arquivos em anexo.
  39. * Quando um anexo for utilizado no corpo de um email, o mesmo deve ser mencionado da seguinte forma:
  40. * <img src="cid:[NOME_DO_ARQUIVO]" />
  41. * @throws Exception em caso de erro inesperado
  42. */
  43. public static void doIt(Session mailSession,
  44. String[] to,
  45. String subject,
  46. String message,
  47. List<File> attachments) throws Exception {
  48.  
  49. if (mailSession == null) {
  50.  
  51. throw new Exception("Erro ao injetar mail session.");
  52. }
  53.  
  54. mailSession.setDebug(true);
  55.  
  56. //Objeto que contém a mensagem
  57. Message msg = null;
  58.  
  59. try {
  60. // final String user = mailSession.getProperty("mail.smtp.user");
  61. // final String password = mailSession.getProperty("mail.smtp.password");
  62. //
  63. // mailSession = Session.getInstance(mailSession.getProperties(),
  64. // new javax.mail.Authenticator(){
  65. // protected PasswordAuthentication getPasswordAuthentication() {
  66. // // Specify the Username and the PassWord
  67. // return new PasswordAuthentication(user, password);
  68. // }
  69. // }
  70. // );
  71.  
  72. msg = new MimeMessage(mailSession);
  73. msg.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");
  74. msg.addHeader("Cache-Control", "no-cache");
  75.  
  76. /* ************************
  77. * Informando destinatários
  78. * ************************/
  79. Address[] recipients = new InternetAddress[to.length];
  80. for (int i = 0; i < to.length; i++) {
  81. recipients[i] = new InternetAddress(to[i]);
  82. }
  83. msg.setRecipients(Message.RecipientType.TO, recipients);
  84.  
  85. /* ***************************
  86. * Informando email de origem
  87. * ***************************/
  88. msg.setFrom(new InternetAddress(mailSession.getProperty("mail.smtp.user")));
  89.  
  90. /* ***************************
  91. * Informando assunto do email
  92. * ***************************/
  93. msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B"));
  94.  
  95. /* ****************************
  96. * Preparando corpo da mensagem
  97. * ****************************/
  98. MimeBodyPart messageBodyPart = new MimeBodyPart();
  99. messageBodyPart.setContent(message, "text/html; charset=\"UTF-8\"");
  100.  
  101. /* ********************************
  102. * Adicionando anexos as mensagens
  103. * ********************************/
  104. Multipart multipart = new MimeMultipart();
  105. multipart.addBodyPart(messageBodyPart);
  106.  
  107.  
  108. if (attachments != null) {
  109. MimetypesFileTypeMap types = new MimetypesFileTypeMap();
  110. for (int count = 0; count < attachments.size(); count++) {
  111. File file = attachments.get(count);
  112.  
  113. String fileName = file.getName();
  114. String fileContentType = types.getContentType(file);
  115.  
  116. messageBodyPart = new MimeBodyPart();
  117. messageBodyPart.setDataHandler(
  118. new DataHandler(
  119. new InputStreamDataSource(
  120. fileName,
  121. fileContentType,
  122. new FileInputStream(file)
  123. )
  124. )
  125. );
  126.  
  127. messageBodyPart.setFileName(fileName);
  128. messageBodyPart.setHeader("Content-ID", String.format("<%s>", fileName));
  129.  
  130. multipart.addBodyPart(messageBodyPart);
  131. }
  132. }
  133. msg.setContent(multipart);
  134. } catch (Exception e) {
  135. throw new Exception("Erro ao completar mensagem.", e);
  136. }
  137.  
  138. // Objeto encarregado de enviar os dados para o email
  139. try {
  140. Transport.send(msg, msg.getAllRecipients());
  141. } catch (Exception e) {
  142. throw new Exception("Erro ao enviar mensagem.", e);
  143. }
  144. }
  145.  
  146. /**
  147. * Envia email
  148. *
  149. * @param transport javax.mail.Session
  150. * @param to destinatários
  151. * @param subject assunto
  152. * @param message mensagem em formato text/html
  153. * @param attachments
  154. * lista de arquivos em anexo.
  155. * Quando um anexo for utilizado no corpo de um email, o mesmo deve ser mencionado da seguinte forma:
  156. * &lt;img src="cid:[NOME_DO_ARQUIVO]" /&gt;
  157. * @throws Exception em caso de erro inesperado
  158. */
  159. public static void doIt(Session mailSession,
  160. Transport mainTransport,
  161. String[] to,
  162. String subject,
  163. String message,
  164. List<File> attachments) throws Exception {
  165.  
  166. //Objeto que contém a mensagem
  167. Message msg = null;
  168. try {
  169. msg = new MimeMessage(mailSession);
  170. msg.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");
  171. msg.addHeader("Cache-Control", "no-cache");
  172.  
  173. /* ************************
  174. * Informando destinatários
  175. * ************************/
  176. Address[] recipients = new InternetAddress[to.length];
  177. for (int i = 0; i < to.length; i++) {
  178. recipients[i] = new InternetAddress(to[i]);
  179. }
  180. msg.setRecipients(Message.RecipientType.TO, recipients);
  181.  
  182. /* ***************************
  183. * Informando email de origem
  184. * ***************************/
  185. msg.setFrom(new InternetAddress(mailSession.getProperty("mail.smtp.user")));
  186.  
  187. /* ***************************
  188. * Informando assunto do email
  189. * ***************************/
  190. msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B"));
  191.  
  192. /* ****************************
  193. * Preparando corpo da mensagem
  194. * ****************************/
  195. MimeBodyPart messageBodyPart = new MimeBodyPart();
  196. messageBodyPart.setContent(message, "text/html; charset=\"UTF-8\"");
  197.  
  198. /* ********************************
  199. * Adicionando anexos as mensagens
  200. * ********************************/
  201. Multipart multipart = new MimeMultipart();
  202. multipart.addBodyPart(messageBodyPart);
  203.  
  204.  
  205. if (attachments != null) {
  206. MimetypesFileTypeMap types = new MimetypesFileTypeMap();
  207. for (int count = 0; count < attachments.size(); count++) {
  208. File file = attachments.get(count);
  209.  
  210. String fileName = file.getName();
  211. String fileContentType = types.getContentType(file);
  212.  
  213. messageBodyPart = new MimeBodyPart();
  214. messageBodyPart.setDataHandler(
  215. new DataHandler(
  216. new InputStreamDataSource(
  217. fileName,
  218. fileContentType,
  219. new FileInputStream(file)
  220. )
  221. )
  222. );
  223.  
  224. messageBodyPart.setFileName(fileName);
  225. messageBodyPart.setHeader("Content-ID", String.format("<%s>", fileName));
  226.  
  227. multipart.addBodyPart(messageBodyPart);
  228. }
  229. }
  230. msg.setContent(multipart);
  231. msg.saveChanges();
  232. } catch (Exception e) {
  233. throw new Exception("Erro ao completar mensagem.", e);
  234. }
  235.  
  236. // ####################################################
  237. // OBJETO ENCARREGADO DE ENVIAR OS DADOS PARA O EMAIL #
  238. // ####################################################
  239. try {
  240. mainTransport.sendMessage(msg, msg.getAllRecipients());
  241. } catch (Exception e) {
  242. throw new Exception("Erro ao enviar mensagem.", e);
  243. }
  244. }
  245.  
  246. private static class InputStreamDataSource implements DataSource {
  247.  
  248. private String name;
  249. private String contentType;
  250. private ByteArrayOutputStream baos;
  251.  
  252. @SuppressWarnings("oracle.jdeveloper.java.nested-assignment")
  253. InputStreamDataSource(String name, String contentType, InputStream inputStream) throws IOException {
  254. this.name = name;
  255. this.contentType = contentType;
  256.  
  257. baos = new ByteArrayOutputStream();
  258. int read = 0;
  259. byte[] buff = new byte[256];
  260. while ((read = inputStream.read(buff)) != -1) {
  261. baos.write(buff, 0, read);
  262. }
  263. baos.close();
  264. }
  265.  
  266. public String getContentType() {
  267. return contentType;
  268. }
  269.  
  270. public InputStream getInputStream() throws IOException {
  271. return new ByteArrayInputStream(baos.toByteArray());
  272. }
  273.  
  274. public String getName() {
  275. return name;
  276. }
  277.  
  278. public OutputStream getOutputStream() throws IOException {
  279. throw new IOException("Cannot write to this read-only resource");
  280. }
  281. }
  282. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement