Example usage for javax.mail.internet MimeMultipart addBodyPart

List of usage examples for javax.mail.internet MimeMultipart addBodyPart

Introduction

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

Prototype

@Override
public synchronized void addBodyPart(BodyPart part) throws MessagingException 

Source Link

Document

Adds a Part to the multipart.

Usage

From source file:org.infoglue.common.util.mail.MailService.java

/**
 * @param attachments /*  w  w  w  .  j  a  v a 2  s .c o  m*/
 *
 */
private Message createMessage(String from, String to, String bcc, String subject, String content,
        String contentType, String encoding, List attachments) throws SystemException {
    try {
        final Message message = new MimeMessage(this.session);
        String contentTypeWithEncoding = contentType + ";charset=" + encoding;

        // message.setContent(content, contentType);
        message.setFrom(createInternetAddress(from));
        //message.setRecipient(Message.RecipientType.TO,
        //      createInternetAddress(to));
        message.setRecipients(Message.RecipientType.TO, createInternetAddresses(to));
        if (bcc != null)
            message.setRecipients(Message.RecipientType.BCC, createInternetAddresses(bcc));
        // message.setSubject(subject);

        ((MimeMessage) message).setSubject(subject, encoding);
        MimeMultipart mp = new MimeMultipart();
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setDataHandler(new DataHandler(new StringDataSource(content, contentTypeWithEncoding, encoding)));
        mp.addBodyPart(mbp1);
        if (attachments != null) {
            for (Iterator it = attachments.iterator(); it.hasNext();) {
                File attachmentFile = (File) it.next();
                if (attachmentFile.exists()) {
                    MimeBodyPart attachment = new MimeBodyPart();
                    attachment.setFileName(attachmentFile.getName());
                    attachment.setDataHandler(new DataHandler(new FileDataSource(attachmentFile)));
                    mp.addBodyPart(attachment);
                }
            }
        }
        message.setContent(mp);
        // message.setText(content);
        // message.setDataHandler(new DataHandler(new
        // StringDataSource(content, contentTypeWithEncoding, encoding)));
        // message.setText(content);
        // message.setDataHandler(new DataHandler(new
        // StringDataSource(content, "text/html")));

        return message;
    } catch (MessagingException e) {
        throw new SystemException("Unable to create the message.", e);
    }
}

From source file:org.j2free.email.EmailService.java

private void send(InternetAddress from, InternetAddress[] recipients, String subject, String body,
        ContentType contentType, Priority priority, boolean ccSender)
        throws AddressException, MessagingException, RejectedExecutionException {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(from);//  ww  w . j  a  va 2  s .  c  om
    message.setRecipients(Message.RecipientType.TO, recipients);

    for (Map.Entry<String, String> header : headers.entrySet())
        message.setHeader(header.getKey(), header.getValue());

    // CC the sender if they want
    if (ccSender)
        message.addRecipient(Message.RecipientType.CC, from);

    message.setReplyTo(new InternetAddress[] { from });

    message.setSubject(subject);
    message.setSentDate(new Date());

    if (contentType == ContentType.PLAIN) {
        // Just set the body as plain text
        message.setText(body, "UTF-8");
    } else {
        MimeMultipart multipart = new MimeMultipart("alternative");

        // Create the text part
        MimeBodyPart text = new MimeBodyPart();
        text.setText(new HtmlFilter().filterForEmail(body), "UTF-8");

        // Add the text part
        multipart.addBodyPart(text);

        // Create the HTML portion
        MimeBodyPart html = new MimeBodyPart();
        html.setContent(body, ContentType.HTML.toString());

        // Add the HTML portion
        multipart.addBodyPart(html);

        // set the message content
        message.setContent(multipart);
    }
    enqueue(message, priority);
}

From source file:org.jahia.services.workflow.jbpm.custom.email.JBPMMailProducer.java

protected void fillContent(MailTemplate template, Message email, WorkItem workItem, JCRSessionWrapper session)
        throws Exception {
    String text = template.getText();
    String html = template.getHtml();
    List<AttachmentTemplate> attachmentTemplates = template.getAttachmentTemplates();

    if (html != null || !attachmentTemplates.isEmpty()) {
        // multipart
        MimeMultipart multipart = new MimeMultipart("related");

        BodyPart p = new MimeBodyPart();
        Multipart alternatives = new MimeMultipart("alternative");
        p.setContent(alternatives, "multipart/alternative");
        multipart.addBodyPart(p);

        // html/*w  w  w. ja v a  2  s  . co  m*/
        if (html != null) {
            BodyPart htmlPart = new MimeBodyPart();
            html = evaluateExpression(workItem, html, session);
            htmlPart.setContent(html, "text/html; charset=UTF-8");
            alternatives.addBodyPart(htmlPart);
        }

        // text
        if (text != null) {
            BodyPart textPart = new MimeBodyPart();
            text = evaluateExpression(workItem, text, session);
            textPart.setContent(text, "text/plain; charset=UTF-8");
            alternatives.addBodyPart(textPart);
        }

        // attachments
        if (!attachmentTemplates.isEmpty()) {
            addAttachments(template, workItem, multipart, session);
        }

        email.setContent(multipart);
    } else if (text != null) {
        // unipart
        text = evaluateExpression(workItem, text, session);
        email.setText(text);
    }
}

From source file:org.jahia.services.workflow.jbpm.JBPMMailProducer.java

protected void fillContent(Message email, Execution execution, JCRSessionWrapper session)
        throws MessagingException {
    String text = getTemplate().getText();
    String html = getTemplate().getHtml();
    List<AttachmentTemplate> attachmentTemplates = getTemplate().getAttachmentTemplates();

    try {/*from   w  w w. j a v  a 2 s  . c  o  m*/
        if (html != null || !attachmentTemplates.isEmpty()) {
            // multipart
            MimeMultipart multipart = new MimeMultipart("related");

            BodyPart p = new MimeBodyPart();
            Multipart alternatives = new MimeMultipart("alternative");
            p.setContent(alternatives, "multipart/alternative");
            multipart.addBodyPart(p);

            // html
            if (html != null) {
                BodyPart htmlPart = new MimeBodyPart();
                html = evaluateExpression(execution, html, session);
                htmlPart.setContent(html, "text/html; charset=UTF-8");
                alternatives.addBodyPart(htmlPart);
            }

            // text
            if (text != null) {
                BodyPart textPart = new MimeBodyPart();
                text = evaluateExpression(execution, text, session);
                textPart.setContent(text, "text/plain; charset=UTF-8");
                alternatives.addBodyPart(textPart);
            }

            // attachments
            if (!attachmentTemplates.isEmpty()) {
                addAttachments(execution, multipart);
            }

            email.setContent(multipart);
        } else if (text != null) {
            // unipart
            text = evaluateExpression(execution, text, session);
            email.setText(text);
        }
    } catch (RepositoryException e) {
        logger.error(e.getMessage(), e);
    } catch (ScriptException e) {
        logger.error(e.getMessage(), e);
    }
}

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

/**
 * {@inheritDoc}// w  w w .ja  v a  2  s  .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();
        }
    }
}

From source file:org.masukomi.aspirin.core.Bouncer.java

/**
 * This generates a response to the Return-Path address, or the address of
 * the message's sender if the Return-Path is not available. Note that this
 * is different than a mail-client's reply, which would use the Reply-To or
 * From header.// w w w.j a  va2 s  .  c o m
 * 
 * @param mail
 *            DOCUMENT ME!
 * @param message
 *            DOCUMENT ME!
 * @param bouncer
 *            DOCUMENT ME!
 * 
 * @throws MessagingException
 *             DOCUMENT ME!
 */
static public void bounce(MailQue que, Mail mail, String message, MailAddress bouncer)
        throws MessagingException {
    if (bouncer != null) {
        if (log.isDebugEnabled()) {
            log.debug("bouncing message to postmaster");
        }
        MimeMessage orig = mail.getMessage();
        //Create the reply message
        MimeMessage reply = (MimeMessage) orig.reply(false);
        //If there is a Return-Path header,
        if (orig.getHeader(RFC2822Headers.RETURN_PATH) != null) {
            //Return the message to that address, not to the Reply-To
            // address
            reply.setRecipient(MimeMessage.RecipientType.TO,
                    new InternetAddress(orig.getHeader(RFC2822Headers.RETURN_PATH)[0]));
        }
        //Create the list of recipients in our MailAddress format
        Collection recipients = new HashSet();
        Address[] addresses = reply.getAllRecipients();
        for (int i = 0; i < addresses.length; i++) {
            recipients.add(new MailAddress((InternetAddress) addresses[i]));
        }
        //Change the sender...
        reply.setFrom(bouncer.toInternetAddress());
        try {
            //Create the message body
            MimeMultipart multipart = new MimeMultipart();
            //Add message as the first mime body part
            MimeBodyPart part = new MimeBodyPart();
            part.setContent(message, "text/plain");
            part.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain");
            multipart.addBodyPart(part);
            //Add the original message as the second mime body part
            part = new MimeBodyPart();
            part.setContent(orig.getContent(), orig.getContentType());
            part.setHeader(RFC2822Headers.CONTENT_TYPE, orig.getContentType());
            multipart.addBodyPart(part);
            reply.setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new Date()));
            reply.setContent(multipart);
            reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType());
        } catch (IOException ioe) {
            throw new MessagingException("Unable to create multipart body", ioe);
        }
        //Send it off...
        //sendMail( bouncer, recipients, reply );
        que.queMail(reply);
    }
}

From source file:org.mule.transport.email.transformers.ObjectToMimeMessage.java

@Override
protected void setContent(Object payload, Message msg, String contentType, MuleMessage message)
        throws Exception {
    boolean transformInboundAttachments = useInboundAttachments
            && message.getInboundAttachmentNames().size() > 0;
    boolean transformOutboundAttachments = useOutboundAttachments
            && message.getOutboundAttachmentNames().size() > 0;
    if (transformInboundAttachments || transformOutboundAttachments) {
        // The content type must be multipart/mixed
        MimeMultipart multipart = new MimeMultipart("mixed");
        multipart.addBodyPart(getPayloadBodyPart(message.getPayload(), contentType));
        if (transformInboundAttachments) {
            for (String name : message.getInboundAttachmentNames()) {
                // Let outbound attachments override inbound ones
                if (!transformOutboundAttachments || message.getOutboundAttachment(name) == null) {
                    BodyPart part = getBodyPartForAttachment(message.getInboundAttachment(name), name);
                    // Check message props for extra headers
                    addBodyPartHeaders(part, name, message);
                    multipart.addBodyPart(part);
                }//from  ww  w.j  ava  2 s  . co m
            }
        }
        if (transformOutboundAttachments) {
            for (String name : message.getOutboundAttachmentNames()) {
                BodyPart part = getBodyPartForAttachment(message.getOutboundAttachment(name), name);
                // Check message props for extra headers
                addBodyPartHeaders(part, name, message);
                multipart.addBodyPart(part);
            }
        }
        // the payload must be set to the constructed MimeMultipart message
        payload = multipart;
        // the ContentType of the message to be sent, must be the multipart content type
        contentType = multipart.getContentType();
    }

    // now the message will contain the multipart payload, and the multipart
    // contentType
    super.setContent(payload, msg, contentType, message);
}

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";
    }//w  ww  .j a  va  2s . 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.openadaptor.auxil.connector.smtp.SMTPConnection.java

/**
 * Generate body of email. It will either be a mime multipart message or text. This is
 * determined by the <code>recordsAsAttachment</code> property.
 *
 * @param body/*ww w  .  j a va2  s. co m*/
 * @throws MessagingException
 */
public void generateMessageBody(String body) throws MessagingException {
    MimeBodyPart mbpPrefaceBody, mbpBody;
    MimeMultipart mmp;

    // Determine if records are to be send as an attachment
    if (recordsAsAttachment) {
        //Define mime parts
        mbpPrefaceBody = new MimeBodyPart();
        mbpPrefaceBody.setText(bodyPreface);
        mbpBody = new MimeBodyPart();
        if (mimeContentType != null && !(mimeContentType.length() == 0)) {
            mbpBody.setContent(body, mimeContentType);
        } else {
            mbpBody.setText(body);
        }
        //Create mime message
        mmp = new MimeMultipart();
        mmp.addBodyPart(mbpPrefaceBody);
        mmp.addBodyPart(mbpBody);
        message.setContent(mmp);
    } else if (mimeContentType != null && !(mimeContentType.length() == 0)) {
        message.setContent(bodyPreface + "\n\n" + body, mimeContentType);
    } else {
        message.setText(bodyPreface + "\n\n" + body);
    }
}

From source file:org.openmrs.notification.mail.MailMessageSender.java

/**
 * Creates a MimeMultipart, so that we can have an attachment.
 *
 * @param message/*from ww w.  java  2  s.c om*/
 * @return
 */
private MimeMultipart createMultipart(Message message) throws Exception {
    MimeMultipart toReturn = new MimeMultipart();

    MimeBodyPart textContent = new MimeBodyPart();
    textContent.setContent(message.getContent(), message.getContentType());

    MimeBodyPart attachment = new MimeBodyPart();
    attachment.setContent(message.getAttachment(), message.getAttachmentContentType());
    attachment.setFileName(message.getAttachmentFileName());

    toReturn.addBodyPart(textContent);
    toReturn.addBodyPart(attachment);

    return toReturn;
}