Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package br.net.eds.integracao.mail.util;
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.util.List;
- import javax.activation.DataHandler;
- import javax.activation.DataSource;
- import javax.activation.MimetypesFileTypeMap;
- import javax.mail.Address;
- import javax.mail.Message;
- import javax.mail.Multipart;
- 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;
- import javax.mail.internet.MimeUtility;
- public class MailSender {
- /**
- * Envia email
- *
- * @param mailSession javax.mail.Session
- * @param to destinatários
- * @param subject assunto
- * @param message mensagem em formato text/html
- * @param attachments
- * lista de arquivos em anexo.
- * Quando um anexo for utilizado no corpo de um email, o mesmo deve ser mencionado da seguinte forma:
- * <img src="cid:[NOME_DO_ARQUIVO]" />
- * @throws Exception em caso de erro inesperado
- */
- public static void doIt(Session mailSession,
- String[] to,
- String subject,
- String message,
- List<File> attachments) throws Exception {
- if (mailSession == null) {
- throw new Exception("Erro ao injetar mail session.");
- }
- mailSession.setDebug(true);
- //Objeto que contém a mensagem
- Message msg = null;
- try {
- // final String user = mailSession.getProperty("mail.smtp.user");
- // final String password = mailSession.getProperty("mail.smtp.password");
- //
- // mailSession = Session.getInstance(mailSession.getProperties(),
- // new javax.mail.Authenticator(){
- // protected PasswordAuthentication getPasswordAuthentication() {
- // // Specify the Username and the PassWord
- // return new PasswordAuthentication(user, password);
- // }
- // }
- // );
- msg = new MimeMessage(mailSession);
- msg.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");
- msg.addHeader("Cache-Control", "no-cache");
- /* ************************
- * Informando destinatários
- * ************************/
- Address[] recipients = new InternetAddress[to.length];
- for (int i = 0; i < to.length; i++) {
- recipients[i] = new InternetAddress(to[i]);
- }
- msg.setRecipients(Message.RecipientType.TO, recipients);
- /* ***************************
- * Informando email de origem
- * ***************************/
- msg.setFrom(new InternetAddress(mailSession.getProperty("mail.smtp.user")));
- /* ***************************
- * Informando assunto do email
- * ***************************/
- msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B"));
- /* ****************************
- * Preparando corpo da mensagem
- * ****************************/
- MimeBodyPart messageBodyPart = new MimeBodyPart();
- messageBodyPart.setContent(message, "text/html; charset=\"UTF-8\"");
- /* ********************************
- * Adicionando anexos as mensagens
- * ********************************/
- Multipart multipart = new MimeMultipart();
- multipart.addBodyPart(messageBodyPart);
- if (attachments != null) {
- MimetypesFileTypeMap types = new MimetypesFileTypeMap();
- for (int count = 0; count < attachments.size(); count++) {
- File file = attachments.get(count);
- String fileName = file.getName();
- String fileContentType = types.getContentType(file);
- messageBodyPart = new MimeBodyPart();
- messageBodyPart.setDataHandler(
- new DataHandler(
- new InputStreamDataSource(
- fileName,
- fileContentType,
- new FileInputStream(file)
- )
- )
- );
- messageBodyPart.setFileName(fileName);
- messageBodyPart.setHeader("Content-ID", String.format("<%s>", fileName));
- multipart.addBodyPart(messageBodyPart);
- }
- }
- msg.setContent(multipart);
- } catch (Exception e) {
- throw new Exception("Erro ao completar mensagem.", e);
- }
- // Objeto encarregado de enviar os dados para o email
- try {
- Transport.send(msg, msg.getAllRecipients());
- } catch (Exception e) {
- throw new Exception("Erro ao enviar mensagem.", e);
- }
- }
- /**
- * Envia email
- *
- * @param transport javax.mail.Session
- * @param to destinatários
- * @param subject assunto
- * @param message mensagem em formato text/html
- * @param attachments
- * lista de arquivos em anexo.
- * Quando um anexo for utilizado no corpo de um email, o mesmo deve ser mencionado da seguinte forma:
- * <img src="cid:[NOME_DO_ARQUIVO]" />
- * @throws Exception em caso de erro inesperado
- */
- public static void doIt(Session mailSession,
- Transport mainTransport,
- String[] to,
- String subject,
- String message,
- List<File> attachments) throws Exception {
- //Objeto que contém a mensagem
- Message msg = null;
- try {
- msg = new MimeMessage(mailSession);
- msg.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");
- msg.addHeader("Cache-Control", "no-cache");
- /* ************************
- * Informando destinatários
- * ************************/
- Address[] recipients = new InternetAddress[to.length];
- for (int i = 0; i < to.length; i++) {
- recipients[i] = new InternetAddress(to[i]);
- }
- msg.setRecipients(Message.RecipientType.TO, recipients);
- /* ***************************
- * Informando email de origem
- * ***************************/
- msg.setFrom(new InternetAddress(mailSession.getProperty("mail.smtp.user")));
- /* ***************************
- * Informando assunto do email
- * ***************************/
- msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B"));
- /* ****************************
- * Preparando corpo da mensagem
- * ****************************/
- MimeBodyPart messageBodyPart = new MimeBodyPart();
- messageBodyPart.setContent(message, "text/html; charset=\"UTF-8\"");
- /* ********************************
- * Adicionando anexos as mensagens
- * ********************************/
- Multipart multipart = new MimeMultipart();
- multipart.addBodyPart(messageBodyPart);
- if (attachments != null) {
- MimetypesFileTypeMap types = new MimetypesFileTypeMap();
- for (int count = 0; count < attachments.size(); count++) {
- File file = attachments.get(count);
- String fileName = file.getName();
- String fileContentType = types.getContentType(file);
- messageBodyPart = new MimeBodyPart();
- messageBodyPart.setDataHandler(
- new DataHandler(
- new InputStreamDataSource(
- fileName,
- fileContentType,
- new FileInputStream(file)
- )
- )
- );
- messageBodyPart.setFileName(fileName);
- messageBodyPart.setHeader("Content-ID", String.format("<%s>", fileName));
- multipart.addBodyPart(messageBodyPart);
- }
- }
- msg.setContent(multipart);
- msg.saveChanges();
- } catch (Exception e) {
- throw new Exception("Erro ao completar mensagem.", e);
- }
- // ####################################################
- // OBJETO ENCARREGADO DE ENVIAR OS DADOS PARA O EMAIL #
- // ####################################################
- try {
- mainTransport.sendMessage(msg, msg.getAllRecipients());
- } catch (Exception e) {
- throw new Exception("Erro ao enviar mensagem.", e);
- }
- }
- private static class InputStreamDataSource implements DataSource {
- private String name;
- private String contentType;
- private ByteArrayOutputStream baos;
- @SuppressWarnings("oracle.jdeveloper.java.nested-assignment")
- InputStreamDataSource(String name, String contentType, InputStream inputStream) throws IOException {
- this.name = name;
- this.contentType = contentType;
- baos = new ByteArrayOutputStream();
- int read = 0;
- byte[] buff = new byte[256];
- while ((read = inputStream.read(buff)) != -1) {
- baos.write(buff, 0, read);
- }
- baos.close();
- }
- public String getContentType() {
- return contentType;
- }
- public InputStream getInputStream() throws IOException {
- return new ByteArrayInputStream(baos.toByteArray());
- }
- public String getName() {
- return name;
- }
- public OutputStream getOutputStream() throws IOException {
- throw new IOException("Cannot write to this read-only resource");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement