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:org.apache.james.transport.mailets.StripAttachmentTest.java

@Test
public void testSimpleAttachment3() throws MessagingException, IOException {
    Mailet mailet = initMailet();/*from   w w  w .j  av  a 2s.  c o  m*/

    // System.setProperty("mail.mime.decodefilename", "true");

    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));

    MimeMultipart mm = new MimeMultipart();
    MimeBodyPart mp = new MimeBodyPart();
    mp.setText("simple text");
    mm.addBodyPart(mp);
    String body = "\u0023\u00A4\u00E3\u00E0\u00E9";
    MimeBodyPart mp2 = new MimeBodyPart(
            new ByteArrayInputStream(("Content-Transfer-Encoding: 8bit\r\n\r\n" + body).getBytes("UTF-8")));
    mp2.setDisposition("attachment");
    mp2.setFileName("=?iso-8859-15?Q?=E9_++++Pubblicit=E0_=E9_vietata____Milano9052.tmp?=");
    mm.addBodyPart(mp2);
    String body2 = "\u0014\u00A3\u00E1\u00E2\u00E4";
    MimeBodyPart mp3 = new MimeBodyPart(
            new ByteArrayInputStream(("Content-Transfer-Encoding: 8bit\r\n\r\n" + body2).getBytes("UTF-8")));
    mp3.setDisposition("attachment");
    mp3.setFileName("temp.zip");
    mm.addBodyPart(mp3);
    message.setSubject("test");
    message.setContent(mm);
    message.saveChanges();

    // message.writeTo(System.out);
    // System.out.println("--------------------------\n\n\n");

    Mail mail = FakeMail.builder().mimeMessage(message).build();

    mailet.service(mail);

    ByteArrayOutputStream rawMessage = new ByteArrayOutputStream();
    mail.getMessage().writeTo(rawMessage, new String[] { "Bcc", "Content-Length", "Message-ID" });
    // String res = rawMessage.toString();

    @SuppressWarnings("unchecked")
    Collection<String> c = (Collection<String>) mail
            .getAttribute(StripAttachment.SAVED_ATTACHMENTS_ATTRIBUTE_KEY);
    Assert.assertNotNull(c);

    Assert.assertEquals(1, c.size());

    String name = c.iterator().next();
    // System.out.println("--------------------------\n\n\n");
    // System.out.println(name);

    Assert.assertTrue(name.startsWith("e_Pubblicita_e_vietata_Milano9052"));

    File f = new File("./" + name);
    try {
        InputStream is = new FileInputStream(f);
        String savedFile = toString(is);
        is.close();
        Assert.assertEquals(body, savedFile);
    } finally {
        FileUtils.deleteQuietly(f);
    }
}

From source file:org.apache.james.transport.mailets.StripAttachmentTest.java

@Test
public void testToAndFromAttributes() throws MessagingException, IOException {
    Mailet strip = new StripAttachment();
    FakeMailetConfig mci = new FakeMailetConfig("Test", FakeMailContext.defaultContext());
    mci.setProperty("attribute", "my.attribute");
    mci.setProperty("remove", "all");
    mci.setProperty("notpattern", ".*\\.tmp.*");
    strip.init(mci);/*ww  w  .  j av a  2s.co  m*/

    Mailet recover = new RecoverAttachment();
    FakeMailetConfig mci2 = new FakeMailetConfig("Test", FakeMailContext.defaultContext());
    mci2.setProperty("attribute", "my.attribute");
    recover.init(mci2);

    Mailet onlyText = new OnlyText();
    onlyText.init(new FakeMailetConfig("Test", FakeMailContext.defaultContext()));

    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));

    MimeMultipart mm = new MimeMultipart();
    MimeBodyPart mp = new MimeBodyPart();
    mp.setText("simple text");
    mm.addBodyPart(mp);
    String body = "\u0023\u00A4\u00E3\u00E0\u00E9";
    MimeBodyPart mp2 = new MimeBodyPart(new ByteArrayInputStream(
            ("Content-Transfer-Encoding: 8bit\r\nContent-Type: application/octet-stream; charset=utf-8\r\n\r\n"
                    + body).getBytes("UTF-8")));
    mp2.setDisposition("attachment");
    mp2.setFileName("=?iso-8859-15?Q?=E9_++++Pubblicit=E0_=E9_vietata____Milano9052.tmp?=");
    mm.addBodyPart(mp2);
    String body2 = "\u0014\u00A3\u00E1\u00E2\u00E4";
    MimeBodyPart mp3 = new MimeBodyPart(new ByteArrayInputStream(
            ("Content-Transfer-Encoding: 8bit\r\nContent-Type: application/octet-stream; charset=utf-8\r\n\r\n"
                    + body2).getBytes("UTF-8")));
    mp3.setDisposition("attachment");
    mp3.setFileName("temp.zip");
    mm.addBodyPart(mp3);
    message.setSubject("test");
    message.setContent(mm);
    message.saveChanges();
    Mail mail = FakeMail.builder().mimeMessage(message).build();

    Assert.assertTrue(mail.getMessage().getContent() instanceof MimeMultipart);
    Assert.assertEquals(3, ((MimeMultipart) mail.getMessage().getContent()).getCount());

    strip.service(mail);

    Assert.assertTrue(mail.getMessage().getContent() instanceof MimeMultipart);
    Assert.assertEquals(1, ((MimeMultipart) mail.getMessage().getContent()).getCount());

    onlyText.service(mail);

    Assert.assertFalse(mail.getMessage().getContent() instanceof MimeMultipart);

    Assert.assertEquals("simple text", mail.getMessage().getContent());

    // prova per caricare il mime message da input stream che altrimenti
    // javamail si comporta differentemente.
    String mimeSource = "Message-ID: <26194423.21197328775426.JavaMail.bago@bagovista>\r\nSubject: test\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=us-ascii\r\nContent-Transfer-Encoding: 7bit\r\n\r\nsimple text";

    MimeMessage mmNew = new MimeMessage(Session.getDefaultInstance(new Properties()),
            new ByteArrayInputStream(mimeSource.getBytes("UTF-8")));

    mmNew.writeTo(System.out);
    mail.setMessage(mmNew);

    recover.service(mail);

    Assert.assertTrue(mail.getMessage().getContent() instanceof MimeMultipart);
    Assert.assertEquals(2, ((MimeMultipart) mail.getMessage().getContent()).getCount());

    Object actual = ((MimeMultipart) mail.getMessage().getContent()).getBodyPart(1).getContent();
    if (actual instanceof ByteArrayInputStream) {
        Assert.assertEquals(body2, toString((ByteArrayInputStream) actual));
    } else {
        Assert.assertEquals(body2, actual);
    }

}

From source file:org.apache.jsieve.mailet.SieveMailboxMailet.java

/**
 * Deliver the original mail as an attachment with the main part being an error report.
 *
 * @param recipient/*from   w w w.  jav a 2 s.c o m*/
 * @param aMail
 * @param ex
 * @throws MessagingException
 * @throws IOException 
 */
protected void handleFailure(MailAddress recipient, Mail aMail, Exception ex)
        throws MessagingException, IOException {
    String user = getUsername(recipient);

    MimeMessage originalMessage = aMail.getMessage();
    MimeMessage message = new MimeMessage(originalMessage);
    MimeMultipart multipart = new MimeMultipart();

    MimeBodyPart noticePart = new MimeBodyPart();
    noticePart.setText(new StringBuilder().append(
            "An error was encountered while processing this mail with the active sieve script for user \"")
            .append(user).append("\". The error encountered was:\r\n").append(ex.getLocalizedMessage())
            .append("\r\n").toString());
    multipart.addBodyPart(noticePart);

    MimeBodyPart originalPart = new MimeBodyPart();
    originalPart.setContent(originalMessage, "message/rfc822");
    if ((originalMessage.getSubject() != null) && (!originalMessage.getSubject().trim().isEmpty())) {
        originalPart.setFileName(originalMessage.getSubject().trim());
    } else {
        originalPart.setFileName("No Subject");
    }
    originalPart.setDisposition(MimeBodyPart.INLINE);
    multipart.addBodyPart(originalPart);

    message.setContent(multipart);
    message.setSubject("[SIEVE ERROR] " + originalMessage.getSubject());
    message.setHeader("X-Priority", "1");
    message.saveChanges();

    storeMessageInbox(user, message);
}

From source file:org.liveSense.service.email.EmailServiceImpl.java

/**
 * {@inheritDoc}//w  w  w  .  jav  a 2 s .c  o  m
 */
@Override
public void sendEmailFromTemplateString(Session session, String template, Node resource, String subject,
        Object replyTo, Object from, Date date, Object[] to, Object[] cc, Object[] bcc,
        HashMap<String, Object> variables) throws Exception {
    boolean haveSession = false;

    try {
        if (session != null && session.isLive()) {
            haveSession = true;
        } else {
            session = repository.loginAdministrative(null);
        }

        if (template == null) {
            throw new RepositoryException("Template is null");
        }
        String html = templateNode(Md5Encrypter.encrypt(template), resource, template, variables);
        if (html == null)
            throw new RepositoryException("Template is empty");

        // create the messge.
        MimeMessage mimeMessage = new MimeMessage((javax.mail.Session) null);

        MimeMultipart rootMixedMultipart = new MimeMultipart("mixed");
        mimeMessage.setContent(rootMixedMultipart);

        MimeMultipart nestedRelatedMultipart = new MimeMultipart("related");
        MimeBodyPart relatedBodyPart = new MimeBodyPart();
        relatedBodyPart.setContent(nestedRelatedMultipart);
        rootMixedMultipart.addBodyPart(relatedBodyPart);

        MimeMultipart messageBody = new MimeMultipart("alternative");
        MimeBodyPart bodyPart = null;
        for (int i = 0; i < nestedRelatedMultipart.getCount(); i++) {
            BodyPart bp = nestedRelatedMultipart.getBodyPart(i);
            if (bp.getFileName() == null) {
                bodyPart = (MimeBodyPart) bp;
            }
        }
        if (bodyPart == null) {
            MimeBodyPart mimeBodyPart = new MimeBodyPart();
            nestedRelatedMultipart.addBodyPart(mimeBodyPart);
            bodyPart = mimeBodyPart;
        }
        bodyPart.setContent(messageBody, "text/alternative");

        // Create the plain text part of the message.
        MimeBodyPart plainTextPart = new MimeBodyPart();
        plainTextPart.setText(extractTextFromHtml(html), configurator.getEncoding());
        messageBody.addBodyPart(plainTextPart);

        // Create the HTML text part of the message.
        MimeBodyPart htmlTextPart = new MimeBodyPart();
        htmlTextPart.setContent(html, "text/html;charset=" + configurator.getEncoding()); // ;charset=UTF-8
        messageBody.addBodyPart(htmlTextPart);

        // Check if resource have nt:file childs adds as attachment
        if (resource != null && resource.hasNodes()) {
            NodeIterator iter = resource.getNodes();
            while (iter.hasNext()) {
                Node n = iter.nextNode();
                if (n.getPrimaryNodeType().isNodeType("nt:file")) {
                    // Part two is attachment
                    MimeBodyPart attachmentBodyPart = new MimeBodyPart();
                    InputStream fileData = n.getNode("jcr:content").getProperty("jcr:data").getBinary()
                            .getStream();
                    String mimeType = n.getNode("jcr:content").getProperty("jcr:mimeType").getString();
                    String fileName = n.getName();

                    DataSource source = new StreamDataSource(fileData, fileName, mimeType);
                    attachmentBodyPart.setDataHandler(new DataHandler(source));
                    attachmentBodyPart.setFileName(fileName);
                    attachmentBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
                    attachmentBodyPart.setContentID(fileName);
                    rootMixedMultipart.addBodyPart(attachmentBodyPart);
                }
            }
        }

        prepareMimeMessage(mimeMessage, resource, template, subject, replyTo, from, date, to, cc, bcc,
                variables);
        sendEmail(session, mimeMessage);

        //
    } finally {
        if (!haveSession && session != null) {
            if (session.hasPendingChanges()) {
                try {
                    session.save();
                } catch (Throwable th) {
                }
            }
            session.logout();
        }
    }
}

From source file:org.xwiki.commons.internal.DefaultMailSender.java

private MimeBodyPart createAttachmentPart(Attachment attachment) {
    try {/* w w  w .j a va2  s. c  o m*/
        String name = attachment.getFilename();
        byte[] stream = attachment.getContent();
        File temp = File.createTempFile("tmpfile", ".tmp");
        FileOutputStream fos = new FileOutputStream(temp);
        fos.write(stream);
        fos.close();
        DataSource source = new FileDataSource(temp);
        MimeBodyPart part = new MimeBodyPart();
        String mimeType = MimeTypesUtil.getMimeTypeFromFilename(name);

        part.setDataHandler(new DataHandler(source));
        part.setHeader("Content-Type", mimeType);
        part.setFileName(name);
        part.setContentID("<" + name + ">");
        part.setDisposition("inline");

        temp.deleteOnExit();
        return part;
    } catch (Exception e) {
        return new MimeBodyPart();
    }
}

From source file:sk.lazyman.gizmo.web.app.PageEmail.java

private Message buildMail(Session session) throws MessagingException, IOException {
    String subject = createSubject();
    Message mimeMessage = createMimeMessage(session, subject);
    mimeMessage.setDisposition(MimeMessage.INLINE);
    Multipart mp = new MimeMultipart("alternative");

    MimeBodyPart textBp = new MimeBodyPart();
    textBp.setDisposition(MimeMessage.INLINE);
    textBp.setContent("Please use mail client with HTML support.", "text/plain; charset=utf-8");
    mp.addBodyPart(textBp);//w  ww  .  j av a 2 s.com

    Multipart commentMultipart = null;
    EmailDto dto = model.getObject();
    if (StringUtils.isNotEmpty(dto.getBody())) {
        BodyPart bodyPart = new MimeBodyPart();
        bodyPart.setDisposition(MimeMessage.INLINE);
        DataHandler dataHandler = new DataHandler(
                new ByteArrayDataSource(dto.getBody(), "text/plain; charset=utf-8"));
        bodyPart.setDataHandler(dataHandler);

        commentMultipart = new MimeMultipart("mixed");
        commentMultipart.addBodyPart(bodyPart);
    }

    String html = createHtml();
    Multipart htmlMp = createHtmlPart(html);

    BodyPart htmlBp = new MimeBodyPart();
    htmlBp.setDisposition(BodyPart.INLINE);
    htmlBp.setContent(htmlMp);
    if (commentMultipart == null) {
        mp.addBodyPart(htmlBp);
    } else {
        commentMultipart.addBodyPart(htmlBp);
        BodyPart all = new MimeBodyPart();
        all.setDisposition(BodyPart.INLINE);
        all.setContent(commentMultipart);
        mp.addBodyPart(all);
    }
    mimeMessage.setContent(mp);

    return mimeMessage;
}