Example usage for javax.mail.internet MimeMultipart MimeMultipart

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

Introduction

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

Prototype

public MimeMultipart(DataSource ds) throws MessagingException 

Source Link

Document

Constructs a MimeMultipart object and its bodyparts from the given DataSource.

Usage

From source file:com.adaptris.core.services.mime.FlattenMimeParts.java

@Override
public void doService(AdaptrisMessage msg) throws ServiceException {
    try (InputStream in = msg.getInputStream()) {
        InputStreamDataSource src = new InputStreamDataSource(in);
        MimeMultipart mime = new MimeMultipart(src);
        MultiPartOutput output = new MultiPartOutput(msg.getUniqueId());
        List<BodyPart> parts = extract(mime);
        for (BodyPart p : parts) {
            output.addPart((MimeBodyPart) p, generateIfNoContentId(p));
        }//  w ww .j ava 2s.  c o  m
        addHeaders(src.getHeaders(), output);
        try (OutputStream out = msg.getOutputStream()) {
            output.writeTo(out);
        }
    } catch (Exception e) {
        throw ExceptionHelper.wrapServiceException(e);
    }
}

From source file:uk.ac.cam.cl.dtg.util.Mailer.java

/**
 * Utility method to allow us to send multipart messages using HTML and plain text.
 *
 * /*  w  ww  .  ja  va  2  s. c o m*/
 * @param recipient
 *            - string array of recipients that the message should be sent to
 * @param from
 *            - the e-mail address that should be used as the sending address
 * @param replyTo
 *            - (nullable) the e-mail address that should be used as the reply-to address
* @param replyToName
*            - (nullable) the name that should be used as the reply-to name
 * @param subject
 *            - The message subject
 * @param plainText
 *            - The message body
 * @param html
 *            - The message body in html
 * @throws MessagingException
 *             - if we cannot send the message for some reason.
 * @throws AddressException
 *             - if the address is not valid.
 */
public void sendMultiPartMail(final String[] recipient, final String from, @Nullable final String replyTo,
        @Nullable final String replyToName, final String subject, final String plainText, final String html)
        throws MessagingException, AddressException, UnsupportedEncodingException {
    Message msg = this.setupMessage(recipient, from, replyTo, replyToName, subject);

    // Create the text part
    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setText(plainText, "utf-8");

    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(html, "text/html; charset=utf-8");

    Multipart multiPart = new MimeMultipart("alternative");
    multiPart.addBodyPart(textPart);
    multiPart.addBodyPart(htmlPart);

    msg.setContent(multiPart);

    Transport.send(msg);
}

From source file:org.xwiki.mail.internal.factory.html.HTMLMimeBodyPartFactory.java

/**
 * @return Multipart part of the email, define the HTML as a multipart/alternative
 *///from  w w w  .java2 s .c  om
private MimeBodyPart createAlternativePart(MimeBodyPart htmlBodyPart, MimeBodyPart textBodyPart)
        throws MessagingException {
    MimeMultipart alternativeMultiPart = new MimeMultipart("alternative");

    // Note: it's important to have the text before the HTML, from low fidelity to high fidelity according to the
    // MIME specification. Otherwise some readers will display text even though there's HTML in your mail message.
    alternativeMultiPart.addBodyPart(textBodyPart);
    alternativeMultiPart.addBodyPart(htmlBodyPart);

    MimeBodyPart alternativePartWrapper = new MimeBodyPart();
    alternativePartWrapper.setContent(alternativeMultiPart);
    return alternativePartWrapper;
}

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

private Multipart createPartForMultipart(final String templateFilename, final Map<String, Object> context,
        final String multipartType, final String mimeType) throws IOException, MessagingException {
    final Multipart multipart = new MimeMultipart(multipartType);
    multipart.addBodyPart(createBodyPart(mimeType, templateFilename, context));
    return multipart;
}

From source file:org.sigmah.server.mail.MailSenderImpl.java

@Override
public void sendFile(Email email, String fileName, InputStream fileStream) throws EmailException {
    final String user = email.getAuthenticationUserName();
    final String password = email.getAuthenticationPassword();

    final Properties properties = new Properties();
    properties.setProperty(MAIL_TRANSPORT_PROTOCOL, TRANSPORT_PROTOCOL);
    properties.setProperty(MAIL_SMTP_HOST, email.getHostName());
    properties.setProperty(MAIL_SMTP_PORT, Integer.toString(email.getSmtpPort()));

    final StringBuilder toBuilder = new StringBuilder();
    for (final String to : email.getToAddresses()) {
        if (toBuilder.length() > 0) {
            toBuilder.append(',');
        }/*  w  ww .  ja v  a2  s .  com*/
        toBuilder.append(to);
    }

    final StringBuilder ccBuilder = new StringBuilder();
    if (email.getCcAddresses().length > 0) {
        for (final String cc : email.getCcAddresses()) {
            if (ccBuilder.length() > 0) {
                ccBuilder.append(',');
            }
            ccBuilder.append(cc);
        }
    }

    final Session session = javax.mail.Session.getInstance(properties);
    try {
        final DataSource attachment = new ByteArrayDataSource(fileStream,
                FileType.fromExtension(FileType.getExtension(fileName), FileType._DEFAULT).getContentType());

        final Transport transport = session.getTransport();

        if (password != null) {
            transport.connect(user, password);
        } else {
            transport.connect();
        }

        final MimeMessage message = new MimeMessage(session);

        // Configures the headers.
        message.setFrom(new InternetAddress(email.getFromAddress(), false));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toBuilder.toString(), false));
        if (email.getCcAddresses().length > 0) {
            message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccBuilder.toString(), false));
        }

        message.setSubject(email.getSubject(), email.getEncoding());

        // Html body part.
        final MimeMultipart textMultipart = new MimeMultipart("alternative");

        final MimeBodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(email.getContent(), "text/html; charset=\"" + email.getEncoding() + "\"");
        textMultipart.addBodyPart(htmlBodyPart);

        final MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(textMultipart);

        // Attachment body part.
        final MimeBodyPart attachmentPart = new MimeBodyPart();
        attachmentPart.setDataHandler(new DataHandler(attachment));
        attachmentPart.setFileName(fileName);
        attachmentPart.setDescription(fileName);

        // Mail multipart content.
        final MimeMultipart contentMultipart = new MimeMultipart("related");
        contentMultipart.addBodyPart(textBodyPart);
        contentMultipart.addBodyPart(attachmentPart);

        message.setContent(contentMultipart);
        message.saveChanges();

        // Sends the mail.
        transport.sendMessage(message, message.getAllRecipients());

    } catch (UnsupportedEncodingException ex) {
        throw new EmailException(
                "An error occured while encoding the mail content to '" + email.getEncoding() + "'.", ex);

    } catch (IOException ex) {
        throw new EmailException("An error occured while reading the attachment of an email.", ex);

    } catch (MessagingException ex) {
        throw new EmailException("An error occured while sending an email.", ex);
    }
}

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

public boolean send() {
    try {//  w w  w . ja  v  a 2  s .c om
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setReplyTo(new Address[] { replyToAddress });

        if (fromAddress == null) {
            msg.addFrom(new Address[] { replyToAddress });
        } else {
            msg.addFrom(new Address[] { fromAddress });
        }

        for (Recipient recipient : recipients) {
            msg.addRecipient(recipient.type, recipient.address);
        }

        msg.setSubject(subject);

        if (textContent.isEmpty()) {
            if (htmlContent.isEmpty()) {
                log.error("Message has neither text body nor HTML body");
            } else {
                msg.setContent(htmlContent, "text/html");
            }
        } else {
            if (htmlContent.isEmpty()) {
                msg.setContent(textContent, "text/plain");
            } else {
                MimeMultipart content = new MimeMultipart("alternative");
                addBodyPart(content, textContent, "text/plain");
                addBodyPart(content, htmlContent, "text/html");
                msg.setContent(content);
            }
        }

        msg.setSentDate(new Date());

        Transport.send(msg);
        return true;
    } catch (MessagingException e) {
        log.error("Failed to send message.", e);
        return false;
    }
}

From source file:org.artifactory.mail.MailServiceImpl.java

/**
 * Send an e-mail message/*from w  w w .  j  a  v  a2s.  c o m*/
 *
 * @param recipients Recipients of the message that will be sent
 * @param subject    The subject of the message
 * @param body       The body of the message
 * @param config     A mail server configuration to use
 * @throws Exception
 */
@Override
public void sendMail(String[] recipients, String subject, String body, final MailServerConfiguration config)
        throws EmailException {

    verifyParameters(recipients, config);

    if (!config.isEnabled()) {
        log.debug("Ignoring requested mail delivery. The given configuration is disabled.");
        return;
    }

    boolean debugEnabled = log.isDebugEnabled();

    Properties properties = new Properties();

    properties.put("mail.smtp.host", config.getHost());
    properties.put("mail.smtp.port", Integer.toString(config.getPort()));

    properties.put("mail.smtp.quitwait", "false");

    //Default protocol
    String protocol = "smtp";

    //Enable TLS if set
    if (config.isUseTls()) {
        properties.put("mail.smtp.starttls.enable", "true");
    }

    //Enable SSL if set
    boolean useSsl = config.isUseSsl();
    if (useSsl) {
        properties.put("mail.smtp.socketFactory.port", Integer.toString(config.getPort()));
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.socketFactory.fallback", "false");
        //Requires special protocol
        protocol = "smtps";
    }

    //Set debug property if enabled by the logger
    properties.put("mail.debug", debugEnabled);

    Authenticator authenticator = null;
    if (!StringUtils.isEmpty(config.getUsername())) {
        properties.put("mail.smtp.auth", "true");
        authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.getUsername(), config.getPassword());
            }
        };
    }

    Session session = Session.getInstance(properties, authenticator);
    Message message = new MimeMessage(session);

    String subjectPrefix = config.getSubjectPrefix();
    String fullSubject = (!StringUtils.isEmpty(subjectPrefix)) ? (subjectPrefix + " " + subject) : subject;
    try {
        message.setSubject(fullSubject);

        if (!StringUtils.isEmpty(config.getFrom())) {
            InternetAddress addressFrom = new InternetAddress(config.getFrom());
            message.setFrom(addressFrom);
        }

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        message.addRecipients(Message.RecipientType.TO, addressTo);

        //Create multi-part message in case we want to add html support
        Multipart multipart = new MimeMultipart("related");

        BodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(body, "text/html");
        multipart.addBodyPart(htmlPart);
        message.setContent(multipart);

        //Set debug property if enabled by the logger
        session.setDebug(debugEnabled);

        //Connect and send
        Transport transport = session.getTransport(protocol);
        if (useSsl) {
            transport.connect(config.getHost(), config.getPort(), config.getUsername(), config.getPassword());
        } else {
            transport.connect();
        }
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    } catch (MessagingException e) {
        String em = e.getMessage();
        throw new EmailException(
                "An error has occurred while sending an e-mail" + (em != null ? ": " + em.trim() : "") + ".\n",
                e);
    }
}

From source file:org.xwiki.mail.internal.factory.html.HTMLMimeBodyPartFactory.java

private MimeMultipart createHTMLMultipart(String content, List<Attachment> embeddedImages)
        throws MessagingException {
    MimeMultipart htmlMultipart = new MimeMultipart("related");
    htmlMultipart.addBodyPart(createHTMLBodyPart(content, true));
    handleAttachments(htmlMultipart, embeddedImages);
    return htmlMultipart;
}

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);//w ww.j a  v  a  2 s . co  m
    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:com.ctriposs.r2.message.rest.QueryTunnelUtil.java

/**
 * Takes a Request object that has been encoded for tunnelling as a POST with an X-HTTP-Override-Method header and
 * creates a new request that represents the intended original request
 *
 * @param request the request to be decoded
 *
 * @return a decoded RestRequest/*from  ww w . ja  va2 s .  co m*/
 */
public static RestRequest decode(final RestRequest request)
        throws MessagingException, IOException, URISyntaxException {
    if (request.getHeader(HEADER_METHOD_OVERRIDE) == null) {
        // Not a tunnelled request, just pass thru
        return request;
    }

    String query = null;
    byte[] entity = new byte[0];

    // All encoded requests must have a content type. If the header is missing, ContentType throws an exception
    ContentType contentType = new ContentType(request.getHeader(HEADER_CONTENT_TYPE));

    RestRequestBuilder requestBuilder = request.builder();

    // Get copy of headers and remove the override
    Map<String, String> h = new HashMap<String, String>(request.getHeaders());
    h.remove(HEADER_METHOD_OVERRIDE);

    // Simple case, just extract query params from entity, append to query, and clear entity
    if (contentType.getBaseType().equals(FORM_URL_ENCODED)) {
        query = request.getEntity().asString(Data.UTF_8_CHARSET);
        h.remove(HEADER_CONTENT_TYPE);
        h.remove(CONTENT_LENGTH);
    } else if (contentType.getBaseType().equals(MULTIPART)) {
        // Clear these in case there is no body part
        h.remove(HEADER_CONTENT_TYPE);
        h.remove(CONTENT_LENGTH);

        MimeMultipart multi = new MimeMultipart(new DataSource() {
            @Override
            public InputStream getInputStream() throws IOException {
                return request.getEntity().asInputStream();
            }

            @Override
            public OutputStream getOutputStream() throws IOException {
                return null;
            }

            @Override
            public String getContentType() {
                return request.getHeader(HEADER_CONTENT_TYPE);
            }

            @Override
            public String getName() {
                return null;
            }
        });

        for (int i = 0; i < multi.getCount(); i++) {
            MimeBodyPart part = (MimeBodyPart) multi.getBodyPart(i);

            if (part.isMimeType(FORM_URL_ENCODED) && query == null) {
                // Assume the first segment we come to that is urlencoded is the tunneled query params
                query = IOUtils.toString((InputStream) part.getContent(), UTF8);
            } else if (entity.length <= 0) {
                // Assume the first non-urlencoded content we come to is the intended entity.
                entity = IOUtils.toByteArray((InputStream) part.getContent());
                h.put(CONTENT_LENGTH, Integer.toString(entity.length));
                h.put(HEADER_CONTENT_TYPE, part.getContentType());
            } else {
                // If it's not form-urlencoded and we've already found another section,
                // this has to be be an extra body section, which we have no way to handle.
                // Proceed with the request as if the 1st part we found was the expected body,
                // but log a warning in case some client is constructing a request that doesn't
                // follow the rules.
                String unexpectedContentType = part.getContentType();
                LOG.warn("Unexpected body part in X-HTTP-Method-Override request, type="
                        + unexpectedContentType);
            }
        }
    }

    // Based on what we've found, construct the modified request. It's possible that someone has
    // modified the request URI, adding extra query params for debugging, tracking, etc, so
    // we have to check and append the original query correctly.
    if (query != null && query.length() > 0) {
        String separator = "&";
        String existingQuery = request.getURI().getRawQuery();

        if (existingQuery == null) {
            separator = "?";
        } else if (existingQuery.isEmpty()) {
            // This would mean someone has appended a "?" with no args to the url underneath us
            separator = "";
        }

        requestBuilder.setURI(new URI(request.getURI().toString() + separator + query));
    }
    requestBuilder.setEntity(entity);
    requestBuilder.setHeaders(h);
    requestBuilder.setMethod(request.getHeader(HEADER_METHOD_OVERRIDE));

    return requestBuilder.build();
}