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:com.zimbra.cs.mailbox.MailboxTestUtil.java

public static ParsedMessage generateMessageWithAttachment(String subject) throws Exception {
    MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession());
    mm.setHeader("From", "Vera Oliphant <oli@example.com>");
    mm.setHeader("To", "Jimmy Dean <jdean@example.com>");
    mm.setHeader("Subject", subject);
    mm.setText("Good as gold");
    MimeMultipart multi = new ZMimeMultipart("mixed");
    ContentDisposition cdisp = new ContentDisposition(Part.ATTACHMENT);
    cdisp.setParameter("filename", "fun.txt");

    ZMimeBodyPart bp = new ZMimeBodyPart();
    // MimeBodyPart.setDataHandler() invalidates Content-Type and CTE if there is any, so make sure
    // it gets called before setting Content-Type and CTE headers.
    try {/*  w w  w. j  av a  2s . c o  m*/
        bp.setDataHandler(new DataHandler(new ByteArrayDataSource("Feeling attached.", "text/plain")));
    } catch (IOException e) {
        throw new MessagingException("could not generate mime part content", e);
    }
    bp.addHeader("Content-Disposition", cdisp.toString());
    bp.addHeader("Content-Type", "text/plain");
    bp.addHeader("Content-Transfer-Encoding", MimeConstants.ET_8BIT);
    multi.addBodyPart(bp);

    mm.setContent(multi);
    mm.saveChanges();

    return new ParsedMessage(mm, false);
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils.java

/**
 * Adds a mulitpart MimeBodyPart from an array of attachments
 *//*from   w w w. java 2  s .  c o m*/

public static void addMultipartAttachment(MimeMultipart mp, StringToStringMap contentIds,
        List<Attachment> attachments) throws MessagingException {
    MimeMultipart multipart = new MimeMultipart("mixed");
    long totalSize = 0;

    for (int c = 0; c < attachments.size(); c++) {
        Attachment att = attachments.get(c);
        String contentType = att.getContentType();
        totalSize += att.getSize();

        MimeBodyPart part = contentType.startsWith("text/") ? new MimeBodyPart()
                : new PreencodedMimeBodyPart("binary");

        part.setDataHandler(new DataHandler(new AttachmentDataSource(att)));
        initPartContentId(contentIds, part, att, false);
        multipart.addBodyPart(part);
    }

    MimeBodyPart part = new PreencodedMimeBodyPart("binary");

    if (totalSize > MAX_SIZE_IN_MEMORY_ATTACHMENT) {
        part.setDataHandler(new DataHandler(new MultipartAttachmentFileDataSource(multipart)));
    } else {
        part.setDataHandler(new DataHandler(new MultipartAttachmentDataSource(multipart)));
    }

    Attachment attachment = attachments.get(0);
    initPartContentId(contentIds, part, attachment, true);

    mp.addBodyPart(part);
}

From source file:fr.paris.lutece.portal.service.mail.MailUtil.java

/**
 * Send a Multipart text message with attached files. FIXME: use
 * prepareMessage method/*from  w  w w.j  av a 2s. co  m*/
 *
 * @param strRecipientsTo
 *            The list of the main recipients email.Every recipient must be
 *            separated by the mail separator defined in config.properties
 * @param strRecipientsCc
 *            The recipients list of the carbon copies .
 * @param strRecipientsBcc
 *            The recipients list of the blind carbon copies .
 * @param strSenderName
 *            The sender name.
 * @param strSenderEmail
 *            The sender email address.
 * @param strSubject
 *            The message subject.
 * @param strMessage
 *            The message.
 * @param fileAttachements
 *            The list of attached files
 * @param transport
 *            the smtp transport object
 * @param session
 *            the smtp session object
 * @throws AddressException
 *             If invalid address
 * @throws SendFailedException
 *             If an error occured during sending
 * @throws MessagingException
 *             If a messaging error occured
 */
protected static void sendMultipartMessageText(String strRecipientsTo, String strRecipientsCc,
        String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject,
        String strMessage, List<FileAttachment> fileAttachements, Transport transport, Session session)
        throws MessagingException, AddressException, SendFailedException {
    Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName,
            strSenderEmail, strSubject, session);
    msg.setHeader(HEADER_NAME, HEADER_VALUE);

    // Creation of the root part containing all the elements of the message
    MimeMultipart multipart = new MimeMultipart();

    // Creation of the html part, the "core" of the message
    BodyPart msgBodyPart = new MimeBodyPart();
    // msgBodyPart.setContent( strMessage, BODY_PART_MIME_TYPE );
    msgBodyPart.setDataHandler(new DataHandler(
            new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_PLAIN)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET))));
    multipart.addBodyPart(msgBodyPart);

    // add File Attachement
    if (fileAttachements != null) {
        for (FileAttachment fileAttachement : fileAttachements) {
            String strFileName = fileAttachement.getFileName();
            byte[] bContentFile = fileAttachement.getData();
            String strContentType = fileAttachement.getType();
            ByteArrayDataSource dataSource = new ByteArrayDataSource(bContentFile, strContentType);
            msgBodyPart = new MimeBodyPart();
            msgBodyPart.setDataHandler(new DataHandler(dataSource));
            msgBodyPart.setFileName(strFileName);
            msgBodyPart.setDisposition(CONSTANT_DISPOSITION_ATTACHMENT);
            multipart.addBodyPart(msgBodyPart);
        }
    }

    msg.setContent(multipart);

    sendMessage(msg, transport);
}

From source file:com.mgmtp.jfunk.core.reporting.EmailReporter.java

private void sendMessage(final String content) {
    try {// www .  j  a v a2s. c  om
        MimeMessage msg = new MimeMessage(sessionProvider.get());
        msg.setSubject("jFunk E-mail Report");
        msg.addRecipients(Message.RecipientType.TO, recipientsProvider.get());

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content, "text/html; charset=UTF-8");

        MimeMultipart multipart = new MimeMultipart("related");
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("check.gif")));
        messageBodyPart.setHeader("Content-ID", "<check>");
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("error.gif")));
        messageBodyPart.setHeader("Content-ID", "<error>");
        multipart.addBodyPart(messageBodyPart);

        msg.setContent(multipart);

        smtpClientProvider.get().send(msg);

        int anzahlRecipients = msg.getAllRecipients().length;
        log.info(
                "Report e-mail was sent to " + anzahlRecipients + " recipient(s): " + recipientsProvider.get());
    } catch (MessagingException e) {
        log.error("Error while creating report e-mail", e);
    } catch (MailException e) {
        log.error("Error while sending report e-mail", e);
    }
}

From source file:de.betterform.connector.serializer.MultipartRelatedSerializer.java

public void serialize(Submission submission, Node node, SerializerRequestWrapper wrapper,
        String defaultEncoding) throws Exception {
    Map cache = new HashMap();
    MimeMultipart multipart = new MimeMultipart();

    MimeBodyPart part = new MimeBodyPart();
    multipart.addBodyPart(part);

    String encoding = defaultEncoding;
    if (submission.getEncoding() != null) {
        encoding = submission.getEncoding();
    }/*from ww  w . ja  v a2 s.  c  om*/

    if (node.getNodeType() == Node.ELEMENT_NODE || node.getNodeType() == Node.DOCUMENT_NODE) {
        part.setText(new String(serializeXML(multipart, cache, submission, node, encoding), encoding),
                encoding);
    } else {
        part.setText(node.getTextContent());
    }
    part.setContentID("<instance.xml@start>");
    part.addHeader("Content-Type", "application/xml");
    part.addHeader("Content-Transfer-Encoding", "base64");
    part.setDisposition("attachment");
    part.setFileName("instance.xml");

    multipart.setSubType("related; type=\"" + submission.getMediatype() + "\"; start=\"instance.xml@start\"");
    // FIXME: Is this a global http header or a local mime header?
    wrapper.getBodyStream()
            .write(("Content-Type: " + multipart.getContentType() + "\n\nThis is a MIME message.\n")
                    .getBytes(encoding));
    multipart.writeTo(wrapper.getBodyStream());
}

From source file:com.jwm123.loggly.reporter.ReportMailer.java

public void send() throws MessagingException {
    if (StringUtils.isNotBlank(config.getMailServer()) && recipients.length > 0) {
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.port", config.getMailPort().toString());
        props.setProperty("mail.smtp.host", config.getMailServer());
        if (StringUtils.isNotBlank(config.getMailUsername())
                && StringUtils.isNotBlank(config.getMailPassword())) {
            props.setProperty("mail.smtp.user", config.getMailUsername());
            props.setProperty("mail.smtp.password", config.getMailPassword());
        }/* w  ww  . ja  v a  2s  .  co m*/

        Session session = Session.getDefaultInstance(props);

        MimeMessage message = new MimeMessage(session);
        message.addFrom(new Address[] { new InternetAddress(config.getMailFrom()) });
        message.setSubject(subject);
        for (String recipient : recipients) {
            message.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }

        MimeMultipart containingMultipart = new MimeMultipart("mixed");

        MimeMultipart messageMultipart = new MimeMultipart("alternative");
        containingMultipart.addBodyPart(newMultipartBodyPart(messageMultipart));

        messageMultipart.addBodyPart(newTextBodyPart(getText()));

        MimeMultipart htmlMultipart = new MimeMultipart("related");
        htmlMultipart.addBodyPart(newHtmlBodyPart(getHtml()));
        messageMultipart.addBodyPart(newMultipartBodyPart(htmlMultipart));

        containingMultipart.addBodyPart(addReportAttachment());

        message.setContent(containingMultipart);

        Transport.send(message);
    }
}

From source file:com.meltmedia.cadmium.email.TestingMessageTransformer.java

public MimeMessage transform(MimeMessage message) throws MessagingException {
    MimeBodyPart sentToBodyPart = newSentToBodyPart(message);
    MimeBodyPart originalBodyPart = newOriginalBodyPart(message);

    // create a new multipart content for this message.
    MimeMultipart multipart = new MimeMultipart(EmailUtil.SUBTYPE_MIXED);

    // add the parts to the body.
    multipart.addBodyPart(originalBodyPart);
    multipart.addBodyPart(sentToBodyPart);

    // get the new values for all of the headers.
    InternetAddress newFromAddress = newFromAddress(message);
    InternetAddress[] newToAddresses = newToAddresses(message);
    InternetAddress[] newCcAddresses = newCcAddresses(message);
    InternetAddress[] newBccAddresses = newBccAddresses(message);
    String newSubject = newSubject(message);

    // update the message.
    message.setFrom(newFromAddress);/* w  w w. ja va  2 s  .com*/
    message.setRecipients(Message.RecipientType.TO, newToAddresses);
    message.setRecipients(Message.RecipientType.CC, newCcAddresses);
    message.setRecipients(Message.RecipientType.BCC, newBccAddresses);
    message.setSubject(newSubject);
    message.setContent(multipart);

    // save the message.
    message.saveChanges();

    if (getLogProperty()) {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            message.writeTo(out);
            log.info("Email Message Sent:\n{}", out.toString());
        } catch (IOException ioe) {
            throw new MessagingException("Exception thrown while writing message to log.", ioe);
        }
    }
    if (!getSendProperty()) {
        message = null;
    }

    // return the message.
    return message;
}

From source file:at.molindo.notify.channel.mail.AbstractMailClient.java

@Override
public synchronized void send(Dispatch dispatch) throws MailException {

    Message message = dispatch.getMessage();

    String recipient = dispatch.getParams().get(MailChannel.RECIPIENT);
    String recipientName = dispatch.getParams().get(MailChannel.RECIPIENT_NAME);
    String subject = message.getSubject();

    try {/*  w w  w  .ja  va2 s. c  o m*/
        MimeMessage mm = new MimeMessage(getSmtpSession(recipient)) {
            @Override
            protected void updateMessageID() throws MessagingException {
                String domain = _from.getAddress();
                int idx = _from.getAddress().indexOf('@');
                if (idx >= 0) {
                    domain = domain.substring(idx + 1);
                }
                setHeader("Message-ID", "<" + UUID.randomUUID() + "@" + domain + ">");
            }
        };
        mm.setFrom(_from);
        mm.setSender(_from);

        InternetAddress replyTo = getReplyTo();
        if (replyTo != null) {
            mm.setReplyTo(new Address[] { replyTo });
        }
        mm.setHeader("X-Mailer", "molindo-notify");
        mm.setSentDate(new Date());

        mm.setRecipient(RecipientType.TO,
                new InternetAddress(recipient, recipientName, CharsetUtils.UTF_8.displayName()));
        mm.setSubject(subject, CharsetUtils.UTF_8.displayName());

        if (_format == Format.HTML) {
            if (message.getType() == Type.TEXT) {
                throw new MailException("can't send HTML mail from TEXT message", false);
            }
            mm.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html");
        } else if (_format == Format.TEXT || _format == Format.MULTI && message.getType() == Type.TEXT) {
            mm.setText(message.getText(), CharsetUtils.UTF_8.displayName());
        } else if (_format == Format.MULTI) {
            MimeBodyPart html = new MimeBodyPart();
            html.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html");

            MimeBodyPart text = new MimeBodyPart();
            text.setText(message.getText(), CharsetUtils.UTF_8.displayName());

            /*
             * The formats are ordered by how faithful they are to the
             * original, with the least faithful first and the most faithful
             * last. (http://en.wikipedia.org/wiki/MIME#Alternative)
             */
            MimeMultipart mmp = new MimeMultipart();
            mmp.setSubType("alternative");

            mmp.addBodyPart(text);
            mmp.addBodyPart(html);

            mm.setContent(mmp);
        } else {
            throw new NotifyRuntimeException(
                    "unexpected format (" + _format + ") or type (" + message.getType() + ")");
        }

        send(mm);

    } catch (final MessagingException e) {
        throw new MailException(
                "could not send mail from " + _from + " to " + recipient + " (" + toErrorMessage(e) + ")", e,
                isTemporary(e));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("utf8 unknown?", e);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.email.FreemarkerEmailMessage.java

private void addBodyPart(MimeMultipart content, String textBody, String type) throws MessagingException {
    MimeBodyPart bodyPart = new MimeBodyPart();
    bodyPart.setContent(textBody, type);
    content.addBodyPart(bodyPart);
}

From source file:fr.paris.lutece.portal.service.mail.MailUtil.java

/**
 * Send a Multipart HTML message with the attachements associated to the
 * message and attached files. FIXME: use prepareMessage method
 *
 * @param strRecipientsTo//from ww  w  . ja  v  a2s  .c  o  m
 *            The list of the main recipients email.Every recipient must be
 *            separated by the mail separator defined in config.properties
 * @param strRecipientsCc
 *            The recipients list of the carbon copies .
 * @param strRecipientsBcc
 *            The recipients list of the blind carbon copies .
 * @param strSenderName
 *            The sender name.
 * @param strSenderEmail
 *            The sender email address.
 * @param strSubject
 *            The message subject.
 * @param strMessage
 *            The message.
 * @param urlAttachements
 *            The List of UrlAttachement Object, containing the URL of
 *            attachments associated with their content-location.
 * @param fileAttachements
 *            The list of files attached
 * @param transport
 *            the smtp transport object
 * @param session
 *            the smtp session object
 * @throws AddressException
 *             If invalid address
 * @throws SendFailedException
 *             If an error occured during sending
 * @throws MessagingException
 *             If a messaging error occurred
 */
protected static void sendMultipartMessageHtml(String strRecipientsTo, String strRecipientsCc,
        String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject,
        String strMessage, List<UrlAttachment> urlAttachements, List<FileAttachment> fileAttachements,
        Transport transport, Session session) throws MessagingException, AddressException, SendFailedException {
    Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName,
            strSenderEmail, strSubject, session);
    msg.setHeader(HEADER_NAME, HEADER_VALUE);

    // Creation of the root part containing all the elements of the message
    MimeMultipart multipart = ((fileAttachements == null) || (fileAttachements.isEmpty()))
            ? new MimeMultipart(MULTIPART_RELATED)
            : new MimeMultipart();

    // Creation of the html part, the "core" of the message
    BodyPart msgBodyPart = new MimeBodyPart();
    // msgBodyPart.setContent( strMessage, BODY_PART_MIME_TYPE );
    msgBodyPart.setDataHandler(new DataHandler(
            new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_HTML)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET))));
    multipart.addBodyPart(msgBodyPart);

    if (urlAttachements != null) {
        ByteArrayDataSource urlByteArrayDataSource;

        for (UrlAttachment urlAttachement : urlAttachements) {
            urlByteArrayDataSource = convertUrlAttachmentDataSourceToByteArrayDataSource(urlAttachement);

            if (urlByteArrayDataSource != null) {
                msgBodyPart = new MimeBodyPart();
                // Fill this part, then add it to the root part with the
                // good headers
                msgBodyPart.setDataHandler(new DataHandler(urlByteArrayDataSource));
                msgBodyPart.setHeader(HEADER_CONTENT_LOCATION, urlAttachement.getContentLocation());
                multipart.addBodyPart(msgBodyPart);
            }
        }
    }

    // add File Attachement
    if (fileAttachements != null) {
        for (FileAttachment fileAttachement : fileAttachements) {
            String strFileName = fileAttachement.getFileName();
            byte[] bContentFile = fileAttachement.getData();
            String strContentType = fileAttachement.getType();
            ByteArrayDataSource dataSource = new ByteArrayDataSource(bContentFile, strContentType);
            msgBodyPart = new MimeBodyPart();
            msgBodyPart.setDataHandler(new DataHandler(dataSource));
            msgBodyPart.setFileName(strFileName);
            msgBodyPart.setDisposition(CONSTANT_DISPOSITION_ATTACHMENT);
            multipart.addBodyPart(msgBodyPart);
        }
    }

    msg.setContent(multipart);

    sendMessage(msg, transport);
}