Example usage for javax.mail.internet MimeMessage setContent

List of usage examples for javax.mail.internet MimeMessage setContent

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage setContent.

Prototype

@Override
public void setContent(Multipart mp) throws MessagingException 

Source Link

Document

This method sets the Message's content to a Multipart object.

Usage

From source file:com.szmslab.quickjavamail.send.MailSender.java

/**
 * ?????//from  ww  w .  ja v a 2s  .  c o m
 *
 * @param message
 *            
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 */
private void setContent(MimeMessage message) throws MessagingException, UnsupportedEncodingException {
    if (StringUtils.isBlank(html)) {
        if (attachmentFileList.isEmpty()) {
            /*
             * text/plain
             */
            message.setText(text, charset);
        } else {
            /*
             * multipart/mixed
             *  text/plain
             *  attachment
             */
            Multipart mixedMultipart = createMixedMimeMultipart();
            mixedMultipart.addBodyPart(createTextPart());
            for (AttachmentFile file : attachmentFileList) {
                mixedMultipart.addBodyPart(createAttachmentPart(file));
            }
            message.setContent(mixedMultipart);
        }
    } else {
        if (attachmentFileList.isEmpty()) {
            if (inlineImageFileList.isEmpty()) {
                /*
                 * multipart/alternative
                 *  text/plain
                 *  text/html
                 */
                Multipart alternativeMultipart = createAlternativeMimeMultipart();
                alternativeMultipart.addBodyPart(createTextPart());
                alternativeMultipart.addBodyPart(createHtmlPart());
                message.setContent(alternativeMultipart);
            } else {
                /*
                 * multipart/alternative
                 *  text/plain
                 *  mulpart/related
                 *    text/html
                 *    image
                 */
                Multipart relatedMultipart = createRelatedMimeMultipart();
                relatedMultipart.addBodyPart(createHtmlPart());
                for (InlineImageFile file : inlineImageFileList) {
                    relatedMultipart.addBodyPart(createImagePart(file));
                }
                MimeBodyPart relatedPart = new MimeBodyPart();
                relatedPart.setContent(relatedMultipart);

                Multipart alternativeMultipart = createAlternativeMimeMultipart();
                alternativeMultipart.addBodyPart(createTextPart());
                alternativeMultipart.addBodyPart(relatedPart);
                message.setContent(alternativeMultipart);
            }
        } else {
            if (inlineImageFileList.isEmpty()) {
                /*
                 * multipart/mixed
                 *  mulpart/alternative
                 *   text/plain
                 *   text/html
                 *  attachment
                 */
                Multipart alternativeMultipart = createAlternativeMimeMultipart();
                alternativeMultipart.addBodyPart(createTextPart());
                alternativeMultipart.addBodyPart(createHtmlPart());
                MimeBodyPart alternativePart = new MimeBodyPart();
                alternativePart.setContent(alternativeMultipart);

                Multipart mixedMultipart = createMixedMimeMultipart();
                mixedMultipart.addBodyPart(alternativePart);
                for (AttachmentFile file : attachmentFileList) {
                    mixedMultipart.addBodyPart(createAttachmentPart(file));
                }
                message.setContent(mixedMultipart);
            } else {
                /*
                 * multipart/mixed
                 *  mulpart/alternative
                 *   text/plain
                 *   mulpart/related
                 *     text/html
                 *     image
                 *  attachment
                 */
                Multipart relatedMultipart = createRelatedMimeMultipart();
                relatedMultipart.addBodyPart(createHtmlPart());
                for (InlineImageFile file : inlineImageFileList) {
                    relatedMultipart.addBodyPart(createImagePart(file));
                }
                MimeBodyPart relatedPart = new MimeBodyPart();
                relatedPart.setContent(relatedMultipart);

                Multipart alternativeMultipart = createAlternativeMimeMultipart();
                alternativeMultipart.addBodyPart(createTextPart());
                alternativeMultipart.addBodyPart(relatedPart);
                MimeBodyPart alternativePart = new MimeBodyPart();
                alternativePart.setContent(alternativeMultipart);

                Multipart mixedMultipart = createMixedMimeMultipart();
                mixedMultipart.addBodyPart(alternativePart);
                for (AttachmentFile file : attachmentFileList) {
                    mixedMultipart.addBodyPart(createAttachmentPart(file));
                }
                message.setContent(mixedMultipart);
            }
        }
    }
    setHeaderToPart(message);
}

From source file:org.topazproject.ambra.email.impl.FreemarkerTemplateMailer.java

/**
 * Mail the email formatted using the given templates
 * @param toEmailAddresses List of email addresses to which emails should be sent.  White space delimited.
 * @param fromEmailAddress fromEmailAddress
 * @param subject subject of the email// w ww .  j  a  v  a  2s.  c  o m
 * @param context context to set the values from for the template
 * @param textTemplateFilename textTemplateFilename
 * @param htmlTemplateFilename htmlTemplateFilename
 */
public void mail(final String toEmailAddresses, final String fromEmailAddress, final String subject,
        final Map<String, Object> context, final String textTemplateFilename,
        final String htmlTemplateFilename) {
    final StringTokenizer emailTokens = new StringTokenizer(toEmailAddresses);

    while (emailTokens.hasMoreTokens()) {
        final String toEmailAddress = emailTokens.nextToken();
        final MimeMessagePreparator preparator = new MimeMessagePreparator() {
            public void prepare(final MimeMessage mimeMessage) throws MessagingException, IOException {
                final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true,
                        configuration.getDefaultEncoding());
                message.setTo(new InternetAddress(toEmailAddress));
                message.setFrom(new InternetAddress(fromEmailAddress, (String) context.get(USER_NAME_KEY)));
                message.setSubject(subject);

                // Create a "text" Multipart message
                final Multipart mp = createPartForMultipart(textTemplateFilename, context, "alternative",
                        MIME_TYPE_TEXT_PLAIN + "; charset=" + configuration.getDefaultEncoding());

                // Create a "HTML" Multipart message
                final Multipart htmlContent = createPartForMultipart(htmlTemplateFilename, context, "related",
                        MIME_TYPE_TEXT_HTML + "; charset=" + configuration.getDefaultEncoding());

                final BodyPart htmlPart = new MimeBodyPart();
                htmlPart.setContent(htmlContent);
                mp.addBodyPart(htmlPart);

                mimeMessage.setContent(mp);
            }
        };
        mailSender.send(preparator);
        if (log.isDebugEnabled()) {
            log.debug("Mail sent to:" + toEmailAddress);
        }
    }
}

From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java

/**Enwrapps the data into a signed MIME message structure and returns it*/
private void enwrappInMessageAndSign(AS2Message message, Part contentPart, Partner sender, Partner receiver)
        throws Exception {
    AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info();
    MimeMessage messagePart = new MimeMessage(Session.getInstance(System.getProperties(), null));
    //sign message if this is requested
    if (info.getSignType() != AS2Message.SIGNATURE_NONE) {
        MimeMultipart signedPart = this.signContentPart(contentPart, sender, receiver);
        if (this.logger != null) {
            String signAlias = this.signatureCertManager.getAliasByFingerprint(sender.getSignFingerprintSHA1());
            this.logger.log(Level.INFO,
                    this.rb.getResourceString("message.signed",
                            new Object[] { info.getMessageId(), signAlias,
                                    this.rbMessage.getResourceString("signature." + receiver.getSignType()) }),
                    info);//from  www.  j a va2s  .  c  o m
        }
        messagePart.setContent(signedPart);
        messagePart.saveChanges();
    } else {
        //unsigned message
        if (contentPart instanceof MimeBodyPart) {
            MimeMultipart unsignedPart = new MimeMultipart();
            unsignedPart.addBodyPart((MimeBodyPart) contentPart);
            if (this.logger != null) {
                this.logger.log(Level.INFO,
                        this.rb.getResourceString("message.notsigned", new Object[] { info.getMessageId() }),
                        info);
            }
            messagePart.setContent(unsignedPart);
        } else if (contentPart instanceof MimeMultipart) {
            messagePart.setContent((MimeMultipart) contentPart);
        } else if (contentPart instanceof MimeMessage) {
            messagePart = (MimeMessage) contentPart;
        } else {
            throw new IllegalArgumentException("enwrappInMessageAndSign: Unable to set the content of a "
                    + contentPart.getClass().getName());
        }
        messagePart.saveChanges();
    }
    //store signed or unsigned data
    ByteArrayOutputStream signedOut = new ByteArrayOutputStream();
    //normally the content type header is folded (which is correct but some products are not able to parse this properly)
    //Now take the content-type, unfold it and write it
    Enumeration headerLines = messagePart.getMatchingHeaderLines(new String[] { "Content-Type" });
    LineOutputStream los = new LineOutputStream(signedOut);
    while (headerLines.hasMoreElements()) {
        //requires java mail API >= 1.4
        String nextHeaderLine = MimeUtility.unfold((String) headerLines.nextElement());
        //write the line only if the as2 message is encrypted. If the as2 message is unencrypted this header is added later
        //in the class MessageHttpUploader
        if (info.getEncryptionType() != AS2Message.ENCRYPTION_NONE) {
            los.writeln(nextHeaderLine);
        }
        //store the content line in the as2 message object, this value is required later in MessageHttpUploader
        message.setContentType(nextHeaderLine.substring(nextHeaderLine.indexOf(':') + 1));
    }
    messagePart.writeTo(signedOut, new String[] { "Message-ID", "Mime-Version", "Content-Type" });
    signedOut.flush();
    signedOut.close();
    message.setDecryptedRawData(signedOut.toByteArray());
}

From source file:org.hoteia.qalingo.core.util.impl.MimeMessagePreparatorImpl.java

public void prepare(MimeMessage message) throws Exception {

    message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">");

    // AUTO unsubscribe for Gmail/Hotmail etc : RFC2369
    if (StringUtils.isNotEmpty(getUnsubscribeUrlOrEmail())) {
        message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">");
    }/* w  w w .ja  v a  2 s.  co  m*/

    if (getFrom() != null) {
        List<InternetAddress> toAddress = new ArrayList<InternetAddress>();
        toAddress.add(new InternetAddress(getFrom(), getFromName()));
        message.addFrom(toAddress.toArray(new InternetAddress[toAddress.size()]));
    }
    if (getTo() != null) {
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getTo()));
    }
    if (getCc() != null) {
        message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(getCc()));
    }
    if (getBcc() != null) {
        message.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(getBcc()));
    }
    if (getSubject() != null) {
        message.setSubject(getSubject());
    }

    MimeMultipart mimeMultipart = new MimeMultipart("alternative");// multipart/mixed or mixed or related or alternative
    message.setContent(mimeMultipart);

    if (getPlainTextContent() != null) {
        BodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");
        textBodyPart.setHeader("Content-Transfer-Encoding", "base64");
        textBodyPart.setContent(getPlainTextContent(), "text/plain; charset=\"UTF-8\"");
        mimeMultipart.addBodyPart(textBodyPart);
    }

    if (getHtmlContent() != null) {
        BodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");
        htmlBodyPart.setHeader("Content-Transfer-Encoding", "base64");
        htmlBodyPart.setContent(getHtmlContent(), "text/html; charset=\"UTF-8\"");
        mimeMultipart.addBodyPart(htmlBodyPart);
    }

}

From source file:org.apache.jsieve.mailet.SieveMailboxMailet.java

/**
 * Deliver the original mail as an attachment with the main part being an error report.
 *
 * @param recipient// w w  w. jav  a  2s .c o  m
 * @param aMail
 * @param ex
 * @throws MessagingException
 * @throws IOException 
 */
protected void handleFailure(MailAddress recipient, Mail aMail, Exception ex)
        throws MessagingException, IOException {
    String user = getUsername(recipient);

    MimeMessage originalMessage = aMail.getMessage();
    MimeMessage message = new MimeMessage(originalMessage);
    MimeMultipart multipart = new MimeMultipart();

    MimeBodyPart noticePart = new MimeBodyPart();
    noticePart.setText(new StringBuilder().append(
            "An error was encountered while processing this mail with the active sieve script for user \"")
            .append(user).append("\". The error encountered was:\r\n").append(ex.getLocalizedMessage())
            .append("\r\n").toString());
    multipart.addBodyPart(noticePart);

    MimeBodyPart originalPart = new MimeBodyPart();
    originalPart.setContent(originalMessage, "message/rfc822");
    if ((originalMessage.getSubject() != null) && (!originalMessage.getSubject().trim().isEmpty())) {
        originalPart.setFileName(originalMessage.getSubject().trim());
    } else {
        originalPart.setFileName("No Subject");
    }
    originalPart.setDisposition(MimeBodyPart.INLINE);
    multipart.addBodyPart(originalPart);

    message.setContent(multipart);
    message.setSubject("[SIEVE ERROR] " + originalMessage.getSubject());
    message.setHeader("X-Priority", "1");
    message.saveChanges();

    storeMessageInbox(user, message);
}

From source file:za.co.jumpingbean.alfresco.repo.EmailDocumentsAction.java

public void addAttachments(final Action action, final NodeRef nodeRef, MimeMessage mimeMessage)
        throws MessagingException {
    String text = (String) action.getParameterValue(PARAM_BODY);
    Boolean convertToPDF = (Boolean) action.getParameterValue(PARAM_CONVERT);
    MimeMultipart mail = new MimeMultipart("mixed");
    MimeBodyPart bodyText = new MimeBodyPart();
    bodyText.setText(text);//from   w  w w  .ja  va  2s  .c  om
    mail.addBodyPart(bodyText);

    Queue<NodeRef> que = new LinkedList<>();
    QName type = nodeService.getType(nodeRef);
    if (type.isMatch(ContentModel.TYPE_FOLDER) || type.isMatch(ContentModel.TYPE_CONTAINER)) {
        que.add(nodeRef);
    } else {
        addAttachement(nodeRef, mail, convertToPDF);
    }
    while (!que.isEmpty()) {
        NodeRef tmpNodeRef = que.remove();
        List<ChildAssociationRef> list = nodeService.getChildAssocs(tmpNodeRef);
        for (ChildAssociationRef childRef : list) {
            NodeRef ref = childRef.getChildRef();
            if (nodeService.getType(ref).isMatch(ContentModel.TYPE_CONTENT)) {
                addAttachement(ref, mail, convertToPDF);
            } else {
                que.add(ref);
            }
        }
    }
    mimeMessage.setContent(mail);
}

From source file:io.mapzone.arena.share.app.EMailSharelet.java

private void sendEmail(final String toText, final String subjectText, final String messageText,
        final boolean withAttachment, final ImagePngContent image) throws Exception {
    MimeMessage msg = new MimeMessage(mailSession());

    msg.addRecipients(RecipientType.TO, InternetAddress.parse(toText, false));
    // TODO we need the FROM from the current user
    msg.addFrom(InternetAddress.parse("support@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) );
    msg.setReplyTo(InternetAddress.parse("DO_NOT_REPLY_TO_THIS_EMAIL@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) );

    msg.setSubject(subjectText, "utf-8");
    if (withAttachment) {
        // add mime multiparts
        Multipart multipart = new MimeMultipart();

        BodyPart part = new MimeBodyPart();
        part.setText(messageText);/*from  ww w . j ava  2s  .c  om*/
        multipart.addBodyPart(part);

        // Second part is attachment
        part = new MimeBodyPart();
        part.setDataHandler(new DataHandler(new URLDataSource(new URL(image.imgResource))));
        part.setFileName("preview.png");
        part.setHeader("Content-ID", "preview");
        multipart.addBodyPart(part);

        // // third part in HTML with embedded image
        // part = new MimeBodyPart();
        // part.setContent( "<img src='cid:preview'>", "text/html" );
        // multipart.addBodyPart( part );

        msg.setContent(multipart);
    } else {
        msg.setText(messageText, "utf-8");
    }
    msg.setSentDate(new Date());
    Transport.send(msg);
}

From source file:net.sf.jclal.util.mail.SenderEmail.java

/**
 * Send the email with the indicated parameters
 *
 * @param subject The subject// w  ww.  j  ava2 s  . c o  m
 * @param content The content
 * @param reportFile The reportFile to send
 */
public void sendEmail(String subject, String content, File reportFile) {

    // Get system properties
    Properties properties = new Properties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", host);
    properties.put("mail.smtp.port", port);

    if (!user.isEmpty() && !pass.isEmpty()) {

        properties.setProperty("mail.user", user);

        properties.setProperty("mail.password", pass);
    }

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.addRecipients(Message.RecipientType.TO, toRecipients.toString());

        // Set Subject: header field
        message.setSubject(subject);

        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        messageBodyPart.setText(content);

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        if (attachReporFile) {

            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(reportFile)));
            messageBodyPart.setFileName(reportFile.getName());
            multipart.addBodyPart(messageBodyPart);
        }

        // Send the complete message parts
        message.setContent(multipart);

        // Send message
        Transport.send(message);

        System.out.println("Sent message successfully....");

    } catch (MessagingException e) {

        Logger.getLogger(SenderEmail.class.getName()).log(Level.SEVERE, null, e);
    }

}

From source file:org.apache.james.transport.mailets.StripAttachmentTest.java

@Test
public void testToAndFromAttributes() throws MessagingException, IOException {
    Mailet strip = new StripAttachment();
    FakeMailetConfig mci = new FakeMailetConfig("Test", FakeMailContext.defaultContext());
    mci.setProperty("attribute", "my.attribute");
    mci.setProperty("remove", "all");
    mci.setProperty("notpattern", ".*\\.tmp.*");
    strip.init(mci);//from ww w.j  a va 2 s .  c  om

    Mailet recover = new RecoverAttachment();
    FakeMailetConfig mci2 = new FakeMailetConfig("Test", FakeMailContext.defaultContext());
    mci2.setProperty("attribute", "my.attribute");
    recover.init(mci2);

    Mailet onlyText = new OnlyText();
    onlyText.init(new FakeMailetConfig("Test", FakeMailContext.defaultContext()));

    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));

    MimeMultipart mm = new MimeMultipart();
    MimeBodyPart mp = new MimeBodyPart();
    mp.setText("simple text");
    mm.addBodyPart(mp);
    String body = "\u0023\u00A4\u00E3\u00E0\u00E9";
    MimeBodyPart mp2 = new MimeBodyPart(new ByteArrayInputStream(
            ("Content-Transfer-Encoding: 8bit\r\nContent-Type: application/octet-stream; charset=utf-8\r\n\r\n"
                    + body).getBytes("UTF-8")));
    mp2.setDisposition("attachment");
    mp2.setFileName("=?iso-8859-15?Q?=E9_++++Pubblicit=E0_=E9_vietata____Milano9052.tmp?=");
    mm.addBodyPart(mp2);
    String body2 = "\u0014\u00A3\u00E1\u00E2\u00E4";
    MimeBodyPart mp3 = new MimeBodyPart(new ByteArrayInputStream(
            ("Content-Transfer-Encoding: 8bit\r\nContent-Type: application/octet-stream; charset=utf-8\r\n\r\n"
                    + body2).getBytes("UTF-8")));
    mp3.setDisposition("attachment");
    mp3.setFileName("temp.zip");
    mm.addBodyPart(mp3);
    message.setSubject("test");
    message.setContent(mm);
    message.saveChanges();
    Mail mail = FakeMail.builder().mimeMessage(message).build();

    Assert.assertTrue(mail.getMessage().getContent() instanceof MimeMultipart);
    Assert.assertEquals(3, ((MimeMultipart) mail.getMessage().getContent()).getCount());

    strip.service(mail);

    Assert.assertTrue(mail.getMessage().getContent() instanceof MimeMultipart);
    Assert.assertEquals(1, ((MimeMultipart) mail.getMessage().getContent()).getCount());

    onlyText.service(mail);

    Assert.assertFalse(mail.getMessage().getContent() instanceof MimeMultipart);

    Assert.assertEquals("simple text", mail.getMessage().getContent());

    // prova per caricare il mime message da input stream che altrimenti
    // javamail si comporta differentemente.
    String mimeSource = "Message-ID: <26194423.21197328775426.JavaMail.bago@bagovista>\r\nSubject: test\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=us-ascii\r\nContent-Transfer-Encoding: 7bit\r\n\r\nsimple text";

    MimeMessage mmNew = new MimeMessage(Session.getDefaultInstance(new Properties()),
            new ByteArrayInputStream(mimeSource.getBytes("UTF-8")));

    mmNew.writeTo(System.out);
    mail.setMessage(mmNew);

    recover.service(mail);

    Assert.assertTrue(mail.getMessage().getContent() instanceof MimeMultipart);
    Assert.assertEquals(2, ((MimeMultipart) mail.getMessage().getContent()).getCount());

    Object actual = ((MimeMultipart) mail.getMessage().getContent()).getBodyPart(1).getContent();
    if (actual instanceof ByteArrayInputStream) {
        Assert.assertEquals(body2, toString((ByteArrayInputStream) actual));
    } else {
        Assert.assertEquals(body2, actual);
    }

}

From source file:org.liveSense.service.email.EmailServiceImpl.java

/**
 * {@inheritDoc}//from ww w  . j  ava 2s .c o  m
 */
@Override
public void sendEmailFromTemplateString(Session session, String template, Node resource, String subject,
        Object replyTo, Object from, Date date, Object[] to, Object[] cc, Object[] bcc,
        HashMap<String, Object> variables) throws Exception {
    boolean haveSession = false;

    try {
        if (session != null && session.isLive()) {
            haveSession = true;
        } else {
            session = repository.loginAdministrative(null);
        }

        if (template == null) {
            throw new RepositoryException("Template is null");
        }
        String html = templateNode(Md5Encrypter.encrypt(template), resource, template, variables);
        if (html == null)
            throw new RepositoryException("Template is empty");

        // create the messge.
        MimeMessage mimeMessage = new MimeMessage((javax.mail.Session) null);

        MimeMultipart rootMixedMultipart = new MimeMultipart("mixed");
        mimeMessage.setContent(rootMixedMultipart);

        MimeMultipart nestedRelatedMultipart = new MimeMultipart("related");
        MimeBodyPart relatedBodyPart = new MimeBodyPart();
        relatedBodyPart.setContent(nestedRelatedMultipart);
        rootMixedMultipart.addBodyPart(relatedBodyPart);

        MimeMultipart messageBody = new MimeMultipart("alternative");
        MimeBodyPart bodyPart = null;
        for (int i = 0; i < nestedRelatedMultipart.getCount(); i++) {
            BodyPart bp = nestedRelatedMultipart.getBodyPart(i);
            if (bp.getFileName() == null) {
                bodyPart = (MimeBodyPart) bp;
            }
        }
        if (bodyPart == null) {
            MimeBodyPart mimeBodyPart = new MimeBodyPart();
            nestedRelatedMultipart.addBodyPart(mimeBodyPart);
            bodyPart = mimeBodyPart;
        }
        bodyPart.setContent(messageBody, "text/alternative");

        // Create the plain text part of the message.
        MimeBodyPart plainTextPart = new MimeBodyPart();
        plainTextPart.setText(extractTextFromHtml(html), configurator.getEncoding());
        messageBody.addBodyPart(plainTextPart);

        // Create the HTML text part of the message.
        MimeBodyPart htmlTextPart = new MimeBodyPart();
        htmlTextPart.setContent(html, "text/html;charset=" + configurator.getEncoding()); // ;charset=UTF-8
        messageBody.addBodyPart(htmlTextPart);

        // Check if resource have nt:file childs adds as attachment
        if (resource != null && resource.hasNodes()) {
            NodeIterator iter = resource.getNodes();
            while (iter.hasNext()) {
                Node n = iter.nextNode();
                if (n.getPrimaryNodeType().isNodeType("nt:file")) {
                    // Part two is attachment
                    MimeBodyPart attachmentBodyPart = new MimeBodyPart();
                    InputStream fileData = n.getNode("jcr:content").getProperty("jcr:data").getBinary()
                            .getStream();
                    String mimeType = n.getNode("jcr:content").getProperty("jcr:mimeType").getString();
                    String fileName = n.getName();

                    DataSource source = new StreamDataSource(fileData, fileName, mimeType);
                    attachmentBodyPart.setDataHandler(new DataHandler(source));
                    attachmentBodyPart.setFileName(fileName);
                    attachmentBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
                    attachmentBodyPart.setContentID(fileName);
                    rootMixedMultipart.addBodyPart(attachmentBodyPart);
                }
            }
        }

        prepareMimeMessage(mimeMessage, resource, template, subject, replyTo, from, date, to, cc, bcc,
                variables);
        sendEmail(session, mimeMessage);

        //
    } finally {
        if (!haveSession && session != null) {
            if (session.hasPendingChanges()) {
                try {
                    session.save();
                } catch (Throwable th) {
                }
            }
            session.logout();
        }
    }
}