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:org.wf.dp.dniprorada.util.MailOld.java

public MailOld _PartHTML() throws MessagingException, EmailException {
    //        init();
    log.info("_PartHTML");
    //oMultiPartEmail.setMsg("0");
    MimeMultipart oMimeMultipart = new MimeMultipart("related");
    BodyPart oBodyPart = new MimeBodyPart();
    oBodyPart.setContent(getBody(), "text/html; charset=\"utf-8\"");
    oMimeMultipart.addBodyPart(oBodyPart);
    oMultiPartEmail.setContent(oMimeMultipart);
    log.info("getBody()=" + getBody());
    return this;
}

From source file:org.igov.io.mail.MailOld.java

public MailOld _PartHTML() throws MessagingException, EmailException {
    //        init();
    LOG.info("_PartHTML");
    //oMultiPartEmail.setMsg("0");
    MimeMultipart oMimeMultipart = new MimeMultipart("related");
    BodyPart oBodyPart = new MimeBodyPart();
    oBodyPart.setContent(getBody(), "text/html; charset=\"utf-8\"");
    oMimeMultipart.addBodyPart(oBodyPart);
    oMultiPartEmail.setContent(oMimeMultipart);
    LOG.info("(getBody()={})", getBody());
    return this;
}

From source file:com.basicservice.service.MailService.java

public void sendEmail(String from, String to, String subject, String messageHtml) throws Exception {
    try {//from  w  w  w.j a  v a2  s .  co m
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", 587);
        props.put("mail.smtp.auth", "true");
        Authenticator auth = new SMTPAuthenticator();
        Session mailSession = Session.getDefaultInstance(props, auth);
        // mailSession.setDebug(true);
        Transport transport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        Multipart multipart = new MimeMultipart("alternative");

        BodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(new String(messageHtml.getBytes("UTF8"), "ISO-8859-1"), "text/html");
        multipart.addBodyPart(htmlPart);

        message.setContent(multipart);
        message.setFrom(new InternetAddress(from));
        message.setSubject(subject, "UTF-8");
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        transport.connect();
        transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
        transport.close();
    } catch (Exception e) {
        LOG.debug("Exception while sending email: ", e);
        throw e;
    }
}

From source file:gov.nih.nci.caarray.util.EmailUtil.java

/**
 * Sends a multipart email with both HTML and plain-text bodies based upon input parameters.
 *
 * @param mailRecipients List of strings that are the recipient email addresses
 * @param from the from of the email/*  ww  w  .ja  va  2s.c  o  m*/
 * @param mailSubject the subject of the email
 * @param htmlMailBody the HTML version of the body of the email
 * @param plainMailBody the plain-text version of the body of the email
 * @throws MessagingException thrown if there is a problem sending the message
 */
public static void sendMultipartMail(List<String> mailRecipients, String from, String mailSubject,
        String htmlMailBody, String plainMailBody) throws MessagingException {
    MimeMessage message = constructMessage(mailRecipients, from, mailSubject);

    Multipart mp = new MimeMultipart("alternative");
    addBodyPart(mp, htmlMailBody, "text/html");
    addBodyPart(mp, plainMailBody, "text/plain");
    message.setContent(mp);

    LOG.debug("sending email");
    Transport.send(message);
    LOG.debug("email successfully sent");
}

From source file:com.tdclighthouse.commons.mail.util.MailClient.java

public void sendMail(String from, String[] to, Mail mail) throws MessagingException, AddressException {
    // a brief validation
    if ((from == null) || "".equals(from) || (to.length == 0) || (mail == null)) {
        throw new IllegalArgumentException();
    }//from   www.j a v  a 2  s  . c o m
    Session session = getSession();

    // Define a new mail message
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    for (int i = 0; i < to.length; i++) {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i]));
    }
    message.setSubject(mail.getSubject(), "utf-8");

    // use a MimeMultipart as we need to handle the file attachments
    Multipart multipart = new MimeMultipart("alternative");

    if ((mail.getMessageBody() != null) && !"".equals(mail.getMessageBody())) {
        // add the message body to the mime message
        BodyPart textPart = new MimeBodyPart();
        textPart.setContent(mail.getMessageBody(), "text/plain; charset=utf-8"); // sets type to "text/plain"
        multipart.addBodyPart(textPart);
    }

    if (mail.getHtmlBody() != null) {
        BodyPart pixPart = new MimeBodyPart();
        pixPart.setContent(mail.getHtmlBody(), "text/html; charset=utf-8");
        multipart.addBodyPart(pixPart);
    }

    // add any file attachments to the message
    addAtachments(mail.getAttachments(), multipart);

    // Put all message parts in the message
    message.setContent(multipart);

    // Send the message
    Transport.send(message);

}

From source file:com.mirth.connect.server.userutil.HTTPUtil.java

/**
 * Serializes an HTTP request body into XML. Multipart requests will also automatically be
 * parsed into separate XML nodes./*from   ww  w .j a  va 2 s .  com*/
 * 
 * @param httpBody
 *            The request body/payload string to parse.
 * @param contentType
 *            The MIME content type of the request.
 * @return The serialized XML string.
 * @throws MessagingException
 * @throws IOException
 * @throws DonkeyElementException
 * @throws ParserConfigurationException
 */
public static String httpBodyToXml(String httpBody, String contentType)
        throws MessagingException, IOException, DonkeyElementException, ParserConfigurationException {
    ContentType type = getContentType(contentType);
    Object content;

    if (type.getMimeType().startsWith(FileUploadBase.MULTIPART)) {
        content = new MimeMultipart(new ByteArrayDataSource(httpBody, type.toString()));
    } else {
        content = httpBody;
    }

    return HttpMessageConverter.contentToXml(content, type, true, null);
}

From source file:com.haulmont.cuba.core.app.EmailSender.java

protected MimeMessage createMimeMessage(SendingMessage sendingMessage) throws MessagingException {
    MimeMessage msg = mailSender.createMimeMessage();
    assignRecipient(sendingMessage, msg);
    msg.setSubject(sendingMessage.getCaption(), StandardCharsets.UTF_8.name());
    msg.setSentDate(timeSource.currentTimestamp());

    assignFromAddress(sendingMessage, msg);
    addHeaders(sendingMessage, msg);/*w  w w  .j a  v  a  2s  .c o m*/

    MimeMultipart content = new MimeMultipart("mixed");
    MimeMultipart textPart = new MimeMultipart("related");

    setMimeMessageContent(sendingMessage, content, textPart);

    for (SendingAttachment attachment : sendingMessage.getAttachments()) {
        MimeBodyPart attachmentPart = createAttachmentPart(attachment);

        if (attachment.getContentId() == null) {
            content.addBodyPart(attachmentPart);
        } else
            textPart.addBodyPart(attachmentPart);
    }

    msg.setContent(content);
    msg.saveChanges();
    return msg;
}

From source file:org.eclipse.ecr.automation.server.jaxrs.io.MultiPartRequestReader.java

public ExecutionRequest readFrom(Class<ExecutionRequest> arg0, Type arg1, Annotation[] arg2, MediaType arg3,
        MultivaluedMap<String, String> headers, InputStream in) throws IOException, WebApplicationException {
    ExecutionRequest req = null;/* www. j  ava  2 s . c  om*/
    try {
        List<String> ctypes = headers.get("Content-Type");
        String ctype = ctypes.get(0);
        // we need to copy first the stream into a file otherwise it may
        // happen that
        // javax.mail fail to receive some parts - I am not sure why -
        // perhaps the stream is no more available when javax.mail need it?
        File tmp = File.createTempFile("nx-automation-mp-upload-", ".tmp");
        FileUtils.copyToFile(in, tmp);
        in = new FileInputStream(tmp); // get the input from the saved
                                       // file
        try {
            MimeMultipart mp = new MimeMultipart(new InputStreamDataSource(in, ctype));
            BodyPart part = mp.getBodyPart(0); // use content ids
            InputStream pin = part.getInputStream();
            req = JsonRequestReader.readRequest(pin, headers);
            int cnt = mp.getCount();
            if (cnt == 2) { // a blob
                req.setInput(readBlob(request, mp.getBodyPart(1)));
            } else if (cnt > 2) { // a blob list
                BlobList blobs = new BlobList();
                for (int i = 1; i < cnt; i++) {
                    blobs.add(readBlob(request, mp.getBodyPart(i)));
                }
                req.setInput(blobs);
            } else {
                log.error("Not all parts received.");
                for (int i = 0; i < cnt; i++) {
                    log.error("Received parts: " + mp.getBodyPart(i).getHeader("Content-ID")[0] + " -> "
                            + mp.getBodyPart(i).getContentType());
                }
                throw ExceptionHandler.newException(
                        new IllegalStateException("Received only " + cnt + " part in a multipart request"));
            }
        } finally {
            tmp.delete();
        }
    } catch (Throwable e) {
        throw ExceptionHandler.newException("Failed to parse multipart request", e);
    }
    return req;
}

From source file:com.pushinginertia.commons.net.email.EmailUtils.java

/**
 * Populates a newly instantiated {@link MultiPartEmail} with the given arguments.
 * @param email email instance to populate
 * @param smtpHost SMTP host that the message will be sent to
 * @param msg container object for the email's headers and contents
 * @throws IllegalArgumentException if the inputs are not valid
 * @throws EmailException if a problem occurs constructing the email
 *//*from   w w  w .  j  ava2 s.  co  m*/
public static void populateMultiPartEmail(final MultiPartEmail email, final String smtpHost,
        final EmailMessage msg) throws IllegalArgumentException, EmailException {
    ValidateAs.notNull(email, "email");
    ValidateAs.notNull(smtpHost, "smtpHost");
    ValidateAs.notNull(msg, "msg");

    email.setHostName(smtpHost);
    email.setCharset(UTF_8);
    email.setFrom(msg.getSender().getEmail(), msg.getSender().getName(), UTF_8);
    email.addTo(msg.getRecipient().getEmail(), msg.getRecipient().getName(), UTF_8);

    final NameEmail replyTo = msg.getReplyTo();
    if (replyTo != null) {
        email.addReplyTo(replyTo.getEmail(), replyTo.getName(), UTF_8);
    }

    final String bounceEmailAddress = msg.getBounceEmailAddress();
    if (bounceEmailAddress != null) {
        email.setBounceAddress(bounceEmailAddress);
    }

    email.setSubject(msg.getSubject());

    final String languageId = msg.getRecipient().getLanguage();
    if (languageId != null) {
        email.addHeader("Language", languageId);
        email.addHeader("Content-Language", languageId);
    }

    // add optional headers
    final EmailMessageHeaders headers = msg.getHeaders();
    if (headers != null) {
        for (final Map.Entry<String, String> header : headers.getHeaders().entrySet()) {
            email.addHeader(header.getKey(), header.getValue());
        }
    }

    // generate email body
    try {
        final MimeMultipart mm = new MimeMultipart("alternative; charset=UTF-8");

        final MimeBodyPart text = new MimeBodyPart();
        text.setContent(msg.getTextContent(), "text/plain; charset=UTF-8");
        mm.addBodyPart(text);

        final MimeBodyPart html = new MimeBodyPart();
        html.setContent(msg.getHtmlContent(), "text/html; charset=UTF-8");
        mm.addBodyPart(html);

        email.setContent(mm);
    } catch (MessagingException e) {
        throw new EmailException(e);
    }

}

From source file:org.eclipse.ecr.automation.server.jaxrs.io.MultiPartFormRequestReader.java

public ExecutionRequest readFrom(Class<ExecutionRequest> arg0, Type arg1, Annotation[] arg2, MediaType arg3,
        MultivaluedMap<String, String> headers, InputStream in) throws IOException, WebApplicationException {
    ExecutionRequest req = null;// w w w . j  a  va 2  s  . c  o m
    try {
        List<String> ctypes = headers.get("Content-Type");
        String ctype = ctypes.get(0);
        // we need to copy first the stream into a file otherwise it may
        // happen that
        // javax.mail fail to receive some parts - I am not sure why -
        // perhaps the stream is no more available when javax.mail need it?
        File tmp = File.createTempFile("nx-automation-mp-upload-", ".tmp");
        FileUtils.copyToFile(in, tmp);
        // get the input from the saved file
        in = new SharedFileInputStream(tmp);
        try {
            MimeMultipart mp = new MimeMultipart(new InputStreamDataSource(in, ctype));
            BodyPart part = mp.getBodyPart(0); // use content ids
            InputStream pin = part.getInputStream();
            req = JsonRequestReader.readRequest(pin, headers);
            int cnt = mp.getCount();
            if (cnt == 2) { // a blob
                req.setInput(readBlob(request, mp.getBodyPart(1)));
            } else if (cnt > 2) { // a blob list
                BlobList blobs = new BlobList();
                for (int i = 1; i < cnt; i++) {
                    blobs.add(readBlob(request, mp.getBodyPart(i)));
                }
                req.setInput(blobs);
            } else {
                log.error("Not all parts received.");
                for (int i = 0; i < cnt; i++) {
                    log.error("Received parts: " + mp.getBodyPart(i).getHeader("Content-ID")[0] + " -> "
                            + mp.getBodyPart(i).getContentType());
                }
                throw ExceptionHandler.newException(
                        new IllegalStateException("Received only " + cnt + " part in a multipart request"));
            }
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                // do nothing
            }
            tmp.delete();
        }
    } catch (Throwable e) {
        throw ExceptionHandler.newException("Failed to parse multipart request", e);
    }
    return req;
}