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.googlecode.psiprobe.tools.Mailer.java

private static MimeBodyPart createAttachmentPart(DataSource attachment) throws MessagingException {
    MimeBodyPart attachmentPart = new MimeBodyPart();
    attachmentPart.setDataHandler(new DataHandler(attachment));
    attachmentPart.setDisposition(MimeBodyPart.ATTACHMENT);
    attachmentPart.setFileName(attachment.getName());
    return attachmentPart;
}

From source file:mitm.common.mail.BodyPartUtils.java

/**
 * Creates a MimeBodyPart with the provided message attached as a RFC822 attachment. 
 *///  ww w.  j a v  a 2s.  c o  m
public static MimeBodyPart toRFC822(MimeMessage message, String filename) throws MessagingException {
    MimeBodyPart bodyPart = new MimeBodyPart();

    bodyPart.setContent(message, "message/rfc822");
    /* somehow the content-Type header is not set so we need to set it ourselves */
    bodyPart.setHeader("Content-Type", "message/rfc822");
    bodyPart.setDisposition(Part.INLINE);
    bodyPart.setFileName(filename);

    return bodyPart;
}

From source file:com.threewks.thundr.mail.JavaMailMailer.java

private void addAttachments(Multipart multipart, List<Attachment> attachments) throws MessagingException {
    for (Attachment attachment : attachments) {
        BasicViewRenderer response = render(attachment.view());
        byte[] base64Encoded = Base64.encodeToByte(response.getOutputAsBytes());

        InternetHeaders headers = new InternetHeaders();
        headers.addHeader(Header.ContentType, response.getContentType());
        headers.addHeader(Header.ContentTransferEncoding, "base64");

        MimeBodyPart part = new MimeBodyPart(headers, base64Encoded);
        part.setFileName(attachment.name());
        part.setDisposition(attachment.disposition().value());

        if (attachment.isInline()) {
            part.setContentID(attachment.contentId());
        }//from w  ww . j a  v a2  s  . c o m

        multipart.addBodyPart(part);
    }
}

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 {//w w  w  .j a  v a  2s. c  o m
        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:de.elomagic.mag.AbstractTest.java

protected MimeMessage createMimeMessage(String filename) throws Exception {

    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setContent("This is some text to be displayed inline", "text/plain");
    textPart.setDisposition(Part.INLINE);

    MimeBodyPart binaryPart = new MimeBodyPart();
    InputStream in = getClass().getResourceAsStream("/TestFile.pdf");
    binaryPart.setContent(getOriginalMailAttachment(), "application/pdf");
    binaryPart.setDisposition(Part.ATTACHMENT);
    binaryPart.setFileName(filename);/* www .  j ava2 s.co m*/

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(textPart);
    mp.addBodyPart(binaryPart);

    MimeMessage message = new MimeMessage(greenMail.getImap().createSession());
    message.setRecipients(Message.RecipientType.TO,
            new InternetAddress[] { new InternetAddress("mailuser@localhost.com") });
    message.setSubject("Another test mail subject");
    message.setContent(mp);

    //
    return message; // GreenMailUtil.createTextEmail("to@localhost.com", "from@localhost.com", "subject", "body", greenMail.getImap().getServerSetup());
}

From source file:com.ikon.util.MailUtils.java

/**
 * Create a mail from a Mail object/*w ww.  ja  v  a 2 s.c o  m*/
 */
public static MimeMessage create(String token, Mail mail) throws MessagingException, PathNotFoundException,
        AccessDeniedException, RepositoryException, IOException, DatabaseException {
    log.debug("create({})", mail);
    Session mailSession = getMailSession();
    MimeMessage msg = new MimeMessage(mailSession);

    if (mail.getFrom() != null) {
        InternetAddress from = new InternetAddress(mail.getFrom());
        msg.setFrom(from);
    } else {
        msg.setFrom();
    }

    InternetAddress[] to = new InternetAddress[mail.getTo().length];
    int i = 0;

    for (String strTo : mail.getTo()) {
        to[i++] = new InternetAddress(strTo);
    }

    // Build a multiparted mail with HTML and text content for better SPAM behaviour
    MimeMultipart content = new MimeMultipart();

    if (Mail.MIME_TEXT.equals(mail.getMimeType())) {
        // Text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(mail.getContent());
        textPart.setHeader("Content-Type", "text/plain");
        textPart.setDisposition(Part.INLINE);
        content.addBodyPart(textPart);
    } else if (Mail.MIME_HTML.equals(mail.getMimeType())) {
        // HTML Part
        MimeBodyPart htmlPart = new MimeBodyPart();
        StringBuilder htmlContent = new StringBuilder();
        htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
        htmlContent.append("<html>\n<head>\n");
        htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n");
        htmlContent.append("</head>\n<body>\n");
        htmlContent.append(mail.getContent());
        htmlContent.append("\n</body>\n</html>");
        htmlPart.setContent(htmlContent.toString(), "text/html");
        htmlPart.setHeader("Content-Type", "text/html");
        htmlPart.setDisposition(Part.INLINE);
        content.addBodyPart(htmlPart);
    } else {
        log.warn("Email does not specify content MIME type");

        // Text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(mail.getContent());
        textPart.setHeader("Content-Type", "text/plain");
        textPart.setDisposition(Part.INLINE);
        content.addBodyPart(textPart);
    }

    for (Document doc : mail.getAttachments()) {
        InputStream is = null;
        FileOutputStream fos = null;
        String docName = PathUtils.getName(doc.getPath());

        try {
            is = OKMDocument.getInstance().getContent(token, doc.getPath(), false);
            File tmp = File.createTempFile("okm", ".tmp");
            fos = new FileOutputStream(tmp);
            IOUtils.copy(is, fos);
            fos.flush();

            // Document attachment part
            MimeBodyPart docPart = new MimeBodyPart();
            DataSource source = new FileDataSource(tmp.getPath());
            docPart.setDataHandler(new DataHandler(source));
            docPart.setFileName(docName);
            docPart.setDisposition(Part.ATTACHMENT);
            content.addBodyPart(docPart);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(fos);
        }
    }

    msg.setHeader("MIME-Version", "1.0");
    msg.setHeader("Content-Type", content.getContentType());
    msg.addHeader("Charset", "UTF-8");
    msg.setRecipients(Message.RecipientType.TO, to);
    msg.setSubject(mail.getSubject(), "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content);
    msg.saveChanges();

    log.debug("create: {}", msg);
    return msg;
}

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

@Test
public void testCheckNewMessages() throws MessagingException, IOException {
    org.jvnet.mock_javamail.Mailbox.clearAll();
    MessageChecker messageChecker = getMessageChecker();
    messageChecker.removeListener("componentId");
    messageChecker.removeListener("thesimpsons@silverpeas.com");
    messageChecker.removeListener("theflanders@silverpeas.com");
    StubMessageListener mockListener1 = new StubMessageListener("thesimpsons@silverpeas.com");
    StubMessageListener mockListener2 = new StubMessageListener("theflanders@silverpeas.com");
    messageChecker.addMessageListener(mockListener1);
    messageChecker.addMessageListener(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(
            TestMessageCheckerWithStubs.class.getResourceAsStream("lemonde.html"));
    attachment.setDisposition(Part.INLINE);
    attachment.setFileName("lemonde.html");
    MimeBodyPart body = new MimeBodyPart();
    body.setText(textEmailContent);/* w w  w .  j a va 2 s .  c om*/
    Multipart multiPart = new MimeMultipart();
    multiPart.addBodyPart(body);
    multiPart.addBodyPart(attachment);
    mail.setContent(multiPart);
    mail.setSentDate(new Date());
    Date sentDate1 = new Date(mail.getSentDate().getTime());
    Transport.send(mail);

    mail = new MimeMessage(messageChecker.getMailSession());
    bart = new InternetAddress("bart.simpson@silverpeas.com");
    theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Plain text Email test");
    mail.setText(textEmailContent);
    mail.setSentDate(new Date());
    Date sentDate2 = new Date(mail.getSentDate().getTime());
    Transport.send(mail);

    //Unauthorized email
    mail = new MimeMessage(messageChecker.getMailSession());
    bart = new InternetAddress("marge.simpson@silverpeas.com");
    theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Plain text Email test");
    mail.setText(textEmailContent);
    mail.setSentDate(new Date());
    Transport.send(mail);

    assertThat(org.jvnet.mock_javamail.Mailbox.get("thesimpsons@silverpeas.com").size(), is(3));

    messageChecker.checkNewMessages(new Date());
    assertThat(mockListener2.getMessageEvent(), is(nullValue()));
    MessageEvent event = mockListener1.getMessageEvent();
    assertThat(event, is(notNullValue()));
    assertThat(event.getMessages(), is(notNullValue()));
    assertThat(event.getMessages(), hasSize(2));
    Message message = event.getMessages().get(0);
    assertThat(message.getSender(), is("bart.simpson@silverpeas.com"));
    assertThat(message.getTitle(), is("Plain text Email test with attachment"));
    assertThat(message.getBody(), is(textEmailContent));
    assertThat(message.getSummary(), is(textEmailContent.substring(0, 200)));
    assertThat(message.getSentDate().getTime(), is(sentDate1.getTime()));
    assertThat(message.getAttachmentsSize(), greaterThan(0L));
    assertThat(message.getAttachments(), hasSize(1));
    String path = MessageFormat.format(theSimpsonsAttachmentPath,
            new Object[] { messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId()) });
    Attachment attached = message.getAttachments().iterator().next();
    assertThat(attached.getPath(), is(path));
    assertThat(message.getComponentId(), is("thesimpsons@silverpeas.com"));

    message = event.getMessages().get(1);
    assertThat(message.getSender(), is("bart.simpson@silverpeas.com"));
    assertThat(message.getTitle(), is("Plain text Email test"));
    assertThat(message.getBody(), is(textEmailContent));
    assertThat(message.getSummary(), is(textEmailContent.substring(0, 200)));
    assertThat(message.getAttachmentsSize(), is(0L));
    assertThat(message.getAttachments(), hasSize(0));
    assertThat(message.getComponentId(), is("thesimpsons@silverpeas.com"));
    assertThat(message.getSentDate().getTime(), is(sentDate2.getTime()));
}

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

public MimeBodyPart newSentToBodyPart(MimeMessage message) throws MessagingException {
    // get information about the original message.
    Address[] originalFromRecipient = message.getFrom();
    Address[] originalToRecipient = message.getRecipients(Message.RecipientType.TO);
    Address[] originalCcRecipient = message.getRecipients(Message.RecipientType.CC);
    Address[] originalBccRecipient = message.getRecipients(Message.RecipientType.BCC);
    String originalSubject = message.getSubject();

    // create the html for the string buffer.
    StringBuffer html = new StringBuffer();
    html.append("<html><body><table style=\"width: 100%;\"><tr><td>header</td><td>value</td></tr>");
    html.append("<tr><td>Subject:</td><td>").append(escape(originalSubject)).append("</td></tr>");

    // iterate over the addresses.
    if (originalFromRecipient != null) {
        for (int i = 0; i < originalFromRecipient.length; i++) {
            html.append("<tr><td>FROM:</td><td>").append(escape(originalFromRecipient[i])).append("</td></tr>");
        }/*from  w  ww  . ja v a  2  s.c  o  m*/
    }
    if (originalToRecipient != null) {
        for (int i = 0; i < originalToRecipient.length; i++) {
            html.append("<tr><td>TO:</td><td>").append(escape(originalToRecipient[i])).append("</td></tr>");
        }
    }
    if (originalCcRecipient != null) {
        for (int i = 0; i < originalCcRecipient.length; i++) {
            html.append("<tr><td>CC:</td><td>").append(escape(originalCcRecipient[i])).append("</td></tr>");
        }
    }
    if (originalBccRecipient != null) {
        for (int i = 0; i < originalBccRecipient.length; i++) {
            html.append("<tr><td>BCC:</td><td>").append(escape(originalBccRecipient[i])).append("</td></tr>");
        }
    }
    html.append("</table></body></html>");

    MimeBodyPart sentToBodyPart = new MimeBodyPart();
    sentToBodyPart.setContent(html.toString(), "text/html");
    sentToBodyPart.setHeader("Content-ID", "original-addresses");
    sentToBodyPart.setDisposition("inline");

    return sentToBodyPart;
}

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

public MimeBodyPart addReportAttachment() throws MessagingException {
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    String mimeType = "application/vnd.ms-excel";
    if (fileName.endsWith(".xlsx")) {
        mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    }/*from  w  w  w  . j a v  a  2  s .  c  o m*/
    mimeBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(reportContent, mimeType)));
    mimeBodyPart.setDisposition("attachment");
    mimeBodyPart.setFileName(fileName);

    return mimeBodyPart;
}

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

/**
 * Embeds an URL in the HTML.//from w  w w.ja  v  a  2 s  .  c  o  m
 *
 * <p>This method allows to embed a file located by an URL into
 * the mail body.  It allows, for instance, to add inline images
 * to the email.  Inline files may be referenced with a
 * <code>cid:xxxxxx</code> URL, where xxxxxx is the Content-ID
 * returned by the embed function.
 *
 * <p>Example of use:<br><code><pre>
 * HtmlEmail he = new HtmlEmail();
 * he.setHtmlMsg("&lt;html&gt;&lt;img src=cid:" +
 *  embed("file:/my/image.gif","image.gif") +
 *  "&gt;&lt;/html&gt;");
 * // code to set the others email fields (not shown)
 * </pre></code>
 *
 * @param url The URL of the file.
 * @param cid A String with the Content-ID of the file.
 * @param name The name that will be set in the filename header
 * field.
 * @throws EmailException when URL supplied is invalid
 *  also see javax.mail.internet.MimeBodyPart for definitions
 *
 */
public void embed(URL url, String cid, String name) throws EmailException {
    // verify that the URL is valid
    try {
        InputStream is = url.openStream();
        is.close();
    } catch (IOException e) {
        throw new EmailException("Invalid URL");
    }

    MimeBodyPart mbp = new MimeBodyPart();

    try {
        mbp.setDataHandler(new DataHandler(new URLDataSource(url)));
        mbp.setFileName(name);
        mbp.setDisposition("inline");
        mbp.addHeader("Content-ID", "<" + cid + ">");
        this.inlineImages.add(mbp);
    } catch (MessagingException me) {
        throw new EmailException(me);
    }
}