Example usage for javax.mail Multipart addBodyPart

List of usage examples for javax.mail Multipart addBodyPart

Introduction

In this page you can find the example usage for javax.mail Multipart addBodyPart.

Prototype

public synchronized void addBodyPart(BodyPart part) throws MessagingException 

Source Link

Document

Adds a Part to the multipart.

Usage

From source file:com.panet.imeta.job.entries.mail.JobEntryMail.java

public Result execute(Result result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();

    File masterZipfile = null;/*w w w  .j  av a  2  s.  c  om*/

    // Send an e-mail...
    // create some properties and get the default Session
    Properties props = new Properties();
    if (Const.isEmpty(server)) {
        log.logError(toString(), Messages.getString("JobMail.Error.HostNotSpecified"));

        result.setNrErrors(1L);
        result.setResult(false);
        return result;
    }

    String protocol = "smtp";
    if (usingSecureAuthentication) {
        if (secureConnectionType.equals("TLS")) {
            // Allow TLS authentication
            props.put("mail.smtp.starttls.enable", "true");
        } else {

            protocol = "smtps";
            // required to get rid of a SSL exception :
            // nested exception is:
            // javax.net.ssl.SSLException: Unsupported record version
            // Unknown
            props.put("mail.smtps.quitwait", "false");
        }

    }

    props.put("mail." + protocol + ".host", environmentSubstitute(server));
    if (!Const.isEmpty(port))
        props.put("mail." + protocol + ".port", environmentSubstitute(port));
    boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG;

    if (debug)
        props.put("mail.debug", "true");

    if (usingAuthentication) {
        props.put("mail." + protocol + ".auth", "true");

        /*
         * authenticator = new Authenticator() { protected
         * PasswordAuthentication getPasswordAuthentication() { return new
         * PasswordAuthentication(
         * StringUtil.environmentSubstitute(Const.NVL(authenticationUser,
         * "")),
         * StringUtil.environmentSubstitute(Const.NVL(authenticationPassword
         * , "")) ); } };
         */
    }

    Session session = Session.getInstance(props);
    session.setDebug(debug);

    try {
        // create a message
        Message msg = new MimeMessage(session);

        // set message priority
        if (usePriority) {
            String priority_int = "1";
            if (priority.equals("low")) {
                priority_int = "3";
            }
            if (priority.equals("normal")) {
                priority_int = "2";
            }

            msg.setHeader("X-Priority", priority_int); // (String)int
            // between 1= high
            // and 3 = low.
            msg.setHeader("Importance", importance);
            // seems to be needed for MS Outlook.
            // where it returns a string of high /normal /low.
        }

        // Set Mail sender (From)
        String sender_address = environmentSubstitute(replyAddress);
        if (!Const.isEmpty(sender_address)) {
            String sender_name = environmentSubstitute(replyName);
            if (!Const.isEmpty(sender_name))
                sender_address = sender_name + '<' + sender_address + '>';
            msg.setFrom(new InternetAddress(sender_address));
        } else {
            throw new MessagingException(Messages.getString("JobMail.Error.ReplyEmailNotFilled"));
        }

        // set Reply to addresses
        String reply_to_address = environmentSubstitute(replyToAddresses);
        if (!Const.isEmpty(reply_to_address)) {
            // Split the mail-address: space separated
            String[] reply_Address_List = environmentSubstitute(reply_to_address).split(" ");
            InternetAddress[] address = new InternetAddress[reply_Address_List.length];
            for (int i = 0; i < reply_Address_List.length; i++)
                address[i] = new InternetAddress(reply_Address_List[i]);
            msg.setReplyTo(address);
        }

        // Split the mail-address: space separated
        String destinations[] = environmentSubstitute(destination).split(" ");
        InternetAddress[] address = new InternetAddress[destinations.length];
        for (int i = 0; i < destinations.length; i++)
            address[i] = new InternetAddress(destinations[i]);
        msg.setRecipients(Message.RecipientType.TO, address);

        if (!Const.isEmpty(destinationCc)) {
            // Split the mail-address Cc: space separated
            String destinationsCc[] = environmentSubstitute(destinationCc).split(" ");
            InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
            for (int i = 0; i < destinationsCc.length; i++)
                addressCc[i] = new InternetAddress(destinationsCc[i]);

            msg.setRecipients(Message.RecipientType.CC, addressCc);
        }

        if (!Const.isEmpty(destinationBCc)) {
            // Split the mail-address BCc: space separated
            String destinationsBCc[] = environmentSubstitute(destinationBCc).split(" ");
            InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
            for (int i = 0; i < destinationsBCc.length; i++)
                addressBCc[i] = new InternetAddress(destinationsBCc[i]);

            msg.setRecipients(Message.RecipientType.BCC, addressBCc);
        }
        String realSubject = environmentSubstitute(subject);
        if (!Const.isEmpty(realSubject)) {
            msg.setSubject(realSubject);
        }

        msg.setSentDate(new Date());
        StringBuffer messageText = new StringBuffer();

        if (comment != null) {
            messageText.append(environmentSubstitute(comment)).append(Const.CR).append(Const.CR);
        }
        if (!onlySendComment) {

            messageText.append(Messages.getString("JobMail.Log.Comment.Job")).append(Const.CR);
            messageText.append("-----").append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobName") + "    : ")
                    .append(parentJob.getJobMeta().getName()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobDirectory") + "  : ")
                    .append(parentJob.getJobMeta().getDirectory()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobEntry") + "   : ").append(getName())
                    .append(Const.CR);
            messageText.append(Const.CR);
        }

        if (includeDate) {
            messageText.append(Const.CR).append(Messages.getString("JobMail.Log.Comment.MsgDate") + ": ")
                    .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR);
        }
        if (!onlySendComment && result != null) {
            messageText.append(Messages.getString("JobMail.Log.Comment.PreviousResult") + ":").append(Const.CR);
            messageText.append("-----------------").append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobEntryNr") + "         : ")
                    .append(result.getEntryNr()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Errors") + "               : ")
                    .append(result.getNrErrors()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesRead") + "           : ")
                    .append(result.getNrLinesRead()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesWritten") + "        : ")
                    .append(result.getNrLinesWritten()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesInput") + "          : ")
                    .append(result.getNrLinesInput()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesOutput") + "         : ")
                    .append(result.getNrLinesOutput()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesUpdated") + "        : ")
                    .append(result.getNrLinesUpdated()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Status") + "  : ")
                    .append(result.getExitStatus()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Result") + "               : ")
                    .append(result.getResult()).append(Const.CR);
            messageText.append(Const.CR);
        }

        if (!onlySendComment && (!Const.isEmpty(environmentSubstitute(contactPerson))
                || !Const.isEmpty(environmentSubstitute(contactPhone)))) {
            messageText.append(Messages.getString("JobMail.Log.Comment.ContactInfo") + " :").append(Const.CR);
            messageText.append("---------------------").append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.PersonToContact") + " : ")
                    .append(environmentSubstitute(contactPerson)).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Tel") + "  : ")
                    .append(environmentSubstitute(contactPhone)).append(Const.CR);
            messageText.append(Const.CR);
        }

        // Include the path to this job entry...
        if (!onlySendComment) {
            JobTracker jobTracker = parentJob.getJobTracker();
            if (jobTracker != null) {
                messageText.append(Messages.getString("JobMail.Log.Comment.PathToJobentry") + ":")
                        .append(Const.CR);
                messageText.append("------------------------").append(Const.CR);

                addBacktracking(jobTracker, messageText);
            }
        }

        Multipart parts = new MimeMultipart();
        MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
        // 1st part

        if (useHTML) {
            if (!Const.isEmpty(getEncoding())) {
                part1.setContent(messageText.toString(), "text/html; " + "charset=" + getEncoding());
            } else {
                part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1");
            }

        }

        else
            part1.setText(messageText.toString());

        parts.addBodyPart(part1);

        if (includingFiles && result != null) {
            List<ResultFile> resultFiles = result.getResultFilesList();
            if (resultFiles != null && !resultFiles.isEmpty()) {
                if (!zipFiles) {
                    // Add all files to the message...
                    //
                    for (ResultFile resultFile : resultFiles) {
                        FileObject file = resultFile.getFile();
                        if (file != null && file.exists()) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType())
                                    found = true;
                            }
                            if (found) {
                                // create a data source
                                MimeBodyPart files = new MimeBodyPart();
                                URLDataSource fds = new URLDataSource(file.getURL());

                                // get a data Handler to manipulate this
                                // file type;
                                files.setDataHandler(new DataHandler(fds));
                                // include the file in the data source
                                files.setFileName(file.getName().getBaseName());
                                // add the part with the file in the
                                // BodyPart();
                                parts.addBodyPart(files);

                                log.logBasic(toString(),
                                        "Added file '" + fds.getName() + "' to the mail message.");
                            }
                        }
                    }
                } else {
                    // create a single ZIP archive of all files
                    masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR
                            + environmentSubstitute(zipFilename));
                    ZipOutputStream zipOutputStream = null;
                    try {
                        zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));

                        for (ResultFile resultFile : resultFiles) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType())
                                    found = true;
                            }
                            if (found) {
                                FileObject file = resultFile.getFile();
                                ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName());
                                zipOutputStream.putNextEntry(zipEntry);

                                // Now put the content of this file into
                                // this archive...
                                BufferedInputStream inputStream = new BufferedInputStream(
                                        KettleVFS.getInputStream(file));
                                int c;
                                while ((c = inputStream.read()) >= 0) {
                                    zipOutputStream.write(c);
                                }
                                inputStream.close();
                                zipOutputStream.closeEntry();

                                log.logBasic(toString(), "Added file '" + file.getName().getURI()
                                        + "' to the mail message in a zip archive.");
                            }
                        }
                    } catch (Exception e) {
                        log.logError(toString(), "Error zipping attachement files into file ["
                                + masterZipfile.getPath() + "] : " + e.toString());
                        log.logError(toString(), Const.getStackTracker(e));
                        result.setNrErrors(1);
                    } finally {
                        if (zipOutputStream != null) {
                            try {
                                zipOutputStream.finish();
                                zipOutputStream.close();
                            } catch (IOException e) {
                                log.logError(toString(),
                                        "Unable to close attachement zip file archive : " + e.toString());
                                log.logError(toString(), Const.getStackTracker(e));
                                result.setNrErrors(1);
                            }
                        }
                    }

                    // Now attach the master zip file to the message.
                    if (result.getNrErrors() == 0) {
                        // create a data source
                        MimeBodyPart files = new MimeBodyPart();
                        FileDataSource fds = new FileDataSource(masterZipfile);
                        // get a data Handler to manipulate this file type;
                        files.setDataHandler(new DataHandler(fds));
                        // include the file in th e data source
                        files.setFileName(fds.getName());
                        // add the part with the file in the BodyPart();
                        parts.addBodyPart(files);
                    }
                }
            }
        }
        msg.setContent(parts);

        Transport transport = null;
        try {
            transport = session.getTransport(protocol);
            if (usingAuthentication) {
                if (!Const.isEmpty(port)) {
                    transport.connect(environmentSubstitute(Const.NVL(server, "")),
                            Integer.parseInt(environmentSubstitute(Const.NVL(port, ""))),
                            environmentSubstitute(Const.NVL(authenticationUser, "")),
                            environmentSubstitute(Const.NVL(authenticationPassword, "")));
                } else {
                    transport.connect(environmentSubstitute(Const.NVL(server, "")),
                            environmentSubstitute(Const.NVL(authenticationUser, "")),
                            environmentSubstitute(Const.NVL(authenticationPassword, "")));
                }
            } else {
                transport.connect();
            }
            transport.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (transport != null)
                transport.close();
        }
    } catch (IOException e) {
        log.logError(toString(), "Problem while sending message: " + e.toString());
        result.setNrErrors(1);
    } catch (MessagingException mex) {
        log.logError(toString(), "Problem while sending message: " + mex.toString());
        result.setNrErrors(1);

        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;

                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    log.logError(toString(), "    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++) {
                        log.logError(toString(), "         " + invalid[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    log.logError(toString(), "    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++) {
                        log.logError(toString(), "         " + validUnsent[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    // System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++) {
                        log.logError(toString(), "         " + validSent[i]);
                        result.setNrErrors(1);
                    }
                }
            }
            if (ex instanceof MessagingException) {
                ex = ((MessagingException) ex).getNextException();
            } else {
                ex = null;
            }
        } while (ex != null);
    } finally {
        if (masterZipfile != null && masterZipfile.exists()) {
            masterZipfile.delete();
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }

    return result;
}

From source file:com.zacwolf.commons.email.Email.java

public Multipart getAsMultipart() throws MessagingException {
    /** First we create the "related" htmlmultipart for the html email content:
     * ?//w w w  .  j av a 2  s  .  c  o  m
     *  msg.setContent()                            
     * ?
     *  htmlmultipart [MimeMultipart("related")]  
     * ?
     *  htmlmessageBodyPart [MimeBodyPart]      
     * 
     *  EmailAttachment(INLINE) [MimeBodyPart] 
     * 
     *  EmailAttachment(INLINE) [BodyPart]     
     * 
     * 
     * 
     **/
    final Multipart htmlmultipart = new MimeMultipart("related");
    final BodyPart htmlmessageBodyPart = new MimeBodyPart();
    htmlmultipart.addBodyPart(htmlmessageBodyPart);
    final org.jsoup.nodes.Document doc = Jsoup.parse(getBody(), "UTF-8");
    prepareImgs(doc, htmlmultipart);
    prepare(doc);
    htmlmessageBodyPart.setContent(doc.toString(), "text/html; charset=utf-8");

    // populate the top multipart
    Multipart msgmultipart = htmlmultipart;
    if (getBodyPlainText() != null) {// Now create a plain-text body part
        /**
         * If there is a plain text attachment (and their should always be one),
         * then an "alternative" type MimeMultipart is added to the structure
         * ?
         *  msg.setContent()                                
         * ?
         *  msgmultipart [MimeMultipart("alternative")]   
         * ?
         *  htmlcontent [MimeBodyPart]                  
         * ?
         *  htmlmultipart [MimeMultipart("related")]  
         * ?
         *  htmlmessageBodyPart [MimeBodyPart]      
         * 
         *  EmailAttachment(INLINE) [MimeBodyPart] 
         * 
         *  EmailAttachment(INLINE) [MimeBodyPart] 
         * 
         * 
         * 
         * plaintxtBodypart [MimeBodyPart]              
         * .setText(message_plaintxt)                   
         * 
         * 
         * 
         */
        msgmultipart = new MimeMultipart("alternative");
        final BodyPart plaintxtBodyPart = new MimeBodyPart();
        plaintxtBodyPart.setText(getBodyPlainText());
        final BodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(htmlmultipart);
        msgmultipart.addBodyPart(plaintxtBodyPart);
        msgmultipart.addBodyPart(htmlBodyPart);
    }

    /**
     * If there are non-inline attachments, then a "mixed" type 
     * MimeMultipart object has to be added to the structure
     * ?
     *  msg.setContent()                                    
     * ?
     *  msgmultipart [MimeMultipart("mixed")]             
     * ?
     *  wrap [MimeBodyPart]                             
     * ?
     *  msgmultipart [MimeMultipart("alternative")]   
     * ?
     *  htmlcontent [MimeBodyPart]                  
     * ?
     *  htmlmultipart [MimeMultipart("related")]  
     * ?
     *  htmlmessageBodyPart [MimeBodyPart]      
     * 
     *  EmailAttachment(INLINE) [MimeBodyPart] 
     * 
     *  EmailAttachment(INLINE) [MimeBodyPart] 
     * 
     * 
     * 
     * plaintxtBodypart [MimeBodyPart]              
     * .setText(message_plaintxt)                   
     * 
     * 
     * 
     *  EmailAttachment (non-inline) [MimeBodyPart]     
     * 
     *  EmailAttachment (non-inline) [MimeBodyPart]     
     * 
     * 
     * 
     */
    Multipart mixed = msgmultipart;
    final Set<EmailAttachment> noninlineattachments = new HashSet<EmailAttachment>();
    for (EmailAttachment attach : getAttachments().values())
        if (attach.disposition != null && !attach.disposition.equals(MimeBodyPart.INLINE))
            noninlineattachments.add(attach);
    // If there are non-IN-LINE attachments, we'll have to create another layer "mixed" MultiPart object
    if (!noninlineattachments.isEmpty()) {
        mixed = new MimeMultipart("mixed");
        //Multiparts are not themselves containers, so create a wrapper BodyPart container
        final BodyPart wrap = new MimeBodyPart();
        wrap.setContent(msgmultipart);
        mixed.addBodyPart(wrap);
        for (EmailAttachment attach : noninlineattachments)
            mixed.addBodyPart(attach);
    }
    return mixed;
}

From source file:cl.cnsv.wsreporteproyeccion.service.ReporteProyeccionServiceImpl.java

@Override
public OutputObtenerCotizacionInternetVO obtenerCotizacionInternet(InputObtenerCotizacionInternetVO input) {

    //<editor-fold defaultstate="collapsed" desc="Inicio">
    LOGGER.info("Iniciando el metodo obtenerCotizacionInternet...");
    OutputObtenerCotizacionInternetVO output = new OutputObtenerCotizacionInternetVO();
    String codigo;//from   w  w w . ja  v  a  2 s.  co m
    String mensaje;
    XStream xStream = new XStream();
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Validacion de entrada">
    OutputVO outputValidacion = validator.validarObtenerCotizacionInternet(input);
    if (!Integer.valueOf(Propiedades.getFuncProperty("codigo.ok")).equals(outputValidacion.getCodigo())) {
        codigo = Integer.toString(outputValidacion.getCodigo());
        mensaje = outputValidacion.getMensaje();
        LOGGER.info(mensaje);
        output.setCodigo(codigo);
        output.setMensaje(mensaje);
        return output;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Ir a JasperServer">
    String numeroCotizacion = input.getNumeroCotizacion();
    InputCotizacionInternet inputCotizacionInternet = new InputCotizacionInternet();
    inputCotizacionInternet.setIdCotizacion(numeroCotizacion);
    String xmlInputCotizacionInternet = xStream.toXML(inputCotizacionInternet);
    LOGGER.info("Llamado a jasperserver: \n" + xmlInputCotizacionInternet);
    servicioJasperServer = new ServicioJasperServerJerseyImpl();
    ResultadoDocumentoVO outputJasperServer;
    try {
        outputJasperServer = servicioJasperServer.buscarArchivoByCotizacion(inputCotizacionInternet);
        String xmlOutputJasperServer = xStream.toXML(outputJasperServer);
        LOGGER.info("Respuesta de jasperserver: \n" + xmlOutputJasperServer);
        String codigoJasperServer = outputJasperServer.getCodigo();
        if (!Propiedades.getFuncProperty("jasperserver.ok.codigo").equals(codigoJasperServer)) {
            codigo = Propiedades.getFuncProperty("jasperserver.error.codigo");
            mensaje = Propiedades.getFuncProperty("jasperserver.error.mensaje");
            LOGGER.info(mensaje + ": " + outputJasperServer.getMensaje());
            output.setCodigo(codigo);
            output.setMensaje(mensaje);
            return output;
        }
    } catch (Exception e) {
        codigo = Propiedades.getFuncProperty("jasperserver.error.codigo");
        mensaje = Propiedades.getFuncProperty("jasperserver.error.mensaje");
        LOGGER.error(mensaje + ": " + e.getMessage(), e);
        output.setCodigo(codigo);
        output.setMensaje(mensaje);
        return output;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Ir a buscar datos email al servicio cotizador vida">
    ClienteServicioCotizadorVida clienteCotizadorVida;
    try {
        clienteCotizadorVida = new ClienteServicioCotizadorVida();
    } catch (Exception e) {
        codigo = Propiedades.getFuncProperty("ws.cotizadorvida.error.login.codigo");
        mensaje = Propiedades.getFuncProperty("ws.cotizadorvida.error.login.mensaje");
        LOGGER.error(mensaje + ": " + e.getMessage(), e);
        output.setCodigo(codigo);
        output.setMensaje(mensaje);
        return output;
    }

    //Se busca el nombre del asegurado, glosa del plan y numero de propuesta        
    LOGGER.info("Llamado a getDatosEmailCotizacionInternet - cotizadorVida: \n" + xmlInputCotizacionInternet);
    OutputEmailCotizacionInternetVO outputEmail;
    try {
        outputEmail = clienteCotizadorVida.getDatosEmailCotizacionInternet(inputCotizacionInternet);
        String xmlOutputEmail = xStream.toXML(outputEmail);
        LOGGER.info("Respuesta de getDatosEmailCotizacionInternet - cotizadorVida: \n" + xmlOutputEmail);
        String codigoOutputEmail = outputEmail.getCodigo();
        if (!Propiedades.getFuncProperty("ws.cotizadorvida.codigo.ok").equals(codigoOutputEmail)) {
            codigo = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.codigo");
            mensaje = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.mensaje");
            LOGGER.info(mensaje + ": " + outputEmail.getMensaje());
            output.setCodigo(codigo);
            output.setMensaje(mensaje);
            return output;
        }

    } catch (Exception e) {
        codigo = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.codigo");
        mensaje = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.mensaje");
        LOGGER.error(mensaje + ": " + e.getMessage(), e);
        output.setCodigo(codigo);
        output.setMensaje(mensaje);
        return output;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Enviar correo con documento adjunto">
    String documento = outputJasperServer.getDocumento();
    try {
        EmailVO datosEmail = outputEmail.getDatosEmail();
        String htmlBody = Propiedades.getFuncProperty("email.html");
        String nombreAsegurable = datosEmail.getNombreAsegurable();
        if (nombreAsegurable == null) {
            nombreAsegurable = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[NOMBRE_ASEGURADO]", nombreAsegurable);
        String glosaPlan = datosEmail.getGlosaPlan();
        if (glosaPlan == null) {
            glosaPlan = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[GLOSA_PLAN]", glosaPlan);
        String numeroPropuesta = datosEmail.getNumeroPropuesta();
        if (numeroPropuesta == null) {
            numeroPropuesta = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[NRO_PROPUESTA]", numeroPropuesta);

        //Parametrizar imagenes
        String imgBulletBgVerde = Propiedades.getFuncProperty("email.images.bulletbgverde");
        if (imgBulletBgVerde == null) {
            imgBulletBgVerde = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_BULLET_BG_VERDE]", imgBulletBgVerde);

        String imgFace = Propiedades.getFuncProperty("email.images.face");
        if (imgFace == null) {
            imgFace = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_FACE]", imgFace);

        String imgTwitter = Propiedades.getFuncProperty("email.images.twitter");
        if (imgTwitter == null) {
            imgTwitter = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_TWITTER]", imgTwitter);

        String imgYoutube = Propiedades.getFuncProperty("email.images.youtube");
        if (imgYoutube == null) {
            imgYoutube = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_YOUTUBE]", imgYoutube);

        String imgMail15 = Propiedades.getFuncProperty("email.images.mail00115");
        if (imgMail15 == null) {
            imgMail15 = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_MAIL_00115]", imgMail15);

        String imgFono = Propiedades.getFuncProperty("email.images.fono");
        if (imgFono == null) {
            imgFono = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_FONO]", imgFono);

        String imgMail16 = Propiedades.getFuncProperty("email.images.mail00116");
        if (imgMail16 == null) {
            imgMail16 = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_MAIL_00116]", imgMail16);

        byte[] attachmentData = Base64.decodeBase64(documento);

        final String username = Propiedades.getKeyProperty("email.username");
        final String encryptedPassword = Propiedades.getKeyProperty("email.password");
        String privateKeyFile = Propiedades.getConfProperty("KEY");
        CryptoUtil cryptoUtil = new CryptoUtil("", privateKeyFile);
        final String password = cryptoUtil.decryptData(encryptedPassword);
        final String auth = Propiedades.getFuncProperty("email.auth");
        final String starttls = Propiedades.getFuncProperty("email.starttls");
        final String host = Propiedades.getFuncProperty("email.host");
        final String port = Propiedades.getFuncProperty("email.port");

        //Log de datos de correo
        String strDatosCorreo = "username: " + username + "\n" + "auth: " + auth + "\n" + "host: " + host
                + "\n";
        LOGGER.info("Datos correo: \n".concat(strDatosCorreo));

        Properties props = new Properties();
        props.put("mail.smtp.auth", auth);
        if (!"0".equals(starttls)) {
            props.put("mail.smtp.starttls.enable", starttls);
        }
        props.put("mail.smtp.host", host);
        if (!"0".equals(port)) {
            props.put("mail.smtp.port", port);
        }
        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        String fileName = Propiedades.getFuncProperty("tmp.cotizacionInternet.file.name");
        fileName = fileName.replaceAll("%s", numeroPropuesta);
        fileName = fileName + ".pdf";

        // creates a new e-mail message
        Message msg = new MimeMessage(session);
        String from = Propiedades.getFuncProperty("email.from");
        msg.setFrom(new InternetAddress(from));
        //TODO considerar email de prueba o email del asegurado            
        String emailTo;
        if ("1".equals(Propiedades.getFuncProperty("email.to.test"))) {
            emailTo = Propiedades.getFuncProperty("email.to.mail");
        } else {
            emailTo = datosEmail.getEmail();
        }
        InternetAddress[] toAddresses = { new InternetAddress(emailTo) };
        msg.setRecipients(Message.RecipientType.TO, toAddresses);
        String subject = Propiedades.getFuncProperty("email.subject");
        msg.setSubject(subject);
        msg.setSentDate(new Date());

        // creates message part
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(htmlBody, "text/html");

        // creates multi-part
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        // adds attachments
        MimeBodyPart attachPart = new MimeBodyPart();
        DataSource dataSource = new ByteArrayDataSource(attachmentData, "application/pdf");
        attachPart.setDataHandler(new DataHandler(dataSource));
        attachPart.setFileName(fileName);
        multipart.addBodyPart(attachPart);

        // sets the multi-part as e-mail's content
        msg.setContent(multipart);

        // sends the e-mail
        Transport.send(msg);

    } catch (Exception ex) {
        codigo = Propiedades.getFuncProperty("email.error.codigo");
        mensaje = Propiedades.getFuncProperty("email.error.mensaje");
        LOGGER.error(mensaje + ": " + ex.getMessage(), ex);
        output.setCodigo(codigo);
        output.setMensaje(mensaje);
        return output;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Termino">
    codigo = Propiedades.getFuncProperty("codigo.ok");
    mensaje = Propiedades.getFuncProperty("mensaje.ok");
    output.setCodigo(codigo);
    output.setMensaje(mensaje);
    return output;
    //</editor-fold>

}

From source file:FirstStatMain.java

private void btnsendemailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnsendemailActionPerformed
    final String senderemail = txtEmailfrom.getText();
    final String sendPass = txtPassword.getText();
    String send_to = txtEmailto.getText();
    String email_sub = txtemailsbj.getText();
    String email_body = tABody.getText();

    Properties prop = new Properties();
    prop.put("mail.smtp.host", "smtp.gmail.com");
    prop.put("mail.smtp.socketFactory.port", "465");
    prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    prop.put("mail.smtp.auth", "true");
    prop.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(prop, new javax.mail.Authenticator() {
        @Override/*from w ww.j a va  2 s .  c  o m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(senderemail, sendPass);
        }
    });
    try {
        /* Message Header*/
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(senderemail));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(send_to));
        message.setSubject(email_sub);
        /*setting text message*/
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(email_body);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        /*attaching file*/
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(file_path);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(txtattachmentname.getText());
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);
        Transport.send(message);
        JOptionPane.showMessageDialog(rootPane, "Message sent");
    } catch (Exception e) {
        JOptionPane.showMessageDialog(rootPane, e);
    }
}

From source file:Implement.Service.ProviderServiceImpl.java

@Override
public boolean sendEmailReferral(String data, int providerID, String baseUrl) throws MessagingException {
    final String username = "registration@youtripper.com";
    final String password = "Tripregister190515";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "mail.youtripper.com");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//from www  . j  ava  2  s .com
    });

    String title = "You have an invitation from your friend.";

    JsonObject jsonObject = gson.fromJson(data, JsonObject.class);
    String content = jsonObject.get("content").getAsString();
    JsonArray sportsArray = jsonObject.get("emails").getAsJsonArray();
    ArrayList<String> listEmail = new ArrayList<>();
    if (sportsArray != null) {
        for (int i = 0; i < sportsArray.size(); i++) {
            listEmail.add(sportsArray.get(i).getAsString());
        }
    }

    String path = System.getProperty("catalina.base");
    MimeBodyPart backgroundImage = new MimeBodyPart();
    // attach the file to the message
    DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/backgroundImage.png"));
    backgroundImage.setDataHandler(new DataHandler(source));
    backgroundImage.setFileName("backgroundImage.png");
    backgroundImage.setDisposition(MimeBodyPart.INLINE);
    backgroundImage.setHeader("Content-ID", "<bg_Icon>"); // cid:image_cid

    MimeBodyPart giftImage = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/emailGift.png"));
    giftImage.setDataHandler(new DataHandler(source));
    giftImage.setFileName("emailGift.png");
    giftImage.setDisposition(MimeBodyPart.INLINE);
    giftImage.setHeader("Content-ID", "<gift_Icon>"); // cid:image_cid

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "US-ASCII", "html");

    Multipart mp = new MimeMultipart("related");
    mp.addBodyPart(mbp1);
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("registration@youtripper.com"));
    String addresses = "";
    for (int i = 0; i < listEmail.size(); i++) {
        if (i < listEmail.size() - 1) {
            addresses = addresses + listEmail.get(i) + ",";
        } else {
            addresses = addresses + listEmail.get(i);
        }
    }

    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(addresses));

    message.setSubject(title);
    message.setContent(mp);
    message.saveChanges();
    try {
        Transport.send(message);
    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("sent");
    return true;
}

From source file:Implement.Service.ProviderServiceImpl.java

@Override
public boolean sendMail(HttpServletRequest request, String providerName, int providerID, String baseUrl)
        throws MessagingException {
    final String username = "registration@youtripper.com";
    final String password = "Tripregister190515";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtpm.csloxinfo.com");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/* w  w w. j  a  v  a  2 s. com*/
    });

    //Create data for referral
    java.util.Date date = new java.util.Date();
    String s = providerID + (new Timestamp(date.getTime()).toString());
    MessageDigest m = null;
    try {
        m = MessageDigest.getInstance("MD5");

    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(ProviderServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    m.update(s.getBytes(), 0, s.length());
    String md5 = (new BigInteger(1, m.digest()).toString(16));

    String title = "You have an invitation from your friend.";
    String receiver = request.getParameter("email");

    //        StringBuilder messageContentHtml = new StringBuilder();
    //        messageContentHtml.append(request.getParameter("message") + "<br />\n");
    //        messageContentHtml.append("You can become a provider from here:  " + baseUrl + "/Common/Provider/SignupReferral/" + md5);
    //        String messageContent = messageContentHtml.toString();
    String emailContent = "  <div style='background: url(cid:bg_Icon) no-repeat;background-color:#ebebec;text-align: center;width:610px;height:365px'>"
            + "            <p style='font-size:16px;padding-top: 45px; padding-bottom: 15px;'>Your friend <b>"
            + providerName + "</b> has invited you to complete purchase via</p>"
            + "            <a href='http://youtripper.com/Common/Provider/SignupReferral/" + md5
            + "' style='width: 160px;height: 50px;border-radius: 5px;border: 0;"
            + "                    background-color: #ff514e;font-size: 14px;font-weight: bolder;color: #fff;display: block;line-height: 50px;margin: 0 auto;text-decoration:none;' >Refferal Link</a>"
            + "            <p style='font-size:16px;margin:30px;'><b>" + providerName
            + "</b> will get 25 credit</p>"
            + "            <a href='http://youtripper.com' target='_blank'><img src='cid:gift_Icon' width='90' height='90'></a>"
            + "            <a href='http://youtripper.com' target='_blank' style='font-size:10px;color:#939598;text-decoration:none'><p>from www.youtripper.com</p></a>"
            + "            " + "            " + "        </div>";

    String path = System.getProperty("catalina.base");
    MimeBodyPart backgroundImage = new MimeBodyPart();
    // attach the file to the message
    DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/backgroundImage.png"));
    backgroundImage.setDataHandler(new DataHandler(source));
    backgroundImage.setFileName("backgroundImage.png");
    backgroundImage.setDisposition(MimeBodyPart.INLINE);
    backgroundImage.setHeader("Content-ID", "<bg_Icon>"); // cid:image_cid

    MimeBodyPart giftImage = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/emailGift.png"));
    giftImage.setDataHandler(new DataHandler(source));
    giftImage.setFileName("emailGift.png");
    giftImage.setDisposition(MimeBodyPart.INLINE);
    giftImage.setHeader("Content-ID", "<gift_Icon>"); // cid:image_cid

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(emailContent, "US-ASCII", "html");

    Multipart mp = new MimeMultipart("related");
    mp.addBodyPart(mbp1);
    mp.addBodyPart(backgroundImage);
    mp.addBodyPart(giftImage);
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("registration@youtripper.com"));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));
    message.setSubject(title);
    message.setContent(mp);
    message.saveChanges();
    Transport.send(message);

    ReferralDTO referral = new ReferralDTO(providerID, receiver, String.valueOf(System.currentTimeMillis()),
            md5, 0);
    referralDAO.insertNewReferral(referral);
    return true;
}

From source file:org.kuali.test.utils.Utils.java

/**
 * /* w  ww. j  av  a2s  . co  m*/
 * @param configuration
 * @param overrideEmail
 * @param testSuite
 * @param testHeader
 * @param testResults
 * @param errorCount
 * @param warningCount
 * @param successCount 
 */
public static void sendMail(KualiTestConfigurationDocument.KualiTestConfiguration configuration,
        String overrideEmail, TestSuite testSuite, TestHeader testHeader, List<File> testResults,
        int errorCount, int warningCount, int successCount) {

    if (StringUtils.isNotBlank(configuration.getEmailSetup().getFromAddress())
            && StringUtils.isNotBlank(configuration.getEmailSetup().getMailHost())) {

        String[] toAddresses = getEmailToAddresses(configuration, testSuite, testHeader);

        if (toAddresses.length > 0) {
            Properties props = new Properties();
            props.put("mail.smtp.host", configuration.getEmailSetup().getMailHost());
            Session session = Session.getDefaultInstance(props, null);

            try {
                Message msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress(configuration.getEmailSetup().getFromAddress()));

                if (StringUtils.isBlank(overrideEmail)) {
                    for (String recipient : toAddresses) {
                        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
                    }
                } else {
                    StringTokenizer st = new StringTokenizer(overrideEmail, ",");
                    while (st.hasMoreTokens()) {
                        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(st.nextToken()));
                    }
                }

                StringBuilder subject = new StringBuilder(configuration.getEmailSetup().getSubject());
                subject.append(" - Platform: ");
                if (testSuite != null) {
                    subject.append(testSuite.getPlatformName());
                    subject.append(", TestSuite: ");
                    subject.append(testSuite.getName());
                } else {
                    subject.append(testHeader.getPlatformName());
                    subject.append(", Test: ");
                    subject.append(testHeader.getTestName());
                }

                subject.append(" - [errors=");
                subject.append(errorCount);
                subject.append(", warnings=");
                subject.append(warningCount);
                subject.append(", successes=");
                subject.append(successCount);
                subject.append("]");

                msg.setSubject(subject.toString());

                StringBuilder msgtxt = new StringBuilder(256);
                msgtxt.append("Please see test output in the following attached files:\n");

                for (File f : testResults) {
                    msgtxt.append(f.getName());
                    msgtxt.append("\n");
                }

                // create and fill the first message part
                MimeBodyPart mbp1 = new MimeBodyPart();
                mbp1.setText(msgtxt.toString());

                // create the Multipart and add its parts to it
                Multipart mp = new MimeMultipart();
                mp.addBodyPart(mbp1);

                for (File f : testResults) {
                    if (f.exists() && f.isFile()) {
                        // create the second message part
                        MimeBodyPart mbp2 = new MimeBodyPart();

                        // attach the file to the message
                        mbp2.setDataHandler(new DataHandler(new FileDataSource(f)));
                        mbp2.setFileName(f.getName());
                        mp.addBodyPart(mbp2);
                    }
                }

                // add the Multipart to the message
                msg.setContent(mp);

                // set the Date: header
                msg.setSentDate(new Date());

                Transport.send(msg);
            } catch (MessagingException ex) {
                LOG.warn(ex.toString(), ex);
            }
        }
    }
}

From source file:com.flexoodb.common.FlexUtils.java

/**
* use this method to obtain a mimemessage with the file wrapped in it.
*
* @param  filename filename of the file.
* @param  data the file in bytes.//from w  w w  .  j a  v  a2  s.  c om
* @return a byte array of the mimemessage.
*/
static public byte[] wrapInMimeMessage(String filename, byte[] data) throws Exception {
    MimeMessage mimemessage = new MimeMessage(javax.mail.Session.getDefaultInstance(new Properties(), null));
    BodyPart messageBodyPart = new MimeBodyPart();
    Multipart multipart = new MimeMultipart();
    DataSource source = new ByteArrayDataSource(data, "application/octet-stream");
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);
    mimemessage.setContent(multipart);
    mimemessage.saveChanges();

    // finally pipe to an array so we can conver to string
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    mimemessage.writeTo(bos);
    return bos.toString().getBytes();
}

From source file:com.zacwolf.commons.email.Email.java

private void prepareImgs(final org.jsoup.nodes.Document doc, final Multipart htmlmultipart) {
    final Map<String, EmailAttachment> attachments = getAttachments();
    final org.jsoup.select.Elements imgs = doc.getElementsByTag("img");
    for (org.jsoup.nodes.Element img : imgs) {
        final String src = img.attr("src");
        final String cid = !src.startsWith("cid:") ? null : src.substring(4);
        try {/*from   www  . j a va  2 s. com*/
            EmailAttachment attachment;
            ByteArrayOutputStream baos;
            if (cid != null) {
                attachment = attachments.get(cid);
                img.attr("alt", attachment.getDescription());
                if (!img.attr("style").contains("display:"))//all inline images need the display:block; added for GMail compatability
                    img.attr("style", img.attr("style") + (!img.attr("style").endsWith(";") ? ";" : "")
                            + "display:block;");
                if (cid.toLowerCase().contains("_banner")
                        && doc.select("#banner").attr("style").contains("-radius")) {
                    BufferedImage image = makeRoundedBanner(
                            ImageIO.read(new ByteArrayInputStream(attachment.data)), 20);
                    doc.select("#contenttable").attr("style",
                            "width:" + image.getWidth() + "px;" + doc.select("#contenttable").attr("style"));
                    baos = new ByteArrayOutputStream();
                    try {
                        ImageIO.write(image, EmailAttachment.CONTENT_MIMETYPES.get(attachment.contenttype),
                                baos);
                    } finally {
                        baos.flush();
                    }
                    attachment = new EmailAttachment(attachment.filename, attachment.contenttype,
                            baos.toByteArray(), cid, "Rounded banner image");
                    if (htmlmultipart == null)
                        dataurlEncode(img, attachment);
                    if (doc.select("#footer").size() == 1
                            && doc.select("#footer").first().attr("style").contains("-radius")) {
                        Color bgcolor = Color.WHITE;
                        Color border = null;
                        String newstyle = "";
                        String[] styles = doc.select("#footer").first().attr("style").split(";");
                        for (String style : styles) {
                            if (style.startsWith("border"))
                                border = getColorFromStyle(style, null);
                            else if (style.startsWith("background-color:"))
                                bgcolor = getColorFromStyle(style, Color.WHITE);
                            else
                                newstyle += style + ";";
                        }
                        baos = new ByteArrayOutputStream();
                        try {
                            ImageIO.write(makeRoundedFooter(image.getWidth(), 20, bgcolor, border), "png",
                                    baos);
                        } finally {
                            baos.flush();
                        }
                        doc.select("#footer").first().parent()
                                .html("<td style=\"margin:0px;padding:0px;\" valign=\"top\" style=\"" + newstyle
                                        + "\"><img id=\"footer\" alt=\"rounded footer image\" src=\"cid:"
                                        + getREFID() + "_rounded_footer\" style=\"display:block;\" /></td>");
                    }
                    if (htmlmultipart == null)
                        dataurlEncode(doc.select("#footer").first(),
                                new EmailAttachment("footer.png", "image/png", baos.toByteArray(),
                                        getREFID() + "_rounded_footer", "Rounded footer image"));
                    else
                        htmlmultipart.addBodyPart(new EmailAttachment("footer.png", "image/png",
                                baos.toByteArray(), getREFID() + "_rounded_footer", "Rounded footer image"));
                } else if (htmlmultipart == null) {
                    dataurlEncode(img, attachment);
                }
                if (htmlmultipart != null)
                    htmlmultipart.addBodyPart(attachment);
            }
        } catch (Exception e) {
            throw new NullPointerException(
                    "Problem with embedding images into content.\nContact the content owner.\n\nERROR:" + e);
        }
    }
}

From source file:org.exist.xquery.modules.mail.SendEmailFunction.java

/**
 * Constructs a mail Object from an XML representation of an email
 *
 * The XML email Representation is expected to look something like this
 *
 * <mail>/*  ww  w.  j  a va  2 s  . com*/
 *    <from></from>
 *    <reply-to></reply-to>
 *    <to></to>
 *    <cc></cc>
 *    <bcc></bcc>
 *    <subject></subject>
 *    <message>
 *       <text charset="" encoding=""></text>
 *       <xhtml charset="" encoding=""></xhtml>
 *       <generic charset="" type="" encoding=""></generic>
 *    </message>
 *    <attachment mimetype="" filename=""></attachment>
 * </mail>
 *
 * @param mailElements   The XML mail Node
 * @return      A mail Object representing the XML mail Node
 */
private List<Message> parseMessageElement(Session session, List<Element> mailElements)
        throws IOException, MessagingException, TransformerException {
    List<Message> mails = new ArrayList<>();

    for (Element mailElement : mailElements) {
        //Make sure that message has a Mail node
        if (mailElement.getLocalName().equals("mail")) {
            //New message Object
            // create a message
            MimeMessage msg = new MimeMessage(session);

            ArrayList<InternetAddress> replyTo = new ArrayList<>();
            boolean fromWasSet = false;
            MimeBodyPart body = null;
            Multipart multibody = null;
            ArrayList<MimeBodyPart> attachments = new ArrayList<>();
            String firstContent = null;
            String firstContentType = null;
            String firstCharset = null;
            String firstEncoding = null;

            //Get the First Child
            Node child = mailElement.getFirstChild();
            while (child != null) {
                //Parse each of the child nodes
                if (child.getNodeType() == Node.ELEMENT_NODE && child.hasChildNodes()) {
                    switch (child.getLocalName()) {
                    case "from":
                        // set the from and to address
                        InternetAddress[] addressFrom = {
                                new InternetAddress(child.getFirstChild().getNodeValue()) };
                        msg.addFrom(addressFrom);
                        fromWasSet = true;
                        break;
                    case "reply-to":
                        // As we can only set the reply-to, not add them, let's keep
                        // all of them in a list
                        replyTo.add(new InternetAddress(child.getFirstChild().getNodeValue()));
                        msg.setReplyTo(replyTo.toArray(new InternetAddress[0]));
                        break;
                    case "to":
                        msg.addRecipient(Message.RecipientType.TO,
                                new InternetAddress(child.getFirstChild().getNodeValue()));
                        break;
                    case "cc":
                        msg.addRecipient(Message.RecipientType.CC,
                                new InternetAddress(child.getFirstChild().getNodeValue()));
                        break;
                    case "bcc":
                        msg.addRecipient(Message.RecipientType.BCC,
                                new InternetAddress(child.getFirstChild().getNodeValue()));
                        break;
                    case "subject":
                        msg.setSubject(child.getFirstChild().getNodeValue());
                        break;
                    case "header":
                        // Optional : You can also set your custom headers in the Email if you Want
                        msg.addHeader(((Element) child).getAttribute("name"),
                                child.getFirstChild().getNodeValue());
                        break;
                    case "message":
                        //If the message node, then parse the child text and xhtml nodes
                        Node bodyPart = child.getFirstChild();
                        while (bodyPart != null) {
                            if (bodyPart.getNodeType() != Node.ELEMENT_NODE)
                                continue;

                            Element elementBodyPart = (Element) bodyPart;
                            String content = null;
                            String contentType = null;

                            if (bodyPart.getLocalName().equals("text")) {
                                // Setting the Subject and Content Type
                                content = bodyPart.getFirstChild().getNodeValue();
                                contentType = "plain";
                            } else if (bodyPart.getLocalName().equals("xhtml")) {
                                //Convert everything inside <xhtml></xhtml> to text
                                TransformerFactory transFactory = TransformerFactory.newInstance();
                                Transformer transformer = transFactory.newTransformer();
                                DOMSource source = new DOMSource(bodyPart.getFirstChild());
                                StringWriter strWriter = new StringWriter();
                                StreamResult result = new StreamResult(strWriter);
                                transformer.transform(source, result);

                                content = strWriter.toString();
                                contentType = "html";
                            } else if (bodyPart.getLocalName().equals("generic")) {
                                // Setting the Subject and Content Type
                                content = elementBodyPart.getFirstChild().getNodeValue();
                                contentType = elementBodyPart.getAttribute("type");
                            }

                            // Now, time to store it
                            if (content != null && contentType != null && contentType.length() > 0) {
                                String charset = elementBodyPart.getAttribute("charset");
                                String encoding = elementBodyPart.getAttribute("encoding");

                                if (body != null && multibody == null) {
                                    multibody = new MimeMultipart("alternative");
                                    multibody.addBodyPart(body);
                                }

                                if (StringUtils.isEmpty(charset)) {
                                    charset = "UTF-8";
                                }

                                if (StringUtils.isEmpty(encoding)) {
                                    encoding = "quoted-printable";
                                }

                                if (body == null) {
                                    firstContent = content;
                                    firstCharset = charset;
                                    firstContentType = contentType;
                                    firstEncoding = encoding;
                                }
                                body = new MimeBodyPart();
                                body.setText(content, charset, contentType);
                                if (encoding != null) {
                                    body.setHeader("Content-Transfer-Encoding", encoding);
                                }
                                if (multibody != null)
                                    multibody.addBodyPart(body);
                            }

                            //next body part
                            bodyPart = bodyPart.getNextSibling();
                        }
                        break;
                    case "attachment":
                        Element attachment = (Element) child;
                        MimeBodyPart part;
                        // if mimetype indicates a binary resource, assume the content is base64 encoded
                        if (MimeTable.getInstance().isTextContent(attachment.getAttribute("mimetype"))) {
                            part = new MimeBodyPart();
                        } else {
                            part = new PreencodedMimeBodyPart("base64");
                        }
                        StringBuilder content = new StringBuilder();
                        Node attachChild = attachment.getFirstChild();
                        while (attachChild != null) {
                            if (attachChild.getNodeType() == Node.ELEMENT_NODE) {
                                TransformerFactory transFactory = TransformerFactory.newInstance();
                                Transformer transformer = transFactory.newTransformer();
                                DOMSource source = new DOMSource(attachChild);
                                StringWriter strWriter = new StringWriter();
                                StreamResult result = new StreamResult(strWriter);
                                transformer.transform(source, result);

                                content.append(strWriter.toString());
                            } else {
                                content.append(attachChild.getNodeValue());
                            }
                            attachChild = attachChild.getNextSibling();
                        }
                        part.setDataHandler(new DataHandler(new ByteArrayDataSource(content.toString(),
                                attachment.getAttribute("mimetype"))));
                        part.setFileName(attachment.getAttribute("filename"));
                        //                            part.setHeader("Content-Transfer-Encoding", "base64");
                        attachments.add(part);
                        break;
                    }
                }

                //next node
                child = child.getNextSibling();

            }
            // Lost from
            if (!fromWasSet)
                msg.setFrom();

            // Preparing content and attachments
            if (attachments.size() > 0) {
                if (multibody == null) {
                    multibody = new MimeMultipart("mixed");
                    if (body != null) {
                        multibody.addBodyPart(body);
                    }
                } else {
                    MimeMultipart container = new MimeMultipart("mixed");
                    MimeBodyPart containerBody = new MimeBodyPart();
                    containerBody.setContent(multibody);
                    container.addBodyPart(containerBody);
                    multibody = container;
                }
                for (MimeBodyPart part : attachments) {
                    multibody.addBodyPart(part);
                }
            }

            // And now setting-up content
            if (multibody != null) {
                msg.setContent(multibody);
            } else if (body != null) {
                msg.setText(firstContent, firstCharset, firstContentType);
                if (firstEncoding != null) {
                    msg.setHeader("Content-Transfer-Encoding", firstEncoding);
                }
            }

            msg.saveChanges();
            mails.add(msg);
        }
    }

    return mails;
}