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:it.ozimov.springboot.templating.mail.service.EmailServiceImpl.java

public MimeMessage send(final @NonNull Email email, final @NonNull String template,
        final Map<String, Object> modelObject, final @NonNull InlinePicture... inlinePictures)
        throws CannotSendEmailException {
    email.setSentAt(new Date());
    final MimeMessage mimeMessage = toMimeMessage(email);
    try {//from  ww w  .  ja  v a 2  s.  c  om
        final MimeMultipart content = new MimeMultipart("related");

        String text = templateService.mergeTemplateIntoString(template,
                fromNullable(modelObject).or(ImmutableMap.of()));

        for (final InlinePicture inlinePicture : inlinePictures) {
            final String cid = UUID.randomUUID().toString();

            //Set the cid in the template
            text = text.replace(inlinePicture.getTemplateName(), "cid:" + cid);

            //Set the image part
            final MimeBodyPart imagePart = new MimeBodyPart();
            imagePart.attachFile(inlinePicture.getFile());
            imagePart.setContentID('<' + cid + '>');
            imagePart.setDisposition(MimeBodyPart.INLINE);
            imagePart.setHeader("Content-Type", inlinePicture.getImageType().getContentType());
            content.addBodyPart(imagePart);
        }

        //Set the HTML text part
        final MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(text, email.getEncoding().displayName(), "html");
        content.addBodyPart(textPart);

        mimeMessage.setContent(content);
        javaMailSender.send(mimeMessage);
    } catch (IOException e) {
        log.error("The template file cannot be read", e);
        throw new CannotSendEmailException(
                "Error while sending the email due to problems with the template file", e);
    } catch (TemplateException e) {
        log.error("The template file cannot be processed", e);
        throw new CannotSendEmailException(
                "Error while processing the template file with the given model object", e);
    } catch (MessagingException e) {
        log.error("The mime message cannot be created", e);
        throw new CannotSendEmailException(
                "Error while sending the email due to problems with the mime content", e);
    }
    return mimeMessage;
}

From source file:gwtupload.sendmailsample.server.SendMailSampleServlet.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    try {/*from  ww w .  jav  a 2  s .c o  m*/
        String from = null, to = null, subject = "", body = "";
        // create a new multipart content
        MimeMultipart multiPart = new MimeMultipart();
        for (FileItem item : sessionFiles) {
            if (item.isFormField()) {
                if ("from".equals(item.getFieldName()))
                    from = item.getString();
                if ("to".equals(item.getFieldName()))
                    to = item.getString();
                if ("subject".equals(item.getFieldName()))
                    subject = item.getString();
                if ("body".equals(item.getFieldName()))
                    body = item.getString();
            } else {
                // add the file part to multipart content
                MimeBodyPart part = new MimeBodyPart();
                part.setFileName(item.getName());
                part.setDataHandler(
                        new DataHandler(new ByteArrayDataSource(item.get(), item.getContentType())));
                multiPart.addBodyPart(part);
            }
        }

        // add the text part to multipart content
        MimeBodyPart txtPart = new MimeBodyPart();
        txtPart.setContent(body, "text/plain");
        multiPart.addBodyPart(txtPart);

        // configure smtp server
        Properties props = System.getProperties();
        props.put("mail.smtp.host", SMTP_SERVER);
        // create a new mail session and the mime message
        MimeMessage mime = new MimeMessage(Session.getInstance(props));
        mime.setText(body);
        mime.setContent(multiPart);
        mime.setSubject(subject);
        mime.setFrom(new InternetAddress(from));
        for (String rcpt : to.split("[\\s;,]+"))
            mime.addRecipient(Message.RecipientType.TO, new InternetAddress(rcpt));
        // send the message
        Transport.send(mime);
    } catch (MessagingException e) {
        throw new UploadActionException(e.getMessage());
    }
    return "Your mail has been sent successfuly.";
}

From source file:com.liferay.mail.imap.IMAPAccessor.java

protected Message createMessage(String personalName, String sender, Address[] to, Address[] cc, Address[] bcc,
        String subject, String body, List<MailFile> mailFiles)
        throws MessagingException, UnsupportedEncodingException {

    Message jxMessage = new MimeMessage(_imapConnection.getSession());

    jxMessage.setFrom(new InternetAddress(sender, personalName));
    jxMessage.addRecipients(Message.RecipientType.TO, to);
    jxMessage.addRecipients(Message.RecipientType.CC, cc);
    jxMessage.addRecipients(Message.RecipientType.BCC, bcc);
    jxMessage.setSentDate(new Date());
    jxMessage.setSubject(subject);// ww w  . ja  v  a 2 s  .  c  o m

    MimeMultipart multipart = new MimeMultipart();

    BodyPart messageBodyPart = new MimeBodyPart();

    messageBodyPart.setContent(body, ContentTypes.TEXT_HTML_UTF8);

    multipart.addBodyPart(messageBodyPart);

    if (mailFiles != null) {
        for (MailFile mailFile : mailFiles) {
            File file = mailFile.getFile();

            if (!file.exists()) {
                continue;
            }

            DataSource dataSource = new FileDataSource(file);

            BodyPart attachmentBodyPart = new MimeBodyPart();

            attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
            attachmentBodyPart.setFileName(mailFile.getFileName());

            multipart.addBodyPart(attachmentBodyPart);
        }
    }

    jxMessage.setContent(multipart);

    return jxMessage;
}

From source file:lucee.runtime.net.mail.HtmlEmailImpl.java

/**
 * @throws EmailException EmailException
 * @throws MessagingException MessagingException
 *///from w  w w .  j  ava  2  s. c  o m
private void buildNoAttachments() throws MessagingException, EmailException {
    MimeMultipart container = this.getContainer();
    MimeMultipart subContainerHTML = new MimeMultipart("related");

    container.setSubType("alternative");

    BodyPart msgText = null;
    BodyPart msgHtml = null;

    if (!StringUtil.isEmpty(this.text)) {
        msgText = this.getPrimaryBodyPart();
        if (!StringUtil.isEmpty(this.charset)) {
            msgText.setContent(this.text, Email.TEXT_PLAIN + "; charset=" + this.charset);
        } else {
            msgText.setContent(this.text, Email.TEXT_PLAIN);
        }
    }

    if (!StringUtil.isEmpty(this.html)) {
        // if the txt part of the message was null, then the html part
        // will become the primary body part
        if (msgText == null) {
            msgHtml = getPrimaryBodyPart();
        } else {
            if (this.inlineImages.size() > 0) {
                msgHtml = new MimeBodyPart();
                subContainerHTML.addBodyPart(msgHtml);
            } else {
                msgHtml = new MimeBodyPart();
                container.addBodyPart(msgHtml, 1);
            }
        }

        if (!StringUtil.isEmpty(this.charset)) {
            msgHtml.setContent(this.html, Email.TEXT_HTML + "; charset=" + this.charset);
        } else {
            msgHtml.setContent(this.html, Email.TEXT_HTML);
        }

        Iterator iter = this.inlineImages.iterator();
        while (iter.hasNext()) {
            subContainerHTML.addBodyPart((BodyPart) iter.next());
        }

        if (this.inlineImages.size() > 0) {
            // add sub container to message
            this.addPart(subContainerHTML);
        }
    }
}

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

protected void visitNode(Map cache, Node node, MimeMultipart multipart) throws Exception {

    ModelItem item = (ModelItem) node.getUserData("");
    if (item != null && item.getDeclarationView().getDatatype() != null
            && item.getDeclarationView().getDatatype().equalsIgnoreCase("anyURI")) {
        String name = item.getFilename();
        if (name == null || item.getValue() == null || item.getValue().equals("")) {
            return;
        }//from w ww  .  ja  v a2 s  .  c  o m

        String cid = (String) cache.get(name);
        if (cid == null) {
            int count = multipart.getCount();
            cid = name + "@part" + (count + 1);

            MimeBodyPart part = new MimeBodyPart();
            part.setContentID("<" + cid + ">");

            DataHandler dh = new DataHandler(new ModelItemDataSource(item));
            part.setDataHandler(dh);

            part.addHeader("Content-Type", item.getMediatype());
            part.addHeader("Content-Transfer-Encoding", "base64");
            part.setDisposition("attachment");
            part.setFileName(name);
            multipart.addBodyPart(part);
            cache.put(name, cid);
        }

        Element element = (Element) node;
        // remove text node
        NodeList list = node.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node n = list.item(i);
            if (n.getNodeType() != Node.TEXT_NODE) {
                continue;
            }
            n.setNodeValue("cid:" + cid);
            break;
        }
    } else {
        NodeList list = node.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node n = list.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                visitNode(cache, n, multipart);
            }
        }
    }
}

From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java

/**Builds up a new message from the passed message parts
 * @param messageType one of the message types definfed in the class AS2Message
 *//*  ww  w.  j a  v  a 2 s . c om*/
public AS2Message createMessage(Partner sender, Partner receiver, AS2Payload[] payloads, int messageType,
        String messageId) throws Exception {
    if (messageId == null) {
        messageId = UniqueId.createMessageId(sender.getAS2Identification(), receiver.getAS2Identification());
    }
    BCCryptoHelper cryptoHelper = new BCCryptoHelper();
    AS2MessageInfo info = new AS2MessageInfo();
    info.setMessageType(messageType);
    info.setSenderId(sender.getAS2Identification());
    info.setReceiverId(receiver.getAS2Identification());
    info.setSenderEMail(sender.getEmail());
    info.setMessageId(messageId);
    info.setDirection(AS2MessageInfo.DIRECTION_OUT);
    info.setSignType(receiver.getSignType());
    info.setEncryptionType(receiver.getEncryptionType());
    info.setRequestsSyncMDN(receiver.isSyncMDN());
    if (!receiver.isSyncMDN()) {
        info.setAsyncMDNURL(sender.getMdnURL());
    }
    info.setSubject(receiver.getSubject());
    try {
        info.setSenderHost(InetAddress.getLocalHost().getCanonicalHostName());
    } catch (UnknownHostException e) {
        //nop
    }
    //create message object to return
    AS2Message message = new AS2Message(info);
    //stores all the available body parts that have been prepared
    List<MimeBodyPart> contentPartList = new ArrayList<MimeBodyPart>();
    for (AS2Payload as2Payload : payloads) {
        //add payload
        message.addPayload(as2Payload);
        if (this.runtimeConnection != null) {
            MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection);
            messageAccess.initializeOrUpdateMessage(info);
        }
        //no MIME message: single payload, unsigned, no CEM
        if (info.getSignType() == AS2Message.SIGNATURE_NONE && payloads.length == 1
                && info.getMessageType() != AS2Message.MESSAGETYPE_CEM) {
            return (this.createMessageNoMIME(message, receiver));
        }
        //MIME message
        MimeBodyPart bodyPart = new MimeBodyPart();
        String contentType = null;
        if (as2Payload.getContentType() == null) {
            contentType = receiver.getContentType();
        } else {
            contentType = as2Payload.getContentType();
        }
        bodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(as2Payload.getData(), contentType)));
        bodyPart.addHeader("Content-Type", contentType);
        if (as2Payload.getContentId() != null) {
            bodyPart.addHeader("Content-ID", as2Payload.getContentId());
        }
        if (receiver.getContentTransferEncoding() == AS2Message.CONTENT_TRANSFER_ENCODING_BASE64) {
            bodyPart.addHeader("Content-Transfer-Encoding", "base64");
        } else {
            bodyPart.addHeader("Content-Transfer-Encoding", "binary");
        }
        //prepare filename to not violate the MIME header rules
        if (as2Payload.getOriginalFilename() == null) {
            as2Payload.setOriginalFilename(new File(as2Payload.getPayloadFilename()).getName());
        }
        String newFilename = as2Payload.getOriginalFilename().replace(' ', '_');
        newFilename = newFilename.replace('@', '_');
        newFilename = newFilename.replace(':', '_');
        newFilename = newFilename.replace(';', '_');
        newFilename = newFilename.replace('(', '_');
        newFilename = newFilename.replace(')', '_');
        bodyPart.addHeader("Content-Disposition", "attachment; filename=" + newFilename);
        contentPartList.add(bodyPart);
    }
    Part contentPart = null;
    //sigle attachment? No CEM? Every CEM is in a multipart/related container
    if (contentPartList.size() == 1 && info.getMessageType() != AS2Message.MESSAGETYPE_CEM) {
        contentPart = contentPartList.get(0);
    } else {
        //build up a new MimeMultipart container for the multiple attachments, content-type
        //is "multipart/related"
        MimeMultipart multipart = null;
        //CEM messages are always in a multipart container (even the response which contains only a single
        //payload) with the subtype "application/ediint-cert-exchange+xml".
        if (info.getMessageType() == AS2Message.MESSAGETYPE_CEM) {
            multipart = new MimeMultipart("related; type=\"application/ediint-cert-exchange+xml\"");
        } else {
            multipart = new MimeMultipart("related");
        }
        for (MimeBodyPart bodyPart : contentPartList) {
            multipart.addBodyPart(bodyPart);
        }
        contentPart = new MimeMessage(Session.getInstance(System.getProperties(), null));
        contentPart.setContent(multipart, multipart.getContentType());
        ((MimeMessage) contentPart).saveChanges();
    }
    //should the content be compressed and enwrapped or just enwrapped?
    if (receiver.getCompressionType() == AS2Message.COMPRESSION_ZLIB) {
        info.setCompressionType(AS2Message.COMPRESSION_ZLIB);
        int uncompressedSize = contentPart.getSize();
        contentPart = this.compressPayload(receiver, contentPart);
        int compressedSize = contentPart.getSize();
        //sometimes size() is unable to determine the size of the compressed body part and will return -1. Dont log the
        //compression ratio in this case.
        if (uncompressedSize == -1 || compressedSize == -1) {
            if (this.logger != null) {
                this.logger.log(Level.INFO, this.rb.getResourceString("message.compressed.unknownratio",
                        new Object[] { info.getMessageId() }), info);
            }
        } else {
            if (this.logger != null) {
                this.logger.log(Level.INFO,
                        this.rb.getResourceString("message.compressed",
                                new Object[] { info.getMessageId(),
                                        AS2Tools.getDataSizeDisplay(uncompressedSize),
                                        AS2Tools.getDataSizeDisplay(compressedSize) }),
                        info);
            }
        }
    }
    //compute content mic. Try to use sign digest as hash alg. For unsigned messages take sha-1
    String digestOID = null;
    if (info.getSignType() == AS2Message.SIGNATURE_MD5) {
        digestOID = cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_MD5);
    } else {
        digestOID = cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_SHA1);
    }
    String mic = cryptoHelper.calculateMIC(contentPart, digestOID);
    if (info.getSignType() == AS2Message.SIGNATURE_MD5) {
        info.setReceivedContentMIC(mic + ", md5");
    } else {
        info.setReceivedContentMIC(mic + ", sha1");
    }
    this.enwrappInMessageAndSign(message, contentPart, sender, receiver);
    //encryption requested for the receiver?
    if (info.getEncryptionType() != AS2Message.ENCRYPTION_NONE) {
        String cryptAlias = this.encryptionCertManager
                .getAliasByFingerprint(receiver.getCryptFingerprintSHA1());
        this.encryptDataToMessage(message, cryptAlias, info.getEncryptionType(), receiver);
    } else {
        message.setRawData(message.getDecryptedRawData());
        if (this.logger != null) {
            this.logger.log(Level.INFO,
                    this.rb.getResourceString("message.notencrypted", new Object[] { info.getMessageId() }),
                    info);
        }
    }
    return (message);
}

From source file:com.boundlessgeo.geoserver.AppIntegrationTest.java

void createMultiPartFormContent(MockHttpServletRequest request, String contentDisposition, String contentType,
        byte[] content) throws Exception {
    MimeMultipart body = new MimeMultipart();
    request.setContentType(body.getContentType());
    InternetHeaders headers = new InternetHeaders();
    headers.setHeader("Content-Disposition", contentDisposition);
    headers.setHeader("Content-Type", contentType);
    body.addBodyPart(new MimeBodyPart(headers, content));

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    body.writeTo(bout);/*  www . j  ava2  s.c om*/
    request.setContent(bout.toByteArray());
}

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

public static boolean prepareRequestPart(WsdlRequest wsdlRequest, MimeMultipart mp, RequestXmlPart requestPart,
        StringToStringMap contentIds) throws Exception, MessagingException {
    boolean isXop = false;

    XmlCursor cursor = requestPart.newCursor();

    try {/*w ww.ja  v a 2 s.  co m*/
        while (!cursor.isEnddoc()) {
            if (cursor.isContainer()) {
                // could be an attachment part (as of "old" SwA specs which specify a content 
                // element referring to the attachment)
                if (requestPart.isAttachmentPart()) {
                    String href = cursor.getAttributeText(new QName("href"));
                    if (href != null && href.length() > 0) {
                        contentIds.put(requestPart.getPart().getName(), href);
                    }

                    break;
                }

                SchemaType schemaType = cursor.getObject().schemaType();
                if (isBinaryType(schemaType)) {
                    String contentType = getXmlMimeContentType(cursor);

                    // extract contentId
                    String textContent = cursor.getTextValue();
                    Attachment attachment = null;
                    boolean isXopAttachment = false;

                    // is content a reference to a file?
                    if (textContent.startsWith("file:")) {
                        String filename = textContent.substring(5);
                        if (contentType == null) {
                            inlineData(cursor, schemaType, new FileInputStream(filename));
                        } else if (wsdlRequest.isMtomEnabled()) {
                            MimeBodyPart part = new PreencodedMimeBodyPart("binary");

                            part.setDataHandler(new DataHandler(
                                    new XOPPartDataSource(new File(filename), contentType, schemaType)));
                            part.setContentID("<" + filename + ">");
                            mp.addBodyPart(part);

                            isXopAttachment = true;
                        }
                    }
                    // is content a reference to an attachment?
                    else if (textContent.startsWith("cid:")) {
                        textContent = textContent.substring(4);
                        Attachment[] attachments = wsdlRequest.getAttachmentsForPart(textContent);
                        if (attachments.length == 1) {
                            attachment = attachments[0];
                        } else if (attachments.length > 1) {
                            attachment = buildMulitpartAttachment(attachments);
                        }

                        isXopAttachment = contentType != null;
                        contentIds.put(textContent, textContent);
                    }
                    // content should be binary data; is this an XOP element which should be serialized with MTOM?
                    else if (wsdlRequest.isMtomEnabled() && contentType != null) {
                        MimeBodyPart part = new PreencodedMimeBodyPart("binary");

                        part.setDataHandler(
                                new DataHandler(new XOPPartDataSource(textContent, contentType, schemaType)));

                        textContent = "http://www.soapui.org/" + System.nanoTime();

                        part.setContentID("<" + textContent + ">");
                        mp.addBodyPart(part);

                        isXopAttachment = true;
                    }

                    // add XOP include?
                    if (isXopAttachment && wsdlRequest.isMtomEnabled()) {
                        buildXopInclude(cursor, textContent);
                        isXop = true;
                    }
                    // inline?
                    else if (attachment != null) {
                        inlineAttachment(cursor, schemaType, attachment);
                    }
                }
            }

            cursor.toNextToken();
        }
    } finally {
        cursor.dispose();
    }

    return isXop;
}

From source file:com.boundlessgeo.geoserver.AppIntegrationTest.java

MimeMultipart appendMultiPartFormContent(MimeMultipart body, String contentDisposition, String contentType,
        byte[] content) throws Exception {
    InternetHeaders headers = new InternetHeaders();
    headers.setHeader("Content-Disposition", contentDisposition);
    headers.setHeader("Content-Type", contentType);
    body.addBodyPart(new MimeBodyPart(headers, content));

    return body;/*w w w .  j a  va 2  s . c  o  m*/
}

From source file:com.nokia.helium.core.EmailDataSender.java

/**
 * Send xml data//from  w w w.ja  v a  2  s .  co m
 * 
 * @param String purpose of this email
 * @param String file to send
 * @param String mime type
 * @param String subject of email
 * @param String header of mail
 * @param boolean compress data if true
 */
public void sendData(String purpose, File fileToSend, String mimeType, String subject, String header,
        boolean compressData) throws EmailSendException {
    try {
        log.debug("sendData:Send file: " + fileToSend + " and mimetype: " + mimeType);
        if (fileToSend != null && fileToSend.exists()) {
            InternetAddress[] toAddresses = getToAddressList();
            Properties props = new Properties();
            if (smtpServerAddress != null) {
                log.debug("sendData:smtp address: " + smtpServerAddress);
                props.setProperty("mail.smtp.host", smtpServerAddress);
            }
            Session mailSession = Session.getDefaultInstance(props, null);
            MimeMessage message = new MimeMessage(mailSession);
            message.setSubject(subject == null ? "" : subject);
            MimeMultipart multipart = new MimeMultipart("related");
            BodyPart messageBodyPart = new MimeBodyPart();
            ByteArrayDataSource dataSrc = null;
            String fileName = fileToSend.getName();
            if (compressData) {
                log.debug("Sending compressed data");
                dataSrc = compressFile(fileToSend);
                dataSrc.setName(fileName + ".gz");
                messageBodyPart.setFileName(fileName + ".gz");
            } else {
                log.debug("Sending uncompressed data:");
                dataSrc = new ByteArrayDataSource(new FileInputStream(fileToSend), mimeType);

                message.setContent(FileUtils.readFileToString(fileToSend), "text/html");
                multipart = null;
            }
            String headerToSend = null;
            if (header == null) {
                headerToSend = "";
            }
            messageBodyPart.setHeader("helium-bld-data", headerToSend);
            messageBodyPart.setDataHandler(new DataHandler(dataSrc));

            if (multipart != null) {
                multipart.addBodyPart(messageBodyPart); // add to the
                // multipart
                message.setContent(multipart);
            }
            try {
                message.setFrom(getFromAddress());
            } catch (AddressException e) {
                throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e);
            } catch (LDAPException e) {
                throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e);
            }
            message.addRecipients(Message.RecipientType.TO, toAddresses);
            log.info("Sending email alert: " + subject);
            Transport.send(message);
        }
    } catch (MessagingException e) {
        String fullErrorMessage = "Failed sending e-mail: " + purpose;
        if (e.getMessage() != null) {
            fullErrorMessage += ": " + e.getMessage();
        }
        throw new EmailSendException(fullErrorMessage, e);
    } catch (IOException e) {
        String fullErrorMessage = "Failed sending e-mail: " + purpose;
        if (e.getMessage() != null) {
            fullErrorMessage += ": " + e.getMessage();
        }
        // We are Ignoring the errors as no need to fail the build.
        throw new EmailSendException(fullErrorMessage, e);
    }
}