Example usage for javax.mail.internet MimeBodyPart setText

List of usage examples for javax.mail.internet MimeBodyPart setText

Introduction

In this page you can find the example usage for javax.mail.internet MimeBodyPart setText.

Prototype

@Override
public void setText(String text, String charset, String subtype) throws MessagingException 

Source Link

Document

Convenience method that sets the given String as this part's content, with a primary MIME type of "text" and the specified MIME subtype.

Usage

From source file:org.eclipse.che.mail.MailSender.java

public void sendMail(EmailBean emailBean) throws SendMailException {
    File tempDir = null;//from  w  ww  .  ja v a 2s.  com
    try {
        MimeMessage message = new MimeMessage(mailSessionProvider.get());
        Multipart contentPart = new MimeMultipart();

        MimeBodyPart bodyPart = new MimeBodyPart();
        bodyPart.setText(emailBean.getBody(), "UTF-8", getSubType(emailBean.getMimeType()));
        contentPart.addBodyPart(bodyPart);

        if (emailBean.getAttachments() != null) {
            tempDir = Files.createTempDir();
            for (Attachment attachment : emailBean.getAttachments()) {
                // Create attachment file in temporary directory
                byte[] attachmentContent = Base64.getDecoder().decode(attachment.getContent());
                File attachmentFile = new File(tempDir, attachment.getFileName());
                Files.write(attachmentContent, attachmentFile);

                // Attach the attachment file to email
                MimeBodyPart attachmentPart = new MimeBodyPart();
                attachmentPart.attachFile(attachmentFile);
                attachmentPart.setContentID("<" + attachment.getContentId() + ">");
                contentPart.addBodyPart(attachmentPart);
            }
        }

        message.setContent(contentPart);
        message.setSubject(emailBean.getSubject(), "UTF-8");
        message.setFrom(new InternetAddress(emailBean.getFrom(), true));
        message.setSentDate(new Date());
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(emailBean.getTo()));

        if (emailBean.getReplyTo() != null) {
            message.setReplyTo(InternetAddress.parse(emailBean.getReplyTo()));
        }
        LOG.info("Sending from {} to {} with subject {}", emailBean.getFrom(), emailBean.getTo(),
                emailBean.getSubject());

        Transport.send(message);
        LOG.debug("Mail sent");
    } catch (Exception e) {
        LOG.error(e.getLocalizedMessage());
        throw new SendMailException(e.getLocalizedMessage(), e);
    } finally {
        if (tempDir != null) {
            try {
                FileUtils.deleteDirectory(tempDir);
            } catch (IOException exception) {
                LOG.error(exception.getMessage());
            }
        }
    }
}

From source file:org.eclipse.ecr.automation.core.mail.Composer.java

public Mailer.Message newMixedMessage(String templateContent, Object ctx, String textType,
        List<Blob> attachments) throws Exception {
    if (textType == null) {
        textType = "plain";
    }/*  www. j  av  a  2 s .c  om*/
    Mailer.Message msg = mailer.newMessage();
    MimeMultipart mp = new MimeMultipart();
    MimeBodyPart body = new MimeBodyPart();
    String result = render(templateContent, ctx);
    body.setText(result, "UTF-8", textType);
    mp.addBodyPart(body);
    for (Blob blob : attachments) {
        MimeBodyPart a = new MimeBodyPart();
        a.setDataHandler(new DataHandler(new BlobDataSource(blob)));
        a.setFileName(blob.getFilename());
        mp.addBodyPart(a);
    }
    msg.setContent(mp);
    return msg;
}

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>//from w ww  .ja v a2 s.  c  om
 *    <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;
}

From source file:org.fogbowcloud.manager.core.plugins.util.CloudInitUserDataBuilder.java

/**
 * Add given file <code>in</code> to the cloud-init mime message.
 * //  w  w  w . j  av  a2  s  . co m
 * @param fileType
 * @param in
 *            file to add as readable
 * @return the builder
 * @throws IllegalArgumentException
 *             the given <code>fileType</code> was already added to this
 *             cloud-init mime message.
 */

public CloudInitUserDataBuilder addFile(FileType fileType, Readable in) throws IllegalArgumentException {
    Preconditions.checkNotNull(fileType, "'fileType' can NOT be null");
    Preconditions.checkNotNull(in, "'in' can NOT be null");
    //Preconditions.checkArgument(!alreadyAddedFileTypes.contains(fileType), "%s as already been added", fileType);
    alreadyAddedFileTypes.add(fileType);

    try {
        StringWriter sw = new StringWriter();
        CharStreams.copy(in, sw);
        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setText(sw.toString(), charset.name(), fileType.getMimeTextSubType());
        mimeBodyPart.setFileName((userDataCounter++) + fileType.getFileName());
        userDataMultipart.addBodyPart(mimeBodyPart);

    } catch (IOException e) {
        throw Throwables.propagate(e);
    } catch (MessagingException e) {
        throw Throwables.propagate(e);
    }
    return this;
}

From source file:org.nuxeo.ecm.automation.core.mail.Composer.java

public Mailer.Message newMixedMessage(String templateContent, Object ctx, String textType,
        List<Blob> attachments) throws TemplateException, IOException, MessagingException {
    if (textType == null) {
        textType = "plain";
    }//from   www  .ja v  a 2s  .  co m
    Mailer.Message msg = mailer.newMessage();
    MimeMultipart mp = new MimeMultipart();
    MimeBodyPart body = new MimeBodyPart();
    String result = render(templateContent, ctx);
    body.setText(result, "UTF-8", textType);
    mp.addBodyPart(body);
    for (Blob blob : attachments) {
        MimeBodyPart a = new MimeBodyPart();
        a.setDataHandler(new DataHandler(new BlobDataSource(blob)));
        a.setFileName(blob.getFilename());
        mp.addBodyPart(a);
    }
    msg.setContent(mp);
    return msg;
}

From source file:org.pentaho.platform.util.Emailer.java

public boolean send() {
    String from = props.getProperty("mail.from.default");
    String fromName = props.getProperty("mail.from.name");
    String to = props.getProperty("to");
    String cc = props.getProperty("cc");
    String bcc = props.getProperty("bcc");
    boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
    String subject = props.getProperty("subject");
    String body = props.getProperty("body");

    logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject
            + "' and the body " + body);

    try {//from  ww w. j a  v a 2  s .c o m
        // Get a Session object
        Session session;

        if (authenticate) {
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // if debugging is not set in the email config file, then default to false
        if (!props.containsKey("mail.debug")) { //$NON-NLS-1$
            session.setDebug(false);
        }

        final MimeMessage msg;

        if (EMBEDDED_HTML.equals(attachmentMimeType)) {

            //Message is ready
            msg = new MimeMessage(session, attachment);

            if (body != null) {
                //We need to add message to the top of the email body
                final MimeMultipart oldMultipart = (MimeMultipart) msg.getContent();
                final MimeMultipart newMultipart = new MimeMultipart("related");

                for (int i = 0; i < oldMultipart.getCount(); i++) {
                    BodyPart bodyPart = oldMultipart.getBodyPart(i);

                    final Object content = bodyPart.getContent();
                    //Main HTML body
                    if (content instanceof String) {
                        final String newContent = body + "<br/><br/>" + content;
                        final MimeBodyPart part = new MimeBodyPart();
                        part.setText(newContent, "UTF-8", "html");
                        newMultipart.addBodyPart(part);
                    } else {
                        //CID attachments
                        newMultipart.addBodyPart(bodyPart);
                    }
                }

                msg.setContent(newMultipart);
            }
        } else {

            // construct the message
            msg = new MimeMessage(session);
            Multipart multipart = new MimeMultipart();

            if (attachment == null) {
                logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
                return false;
            }

            ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType);

            if (body != null) {
                MimeBodyPart bodyMessagePart = new MimeBodyPart();
                bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding());
                multipart.addBodyPart(bodyMessagePart);
            }

            // attach the file to the message
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
            attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null));
            multipart.addBodyPart(attachmentBodyPart);

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

        if (from != null) {
            msg.setFrom(new InternetAddress(from, fromName));
        } else {
            // There should be no way to get here
            logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        return true;
    } catch (SendFailedException e) {
        logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$
    } catch (AuthenticationFailedException e) {
        logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$
    } catch (Throwable e) {
        logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$
    }
    return false;
}

From source file:org.tizzit.util.mail.Mail.java

public boolean sendHtmlMail(String alternativePlaintextBody) {
    try {// w w w  .  j  a  va2 s.c  o  m
        if (this.attachments.size() > 0) {
            MimeMultipart mainMultiPart = new MimeMultipart("mixed");
            if (alternativePlaintextBody != null) {
                MimeMultipart alternativeMultiPart = new MimeMultipart("alternative");
                MimeBodyPart plainTextBodyPart = new MimeBodyPart();
                MimeBodyPart htmlBodyPart = new MimeBodyPart();
                plainTextBodyPart.setText(alternativePlaintextBody, this.encoding, "plain");
                htmlBodyPart.setText(this.messageText, this.encoding, "html");
                alternativeMultiPart.addBodyPart(plainTextBodyPart);
                alternativeMultiPart.addBodyPart(htmlBodyPart);

                MimeBodyPart containerBodyPart = new MimeBodyPart();
                containerBodyPart.setContent(alternativeMultiPart);
                mainMultiPart.addBodyPart(containerBodyPart);
            } else { // without plain text alternative
                MimeBodyPart htmlBodyPart = new MimeBodyPart();
                htmlBodyPart.setText(this.messageText, this.encoding, "html");
                mainMultiPart.addBodyPart(htmlBodyPart);
            }
            for (int i = 0; i < this.attachments.size(); i++) {
                mainMultiPart.addBodyPart(this.attachments.get(i));
            }
            this.message.setContent(mainMultiPart);
        } else { // no attachments
            if (alternativePlaintextBody != null) {
                MimeMultipart mainMultipart = new MimeMultipart("alternative");
                MimeBodyPart plainTextBodyPart = new MimeBodyPart();
                MimeBodyPart htmlBodyPart = new MimeBodyPart();
                plainTextBodyPart.setText(alternativePlaintextBody, this.encoding, "plain");
                htmlBodyPart.setText(this.messageText, this.encoding, "html");
                mainMultipart.addBodyPart(plainTextBodyPart);
                mainMultipart.addBodyPart(htmlBodyPart);
                this.message.setContent(mainMultipart);
            } else { // no alternative plain text neither -> no MimeMessage!
                this.message.setContent(this.messageText, "text/html");
            }
        }
        this.message.saveChanges();
        doSend();
    } catch (MessagingException exception) {
        log.error("Error sending HTML mail", exception);
        return false;
    }
    return true;
}