Example usage for org.apache.commons.mail MultiPartEmail getMimeMessage

List of usage examples for org.apache.commons.mail MultiPartEmail getMimeMessage

Introduction

In this page you can find the example usage for org.apache.commons.mail MultiPartEmail getMimeMessage.

Prototype

public MimeMessage getMimeMessage() 

Source Link

Document

Returns the internal MimeMessage.

Usage

From source file:TestSendMail.java

public void testSend() {
    try {/*from   ww w . j  a  va2s.  co  m*/
        Security.removeProvider(new BouncyCastleProvider().getName());
        Security.addProvider(new BouncyCastleProvider());
        //log.info("Lista de proveedores disponible:"+Arrays.asList(Security.getProviders()));
        org.apache.xml.security.Init.init();
        Properties configuracion = new Properties();
        configuracion.put("HOST_SMTP", "192.168.10.7");

        SendMailUtil.init(configuracion); //benito.galan@avansi.com.do
        MultiPartEmail mail = SendMailUtil.getCurrentInstance().buildMessage("Ejemplo de Firma",
                "rquintero@viavansi.com", "", "<p>rub&eacute;n</p> ", "certificadoavansicxa", "avansicxa");
        mail.setDebug(true);
        // Enviamos 
        String id = mail.send();
        System.out.println(id);
        mail.getMimeMessage().writeTo(System.out);

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.duroty.application.files.manager.StoreManager.java

/**
 * DOCUMENT ME!/*from  w  w w.jav a 2s  . c om*/
 *
 * @param hsession DOCUMENT ME!
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param identity DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param cc DOCUMENT ME!
 * @param bcc DOCUMENT ME!
 * @param subject DOCUMENT ME!
 * @param body DOCUMENT ME!
 * @param attachments DOCUMENT ME!
 * @param isHtml DOCUMENT ME!
 * @param charset DOCUMENT ME!
 * @param headers DOCUMENT ME!
 * @param priority DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void send(org.hibernate.Session hsession, Session session, String repositoryName, Vector files,
        int label, String charset) throws FilesException {
    ByteArrayInputStream bais = null;
    FileOutputStream fos = null;

    try {
        if ((files == null) || (files.size() <= 0)) {
            return;
        }

        if (charset == null) {
            charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName());
        }

        Users user = getUser(hsession, repositoryName);
        Identity identity = getDefaultIdentity(hsession, user);

        InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName());
        InternetAddress _to = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());

        for (int i = 0; i < files.size(); i++) {
            MultiPartEmail email = email = new MultiPartEmail();
            email.setCharset(charset);

            if (_from != null) {
                email.setFrom(_from.getAddress(), _from.getPersonal());
            }

            if (_returnPath != null) {
                email.addHeader("Return-Path", _returnPath.getAddress());
                email.addHeader("Errors-To", _returnPath.getAddress());
                email.addHeader("X-Errors-To", _returnPath.getAddress());
            }

            if (_replyTo != null) {
                email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal());
            }

            if (_to != null) {
                email.addTo(_to.getAddress(), _to.getPersonal());
            }

            MailPartObj obj = (MailPartObj) files.get(i);

            email.setSubject("Files-System " + obj.getName());

            Date now = new Date();
            email.setSentDate(now);

            File dir = new File(System.getProperty("user.home") + File.separator + "tmp");

            if (!dir.exists()) {
                dir.mkdir();
            }

            File file = new File(dir, obj.getName());

            bais = new ByteArrayInputStream(obj.getAttachent());
            fos = new FileOutputStream(file);
            IOUtils.copy(bais, fos);

            IOUtils.closeQuietly(bais);
            IOUtils.closeQuietly(fos);

            EmailAttachment attachment = new EmailAttachment();
            attachment.setPath(file.getPath());
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setDescription("File Attachment: " + file.getName());
            attachment.setName(file.getName());

            email.attach(attachment);

            String mid = getId();
            email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">");
            email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">");

            email.addHeader("X-DBox", "FILES");

            email.addHeader("X-DRecent", "false");

            //email.setMsg(body);
            email.setMailSession(session);

            email.buildMimeMessage();

            MimeMessage mime = email.getMimeMessage();

            int size = MessageUtilities.getMessageSize(mime);

            if (!controlQuota(hsession, user, size)) {
                throw new MailException("ErrorMessages.mail.quota.exceded");
            }

            messageable.storeMessage(mid, mime, user);
        }
    } catch (FilesException e) {
        throw e;
    } catch (Exception e) {
        throw new FilesException(e);
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        throw new FilesException(ex);
    } catch (Throwable e) {
        throw new FilesException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(fos);
    }
}

From source file:org.apache.nifi.processors.email.ConsumeEWS.java

public MimeMessage parseMessage(EmailMessage item) throws Exception {
    EmailMessage ewsMessage = item;/*from   w  ww .j  ava2s . co  m*/
    final String bodyText = ewsMessage.getBody().toString();

    MultiPartEmail mm;

    if (ewsMessage.getBody().getBodyType() == BodyType.HTML) {
        mm = new HtmlEmail().setHtmlMsg(bodyText);
    } else {
        mm = new MultiPartEmail();
        mm.setMsg(bodyText);
    }
    mm.setHostName("NiFi-EWS");
    //from
    mm.setFrom(ewsMessage.getFrom().getAddress());
    //to recipients
    ewsMessage.getToRecipients().forEach(x -> {
        try {
            mm.addTo(x.getAddress());
        } catch (EmailException e) {
            throw new ProcessException("Failed to add TO recipient.", e);
        }
    });
    //cc recipients
    ewsMessage.getCcRecipients().forEach(x -> {
        try {
            mm.addCc(x.getAddress());
        } catch (EmailException e) {
            throw new ProcessException("Failed to add CC recipient.", e);
        }
    });
    //subject
    mm.setSubject(ewsMessage.getSubject());
    //sent date
    mm.setSentDate(ewsMessage.getDateTimeSent());
    //add message headers
    ewsMessage.getInternetMessageHeaders().forEach(x -> mm.addHeader(x.getName(), x.getValue()));

    //Any attachments
    if (ewsMessage.getHasAttachments()) {
        ewsMessage.getAttachments().forEach(x -> {
            try {
                FileAttachment file = (FileAttachment) x;
                file.load();

                ByteArrayDataSource bds = new ByteArrayDataSource(file.getContent(), file.getContentType());

                mm.attach(bds, file.getName(), "", EmailAttachment.ATTACHMENT);
            } catch (MessagingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    mm.buildMimeMessage();
    return mm.getMimeMessage();
}

From source file:org.apache.nifi.processors.email.GenerateAttachment.java

public byte[] WithAttachments(int amount) {
    MultiPartEmail email = new MultiPartEmail();
    try {// w  ww . j  a  va  2 s  .  co  m

        email.setFrom(from);
        email.addTo(to);
        email.setSubject(subject);
        email.setMsg(message);
        email.setHostName(hostName);

        int x = 1;
        while (x <= amount) {
            // Create an attachment with the pom.xml being used to compile (yay!!!)
            EmailAttachment attachment = new EmailAttachment();
            attachment.setPath("pom.xml");
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setDescription("pom.xml");
            attachment.setName("pom.xml" + String.valueOf(x));
            //  attach
            email.attach(attachment);
            x++;
        }
        email.buildMimeMessage();
    } catch (EmailException e) {
        e.printStackTrace();
    }
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    MimeMessage mimeMessage = email.getMimeMessage();
    try {
        mimeMessage.writeTo(output);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    }

    return output.toByteArray();
}

From source file:org.ploin.pmf.impl.MailSender.java

/**
 *
 * @param email - the MultipartEmail//from ww  w  . ja  v a2 s.c  o m
 * @param mailConfig - the mail config object
 * @param serverConfig - the server config object
 * @return SendingResult object
 */
private SendingResult send(MultiPartEmail email, MailConfig mailConfig, ServerConfig serverConfig)
        throws MailFactoryException {
    try {
        email.setCharset(Email.ISO_8859_1);
        setServerProperties(email, serverConfig);
        setMailProperties(email, mailConfig);
        setAttachements(email, mailConfig); // here is a bug in apache commons email ... problems with html and attachements
        String sendMessage = email.send();
        log.debug("email.send() = " + sendMessage);
        SendingResult sendingResult = new SendingResult();
        sendingResult.setResult(sendMessage);
        sendingResult.setMimeMessage(email.getMimeMessage());
        return sendingResult;
    } catch (Exception e) {
        throw new MailFactoryException(e);
    }
}

From source file:org.sakaiproject.nakamura.email.outgoing.LiteOutgoingEmailMessageListener.java

private void logEmail(MultiPartEmail multiPartMessage) {
    if (multiPartMessage != null) {
        MimeMessage mimeMessage = multiPartMessage.getMimeMessage();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {//from   w  w  w.  j a  va 2s.  c o m
            mimeMessage.writeTo(new FilterOutputStream(baos));
            LOGGER.debug("Email content = \n" + baos.toString());
        } catch (IOException e) {
            LOGGER.error("failed to log email", e);
        } catch (MessagingException e) {
            LOGGER.error("failed to log email", e);
        }
    } else {
        LOGGER.error("Email is null");
    }
}

From source file:org.viafirma.nucleo.Nucleo.java

/**
 * Enva un email firmado al destinatario.
 * /*from  w  w  w.  ja  va2 s  .c  o  m*/
 * @param texto
 *            Texto del email
 * @param textoHtml
 *            Versin HTML del email
 * @param datosAdjunto
 *            Fichero adjunto si existe.
 * @param toUser
 *            Usuario destino
 * @param alias
 * @param password
 * @throws ExcepcionErrorInterno
 *             No se ha podido enviar el email.
 */
public void sendSignMailByServer(String subject, String mailTo, String texto, String htmlTexto, String alias,
        String password) throws ExcepcionErrorInterno {
    // Preparamos el envio
    MultiPartEmail mail;
    try {
        mail = SendMailUtil.getCurrentInstance().buildMessage(subject, mailTo, texto, htmlTexto, alias,
                password);
        // mail.setDebug(true);
        String id = mail.send();
        if (log.isDebugEnabled()) {
            log.debug("Nuevo email enviado, con el identificador: " + id);
            mail.getMimeMessage().writeTo(System.out);
        }
    } catch (ExcepcionErrorInterno e) {
        log.warn(e.getMessage());
        throw new ExcepcionErrorInterno(CodigoError.ERROR_SEND_MAIL, e.getMessage(), e);
    } catch (ExcepcionCertificadoNoEncontrado e) {
        log.warn(e.getMessage());
        throw new ExcepcionErrorInterno(CodigoError.ERROR_SEND_MAIL, e.getMessage(), e);
    } catch (EmailException e) {
        log.warn(e.getMessage());
        throw new ExcepcionErrorInterno(CodigoError.ERROR_SEND_MAIL, e.getMessage(), e);
    } catch (IOException e) {
        log.warn(e.getMessage());
        throw new ExcepcionErrorInterno(CodigoError.ERROR_SEND_MAIL, e.getMessage(), e);
    } catch (MessagingException e) {
        log.warn(e.getMessage());
        throw new ExcepcionErrorInterno(CodigoError.ERROR_SEND_MAIL, e.getMessage(), e);
    }
}