Example usage for javax.mail BodyPart setContent

List of usage examples for javax.mail BodyPart setContent

Introduction

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

Prototype

public void setContent(Multipart mp) throws MessagingException;

Source Link

Document

This method sets the given Multipart object as this message's content.

Usage

From source file:org.ambraproject.wombat.service.FreemarkerMailServiceImpl.java

@Override
public Multipart createContent(Site site, String templateFilename, Model context)
        throws IOException, MessagingException {
    Template textTemplate = getEmailTemplate(site, "txt", templateFilename);
    Template htmlTemplate = getEmailTemplate(site, "html", templateFilename);

    // Create a "text" Multipart message
    Multipart mp = createPartForMultipart(textTemplate, context, "alternative", ContentType.TEXT_PLAIN);

    // Create a "HTML" Multipart message
    Multipart htmlContent = createPartForMultipart(htmlTemplate, context, "related", ContentType.TEXT_HTML);

    BodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(htmlContent);
    mp.addBodyPart(htmlPart);// w ww.j a va  2s.  c o  m

    return mp;
}

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//from   www. ja v  a2s .  c om
 * @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:immf.MyHtmlEmail.java

/**
 * @throws EmailException EmailException
 * @throws MessagingException MessagingException
 *//*w ww  .  java 2  s.c  om*/
private void build() throws MessagingException, EmailException {
    MimeMultipart rootContainer = this.getContainer();
    MimeMultipart bodyEmbedsContainer = rootContainer;
    MimeMultipart bodyContainer = rootContainer;
    BodyPart msgHtml = null;
    BodyPart msgText = null;

    rootContainer.setSubType("mixed");

    // determine how to form multiparts of email

    if (StringUtils.isNotEmpty(this.html) && this.inlineEmbeds.size() > 0) {
        //If HTML body and embeds are used, create a related container and add it to the root container
        bodyEmbedsContainer = new MimeMultipart("related");
        bodyContainer = bodyEmbedsContainer;
        this.addPart(bodyEmbedsContainer, 0);

        //If TEXT body was specified, create a alternative container and add it to the embeds container
        if (StringUtils.isNotEmpty(this.text)) {
            bodyContainer = new MimeMultipart("alternative");
            BodyPart bodyPart = createBodyPart();
            try {
                bodyPart.setContent(bodyContainer);
                bodyEmbedsContainer.addBodyPart(bodyPart, 0);
            } catch (MessagingException me) {
                throw new EmailException(me);
            }
        }
    } else if (StringUtils.isNotEmpty(this.text) && StringUtils.isNotEmpty(this.html)) {
        //If both HTML and TEXT bodies are provided, create a alternative container and add it to the root container
        bodyContainer = new MimeMultipart("alternative");
        this.addPart(bodyContainer, 0);
    }

    if (StringUtils.isNotEmpty(this.html)) {
        msgHtml = new MimeBodyPart();
        bodyContainer.addBodyPart(msgHtml, 0);

        // apply default charset if one has been set
        if (StringUtils.isNotEmpty(this.charset)) {
            msgHtml.setContent(this.html, Email.TEXT_HTML + "; charset=" + this.charset);
        } else {
            msgHtml.setContent(this.html, Email.TEXT_HTML);
        }
        if (contentTransferEncoding != null) {
            msgHtml.setHeader("Content-Transfer-Encoding", contentTransferEncoding);
        }

        Iterator<InlineImage> iter = this.inlineEmbeds.values().iterator();
        while (iter.hasNext()) {
            InlineImage ii = (InlineImage) iter.next();
            bodyEmbedsContainer.addBodyPart(ii.getMbp());
        }
    }

    if (StringUtils.isNotEmpty(this.text)) {
        msgText = new MimeBodyPart();
        bodyContainer.addBodyPart(msgText, 0);

        // apply default charset if one has been set
        if (StringUtils.isNotEmpty(this.charset)) {
            msgText.setContent(this.text, Email.TEXT_PLAIN + "; charset=" + this.charset);
        } else {
            msgText.setContent(this.text, Email.TEXT_PLAIN);
        }
        if (contentTransferEncoding != null) {
            msgText.setHeader("Content-Transfer-Encoding", contentTransferEncoding);
        }
    }
}

From source file:org.apache.camel.component.mail.MailBinding.java

protected void createMultipartAlternativeMessage(MimeMessage mimeMessage, MailConfiguration configuration,
        Exchange exchange) throws MessagingException, IOException {

    MimeMultipart multipartAlternative = new MimeMultipart("alternative");
    mimeMessage.setContent(multipartAlternative);

    MimeBodyPart plainText = new MimeBodyPart();
    plainText.setText(getAlternativeBody(configuration, exchange), determineCharSet(configuration, exchange));
    // remove the header with the alternative mail now that we got it
    // otherwise it might end up twice in the mail reader
    exchange.getIn().removeHeader(configuration.getAlternativeBodyHeader());
    multipartAlternative.addBodyPart(plainText);

    // if there are no attachments, add the body to the same mulitpart message
    if (!exchange.getIn().hasAttachments()) {
        addBodyToMultipart(configuration, multipartAlternative, exchange);
    } else {/*from  www .  j  a va2 s  . c  o m*/
        // if there are attachments, but they aren't set to be inline, add them to
        // treat them as normal. It will append a multipart-mixed with the attachments and the body text
        if (!configuration.isUseInlineAttachments()) {
            BodyPart mixedAttachments = new MimeBodyPart();
            mixedAttachments.setContent(createMixedMultipartAttachments(configuration, exchange));
            multipartAlternative.addBodyPart(mixedAttachments);
        } else {
            // if the attachments are set to be inline, attach them as inline attachments
            MimeMultipart multipartRelated = new MimeMultipart("related");
            BodyPart related = new MimeBodyPart();

            related.setContent(multipartRelated);
            multipartAlternative.addBodyPart(related);

            addBodyToMultipart(configuration, multipartRelated, exchange);

            addAttachmentsToMultipart(multipartRelated, Part.INLINE, exchange);
        }
    }
}

From source file:org.linagora.linshare.core.service.impl.MailNotifierServiceImpl.java

@Override
public void sendNotification(String smtpSender, String replyTo, String recipient, String subject,
        String htmlContent, String inReplyTo, String references) throws SendFailedException {

    if (smtpServer.equals("")) {
        logger.warn("Mail notifications are disabled.");
        return;//from w  w  w .  j  a  v a  2  s.  c  om
    }
    // get the mail session
    Session session = getMailSession();

    // Define message
    MimeMessage messageMim = new MimeMessage(session);

    try {
        messageMim.setFrom(new InternetAddress(smtpSender));

        if (replyTo != null) {
            InternetAddress reply[] = new InternetAddress[1];
            reply[0] = new InternetAddress(replyTo);
            messageMim.setReplyTo(reply);
        }

        messageMim.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient));

        if (inReplyTo != null && inReplyTo != "") {
            // This field should contain only ASCCI character (RFC 822)
            if (isPureAscii(inReplyTo)) {
                messageMim.setHeader("In-Reply-To", inReplyTo);
            }
        }

        if (references != null && references != "") {
            // This field should contain only ASCCI character (RFC 822)  
            if (isPureAscii(references)) {
                messageMim.setHeader("References", references);
            }
        }

        messageMim.setSubject(subject, charset);

        // Create a "related" Multipart message
        // content type is multipart/alternative
        // it will contain two part BodyPart 1 and 2
        Multipart mp = new MimeMultipart("alternative");

        // BodyPart 2
        // content type is multipart/related
        // A multipart/related is used to indicate that message parts should
        // not be considered individually but rather
        // as parts of an aggregate whole. The message consists of a root
        // part (by default, the first) which reference other parts inline,
        // which may in turn reference other parts.
        Multipart html_mp = new MimeMultipart("related");

        // Include an HTML message with images.
        // BodyParts: the HTML file and an image

        // Get the HTML file
        BodyPart rel_bph = new MimeBodyPart();
        rel_bph.setDataHandler(
                new DataHandler(new ByteArrayDataSource(htmlContent, "text/html; charset=" + charset)));
        html_mp.addBodyPart(rel_bph);

        // Create the second BodyPart of the multipart/alternative,
        // set its content to the html multipart, and add the
        // second bodypart to the main multipart.
        BodyPart alt_bp2 = new MimeBodyPart();
        alt_bp2.setContent(html_mp);
        mp.addBodyPart(alt_bp2);

        messageMim.setContent(mp);

        // RFC 822 "Date" header field
        // Indicates that the message is complete and ready for delivery
        messageMim.setSentDate(new GregorianCalendar().getTime());

        // Since we used html tags, the content must be marker as text/html
        // messageMim.setContent(content,"text/html; charset="+charset);

        Transport tr = session.getTransport("smtp");

        // Connect to smtp server, if needed
        if (needsAuth) {
            tr.connect(smtpServer, smtpPort, smtpUser, smtpPassword);
            messageMim.saveChanges();
            tr.sendMessage(messageMim, messageMim.getAllRecipients());
            tr.close();
        } else {
            // Send message
            Transport.send(messageMim);
        }
    } catch (SendFailedException e) {
        logger.error("Error sending notification on " + smtpServer + " port " + smtpPort + " to " + recipient,
                e);
        throw e;
    } catch (MessagingException e) {
        logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e);
        throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e);
    } catch (Exception e) {
        logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e);
        throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e);
    }
}

From source file:sk.lazyman.gizmo.web.app.PageEmail.java

private Message buildMail(Session session) throws MessagingException, IOException {
    String subject = createSubject();
    Message mimeMessage = createMimeMessage(session, subject);
    mimeMessage.setDisposition(MimeMessage.INLINE);
    Multipart mp = new MimeMultipart("alternative");

    MimeBodyPart textBp = new MimeBodyPart();
    textBp.setDisposition(MimeMessage.INLINE);
    textBp.setContent("Please use mail client with HTML support.", "text/plain; charset=utf-8");
    mp.addBodyPart(textBp);/*from www  .j  av  a 2 s.  co m*/

    Multipart commentMultipart = null;
    EmailDto dto = model.getObject();
    if (StringUtils.isNotEmpty(dto.getBody())) {
        BodyPart bodyPart = new MimeBodyPart();
        bodyPart.setDisposition(MimeMessage.INLINE);
        DataHandler dataHandler = new DataHandler(
                new ByteArrayDataSource(dto.getBody(), "text/plain; charset=utf-8"));
        bodyPart.setDataHandler(dataHandler);

        commentMultipart = new MimeMultipart("mixed");
        commentMultipart.addBodyPart(bodyPart);
    }

    String html = createHtml();
    Multipart htmlMp = createHtmlPart(html);

    BodyPart htmlBp = new MimeBodyPart();
    htmlBp.setDisposition(BodyPart.INLINE);
    htmlBp.setContent(htmlMp);
    if (commentMultipart == null) {
        mp.addBodyPart(htmlBp);
    } else {
        commentMultipart.addBodyPart(htmlBp);
        BodyPart all = new MimeBodyPart();
        all.setDisposition(BodyPart.INLINE);
        all.setContent(commentMultipart);
        mp.addBodyPart(all);
    }
    mimeMessage.setContent(mp);

    return mimeMessage;
}