Example usage for javax.mail.internet MimeBodyPart setDisposition

List of usage examples for javax.mail.internet MimeBodyPart setDisposition

Introduction

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

Prototype

@Override
public void setDisposition(String disposition) throws MessagingException 

Source Link

Document

Set the disposition in the "Content-Disposition" header field of this body part.

Usage

From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java

@Test
public void testProcessEmailHtmlTextWithAttachment() throws MessagingException, IOException {
    MessageListener mockListener1 = mock(MessageListener.class);
    when(mockListener1.getComponentId()).thenReturn("componentId");
    when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE);
    MessageListener mockListener2 = mock(MessageListener.class);
    messageChecker.addMessageListener(mockListener1);
    messageChecker.addMessageListener(mockListener2);
    Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2);
    listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1);
    listenersByEmail.put("theflanders@silverpeas.com", mockListener2);
    MimeMessage mail = new MimeMessage(messageChecker.getMailSession());
    InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com");
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Html Email test with attachment");
    String html = loadHtml();/*from  w w w. j a va2 s  .co m*/
    MimeBodyPart attachment = new MimeBodyPart(TestMessageChecker.class.getResourceAsStream("lemonde.html"));
    attachment.setDisposition(Part.ATTACHMENT);
    attachment.setFileName("lemonde.html");
    MimeBodyPart body = new MimeBodyPart();
    body.setContent(html, "text/html; charset=\"UTF-8\"");
    Multipart multiPart = new MimeMultipart();
    multiPart.addBodyPart(body);
    multiPart.addBodyPart(attachment);
    mail.setContent(multiPart);
    Transport.send(mail);
    Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>();
    messageChecker.processEmail(mail, events, listenersByEmail);
    assertNotNull(events);
    assertEquals(1, events.size());
    assertNull(events.get(mockListener2));

    MessageEvent event = events.get(mockListener1);
    assertNotNull(event);
    assertNotNull(event.getMessages());
    assertEquals(1, event.getMessages().size());
    Message message = event.getMessages().get(0);
    assertEquals("bart.simpson@silverpeas.com", message.getSender());
    assertEquals("Html Email test with attachment", message.getTitle());
    assertEquals(html, message.getBody());
    assertEquals(htmlEmailSummary, message.getSummary());
    assertEquals(ATT_SIZE, message.getAttachmentsSize());
    assertEquals(1, message.getAttachments().size());
    String path = MessageFormat.format(attachmentPath,
            messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId()));
    Attachment attached = message.getAttachments().iterator().next();
    assertEquals(path, attached.getPath());
    assertEquals("lemonde.html", attached.getFileName());
    assertEquals("componentId", message.getComponentId());
    assertEquals("text/html", message.getContentType());
    verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com");
}

From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java

@Test
public void testProcessEmailTextWithAttachment() throws MessagingException, IOException {
    MessageListener mockListener1 = mock(MessageListener.class);
    when(mockListener1.getComponentId()).thenReturn("componentId");
    when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE);
    MessageListener mockListener2 = mock(MessageListener.class);
    messageChecker.addMessageListener(mockListener1);
    messageChecker.addMessageListener(mockListener2);
    Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2);
    listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1);
    listenersByEmail.put("theflanders@silverpeas.com", mockListener2);
    MimeMessage mail = new MimeMessage(messageChecker.getMailSession());
    InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com");
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Plain text Email test with attachment");
    MimeBodyPart attachment = new MimeBodyPart(TestMessageChecker.class.getResourceAsStream("lemonde.html"));
    attachment.setDisposition(Part.INLINE);
    attachment.setFileName("lemonde.html");
    MimeBodyPart body = new MimeBodyPart();
    body.setText(textEmailContent);//w  w  w .  j a  v a2s .c om
    Multipart multiPart = new MimeMultipart();
    multiPart.addBodyPart(body);
    multiPart.addBodyPart(attachment);
    mail.setContent(multiPart);
    mail.setSentDate(new Date());
    Date sentDate = new Date(mail.getSentDate().getTime());
    Transport.send(mail);
    Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>();
    messageChecker.processEmail(mail, events, listenersByEmail);
    assertNotNull(events);
    assertEquals(1, events.size());
    assertNull(events.get(mockListener2));

    MessageEvent event = events.get(mockListener1);
    assertNotNull(event);
    assertNotNull(event.getMessages());
    assertEquals(1, event.getMessages().size());
    Message message = event.getMessages().get(0);
    assertEquals("bart.simpson@silverpeas.com", message.getSender());
    assertEquals("Plain text Email test with attachment", message.getTitle());
    assertEquals(textEmailContent, message.getBody());
    assertEquals(textEmailContent.substring(0, 200), message.getSummary());
    assertEquals(ATT_SIZE, message.getAttachmentsSize());
    assertEquals(1, message.getAttachments().size());
    String path = MessageFormat.format(attachmentPath,
            messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId()));
    Attachment attached = message.getAttachments().iterator().next();
    assertEquals(path, attached.getPath());
    assertEquals("lemonde.html", attached.getFileName());
    assertEquals("componentId", message.getComponentId());
    assertEquals(sentDate.getTime(), message.getSentDate().getTime());
    assertEquals("text/plain", message.getContentType());
    org.jvnet.mock_javamail.Mailbox.clearAll();
    verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com");
    verify(mockListener1, times(2)).getComponentId();
}

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

protected MimeBodyPart createAttachmentPart(SendingAttachment attachment) throws MessagingException {
    DataSource source = new MyByteArrayDataSource(attachment.getContent());

    String mimeType = FileTypesHelper.getMIMEType(attachment.getName());
    String encodedFileName = encodeAttachmentName(attachment);

    String contentId = attachment.getContentId();
    if (contentId == null) {
        contentId = encodedFileName;/*from www.j  av a 2  s  .  c om*/
    }

    String disposition = attachment.getDisposition() != null ? attachment.getDisposition() : Part.INLINE;
    String charset = MimeUtility.mimeCharset(
            attachment.getEncoding() != null ? attachment.getEncoding() : StandardCharsets.UTF_8.name());
    String contentTypeValue = String.format("%s; charset=%s; name=\"%s\"", mimeType, charset, encodedFileName);

    MimeBodyPart attachmentPart = new MimeBodyPart();
    attachmentPart.setDataHandler(new DataHandler(source));
    attachmentPart.setHeader("Content-ID", "<" + contentId + ">");
    attachmentPart.setHeader("Content-Type", contentTypeValue);
    attachmentPart.setFileName(encodedFileName);
    attachmentPart.setDisposition(disposition);

    return attachmentPart;
}

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 w w. j a  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:com.eviware.soapui.impl.wsdl.submit.filters.HttpRequestFilter.java

private void addFormMultipart(HttpRequestInterface<?> request, MimeMultipart formMp, String name, String value)
        throws MessagingException {
    MimeBodyPart part = new MimeBodyPart();

    if (value.startsWith("file:")) {
        String fileName = value.substring(5);
        File file = new File(fileName);
        part.setDisposition("form-data; name=\"" + name + "\"; filename=\"" + file.getName() + "\"");
        if (file.exists()) {
            part.setDataHandler(new DataHandler(new FileDataSource(file)));
        } else {//  w w  w. ja  va  2s  .com
            for (Attachment attachment : request.getAttachments()) {
                if (attachment.getName().equals(fileName)) {
                    part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment)));
                    break;
                }
            }
        }

        part.setHeader("Content-Type", ContentTypeHandler.getContentTypeFromFilename(file.getName()));
        part.setHeader("Content-Transfer-Encoding", "binary");
    } else {
        part.setDisposition("form-data; name=\"" + name + "\"");
        part.setText(value, System.getProperty("soapui.request.encoding", request.getEncoding()));
    }

    if (part != null) {
        formMp.addBodyPart(part);
    }
}

From source file:eagle.common.email.EagleMailClient.java

public boolean send(String from, String to, String cc, String title, String templatePath,
        VelocityContext context, Map<String, File> attachments) {
    if (attachments == null || attachments.isEmpty()) {
        return send(from, to, cc, title, templatePath, context);
    }//  w  ww .j a  va 2s  .co m
    Template t = null;

    List<MimeBodyPart> mimeBodyParts = new ArrayList<MimeBodyPart>();
    Map<String, String> cid = new HashMap<String, String>();

    for (Map.Entry<String, File> entry : attachments.entrySet()) {
        final String attachment = entry.getKey();
        final File attachmentFile = entry.getValue();
        final MimeBodyPart mimeBodyPart = new MimeBodyPart();
        if (attachmentFile != null && attachmentFile.exists()) {
            DataSource source = new FileDataSource(attachmentFile);
            try {
                mimeBodyPart.setDataHandler(new DataHandler(source));
                mimeBodyPart.setFileName(attachment);
                mimeBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
                mimeBodyPart.setContentID(attachment);
                cid.put(attachment, mimeBodyPart.getContentID());
                mimeBodyParts.add(mimeBodyPart);
            } catch (MessagingException e) {
                LOG.error("Generate mail failed, got exception while attaching files: " + e.getMessage(), e);
            }
        } else {
            LOG.error("Attachment: " + attachment + " is null or not exists");
        }
    }
    //TODO remove cid, because not used at all
    if (LOG.isDebugEnabled())
        LOG.debug("Cid maps: " + cid);
    context.put("cid", cid);

    try {
        t = velocityEngine.getTemplate(BASE_PATH + templatePath);
    } catch (ResourceNotFoundException ex) {
        //         LOGGER.error("Template not found:"+BASE_PATH + templatePath, ex);
    }

    if (t == null) {
        try {
            t = velocityEngine.getTemplate(templatePath);
        } catch (ResourceNotFoundException e) {
            try {
                t = velocityEngine.getTemplate("/" + templatePath);
            } catch (Exception ex) {
                LOG.error("Template not found:" + "/" + templatePath, ex);
            }
        }
    }

    final StringWriter writer = new StringWriter();
    t.merge(context, writer);
    if (LOG.isDebugEnabled())
        LOG.debug(writer.toString());
    return this._send(from, to, cc, title, writer.toString(), mimeBodyParts);
}

From source file:com.smartitengineering.emailq.service.impl.EmailServiceImpl.java

private void addAttachment(Multipart multipart, Attachments attachment) throws MessagingException {
    MimeBodyPart attachmentPart = new MimeBodyPart();
    attachmentPart.setFileName(attachment.getName());
    if (StringUtils.isNotBlank(attachment.getDescription())) {
        attachmentPart.setDescription(attachment.getDescription());
    }//from   w ww. jav  a  2  s.c o  m
    if (StringUtils.isNotBlank(attachment.getDisposition())) {
        attachmentPart.setDisposition(attachment.getDisposition());
    }
    DataSource source = new ByteArrayDataSource(attachment.getBlob(), attachment.getContentType());
    attachmentPart.setDataHandler(new DataHandler(source));
    multipart.addBodyPart(attachmentPart);
}

From source file:com.threewks.thundr.gmail.GmailMailer.java

protected void populateMimeBodyPart(MimeBodyPart mimeBodyPart, Attachment attachment, byte[] data,
        String attachmentContentType, String attachmentCharacterEncoding) throws MessagingException {
    String fullContentType = attachmentContentType + "; charset=" + attachmentCharacterEncoding;
    mimeBodyPart.setFileName(attachment.name());
    mimeBodyPart.setContent(data, fullContentType);
    mimeBodyPart.setDisposition(attachment.disposition().toString());
    if (attachment.isInline()) {
        mimeBodyPart.setContentID("<" + attachment.name() + ">");
    }//from   ww w.  j a va  2 s  .  com
}

From source file:Implement.Service.AdminServiceImpl.java

@Override
public boolean sendPackageApprovedEmail(PackageApprovedEmailData emailData) throws MessagingException {
    String path = System.getProperty("catalina.base");
    MimeBodyPart logo = new MimeBodyPart();
    // attach the file to the message
    DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/logoIcon.png"));
    logo.setDataHandler(new DataHandler(source));
    logo.setFileName("logoIcon.png");
    logo.setDisposition(MimeBodyPart.INLINE);
    logo.setHeader("Content-ID", "<logo_Icon>"); // cid:image_cid

    MimeBodyPart facebook = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/facebookIcon.png"));
    facebook.setDataHandler(new DataHandler(source));
    facebook.setFileName("facebookIcon.png");
    facebook.setDisposition(MimeBodyPart.INLINE);
    facebook.setHeader("Content-ID", "<fb_Icon>"); // cid:image_cid

    MimeBodyPart twitter = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/twitterIcon.png"));
    twitter.setDataHandler(new DataHandler(source));
    twitter.setFileName("twitterIcon.png");
    twitter.setDisposition(MimeBodyPart.INLINE);
    twitter.setHeader("Content-ID", "<twitter_Icon>"); // cid:image_cid

    MimeBodyPart insta = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/instaIcon.png"));
    insta.setDataHandler(new DataHandler(source));
    insta.setFileName("instaIcon.png");
    insta.setDisposition(MimeBodyPart.INLINE);
    insta.setHeader("Content-ID", "<insta_Icon>"); // cid:image_cid

    MimeBodyPart youtube = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/youtubeIcon.png"));
    youtube.setDataHandler(new DataHandler(source));
    youtube.setFileName("youtubeIcon.png");
    youtube.setDisposition(MimeBodyPart.INLINE);
    youtube.setHeader("Content-ID", "<yt_Icon>"); // cid:image_cid

    MimeBodyPart pinterest = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/pinterestIcon.png"));
    pinterest.setDataHandler(new DataHandler(source));
    pinterest.setFileName("pinterestIcon.png");
    pinterest.setDisposition(MimeBodyPart.INLINE);
    pinterest.setHeader("Content-ID", "<pin_Icon>"); // cid:image_cid

    String content = "<div style=' width: 507px;background-color: #f2f2f4;'>"
            + "    <div style='padding: 30px 0;text-align: center; color: #fff; background-color: #ff514e;font-size: 30px;font-weight: bold;'>"
            + "        <img style=' text-align:center;' width=57 height=57 src='cid:logo_Icon'/>"
            + "        <p style='margin:25px 0px 0px 0px;'> Package Approved! </p>" + "    </div>"
            + "    <div style=' padding: 50px;margin-bottom: 20px;'>" + "        <div id='email-form'>"
            + "            <div style='margin-bottom: 20px'>" + "                Hi " + emailData.getLastName()
            + " ,<br/>" + "                Your package " + emailData.getLastestPackageName()
            + " has been approved" + "            </div>" + "            <div style='margin-bottom: 20px'>"
            + "                Thanks,<br/>" + "                Youtripper team\n" + "            </div>"
            + "        </div>" + "        <div style='border-top: solid 1px #c4c5cc;text-align:center;'>"
            + "            <p style='text-align: center; color: #3b3e53;margin-top: 10px;margin-bottom: 0px;font-size: 10px;'>Sent from Youtripper.com</p>"
            + "            <div>"
            + "                <a href='https://www.facebook.com/youtrippers/'><img style='margin:10px;' src='cid:fb_Icon' alt=''/></a>"
            + "                <a href='https://twitter.com/youtrippers'><img style='margin:10px;' src='cid:twitter_Icon' alt=''/></a>"
            + "                <a href='https://www.instagram.com/youtrippers/'><img style='margin:10px;' src='cid:insta_Icon' alt=''/></a>"
            + "                <a href='https://www.youtube.com/channel/UCtd4xd_SSjRR9Egug7tXIWA'><img style='margin:10px;' src='cid:yt_Icon' alt=''/></a>"
            + "                <a href='https://www.pinterest.com/youtrippers/'><img style='margin:10px;' src='cid:pin_Icon' alt=''/></a>"
            + "            </div>"
            + "            <p>Youtripper Ltd., 56 Soi Seri Villa, Srinakarin Rd., Nongbon,"
            + "                <br>Pravet, Bangkok, Thailand 10250</p>" + "        </div>" + "    </div>"
            + "</div>";

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "US-ASCII", "html");

    Multipart mp = new MimeMultipart("related");
    mp.addBodyPart(mbp1);/*from w w  w  .j a  v  a 2s  .c o  m*/
    mp.addBodyPart(logo);
    mp.addBodyPart(facebook);
    mp.addBodyPart(twitter);
    mp.addBodyPart(insta);
    mp.addBodyPart(youtube);
    mp.addBodyPart(pinterest);

    final String username = "noreply@youtripper.com";
    final String password = "Tripper190515";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "mail.youtripper.com");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("noreply@youtripper.com"));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailData.getEmail()));
    message.setSubject("Package Approved!");
    message.setContent(mp);
    message.saveChanges();
    Transport.send(message);
    return true;
}

From source file:com.adaptris.mail.MailSenderImp.java

private void addAttachmentsToMessage(MimeMultipart multipart) throws MailException {
    try {/*from www  . ja  v a  2 s.c o  m*/
        for (Attachment a : attachments) {
            MimeBodyPart part = create(a.getBytes(), new InternetHeaders(), a.getEncoding());
            part.setHeader(Mail.CONTENT_TYPE, a.getContentType());
            ContentDisposition cd = new ContentDisposition();
            cd.setDisposition(Mail.DISPOSITION_TYPE_ATTACHMENT);
            if (a.getFilename() != null) {
                cd.setParameter(Mail.DISPOSITION_PARAM_FILENAME, a.getFilename());
            }
            part.setDisposition(cd.toString());
            multipart.addBodyPart(part);
        }
    } catch (Exception e) {
        throw new MailException(e);
    }
}