Example usage for javax.mail BodyPart getFileName

List of usage examples for javax.mail BodyPart getFileName

Introduction

In this page you can find the example usage for javax.mail BodyPart getFileName.

Prototype

public String getFileName() throws MessagingException;

Source Link

Document

Get the filename associated with this part, if possible.

Usage

From source file:org.ikasan.component.endpoint.email.producer.EmailProducerTest.java

@Test
public void test_successful_email_withAttachment() throws MessagingException, IOException {

    EmailProducerConfiguration emailProducerConfiguration = getConfiguration(true, null);

    EmailProducer emailProducer = new EmailProducer();
    ((Configured) emailProducer).setConfiguration(emailProducerConfiguration);
    ((ManagedResource) emailProducer).startManagedResource();

    emailProducer.invoke(getEmailPayload(true, null));
    List<WiserMessage> messages = wiser.getMessages();

    Assert.assertTrue("Should be three messages - one per addressee", messages.size() == 3);
    for (WiserMessage message : wiser.getMessages()) {
        Assert.assertTrue("sender should be " + sender, sender.equals(message.getEnvelopeSender()));

        MimeMessage mimeMessage = message.getMimeMessage();
        MimeMultipart mimeMultipart = (MimeMultipart) mimeMessage.getContent();
        Assert.assertTrue("should be 2 bodypart", mimeMultipart.getCount() == 2);
        BodyPart bodyPart = mimeMultipart.getBodyPart(0);
        String content = (String) bodyPart.getContent();
        Assert.assertTrue("The email content should be empty", content.isEmpty());
        BodyPart attachment = mimeMultipart.getBodyPart(1);
        Assert.assertEquals("Check attachment file name", "testAttachment", attachment.getFileName());
        Assert.assertTrue("Check file content",
                IOUtils.toString(attachment.getDataHandler().getDataSource().getInputStream())
                        .contains("1997,Ford,E350"));
        Assert.assertTrue("Should find email format as \"text/plain\"",
                bodyPart.getContentType().contains("text/plain"));

    }/*from  w  w  w.  j  av a2s .c o  m*/
}

From source file:com.crawlersick.nettool.GetattchmentFromMail1.java

public boolean fetchmailforattch() throws IOException, MessagingException {
    boolean fetchtest = false;

    Properties props = new Properties();
    props.setProperty("mail.store.protocol", "imaps");

    try {/*from   w  w w  .  j  av a  2s.c om*/
        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect(IMapHost, MailId, MailPassword);
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);
        totalmailcount = inbox.getMessageCount();

        Message msg = null;
        for (int i = totalmailcount; i > 0; i--) {
            fromadd = "";
            msg = inbox.getMessage(i);
            Address[] in = msg.getFrom();
            for (Address address : in) {
                fromadd = address.toString() + fromadd;
                //System.out.println("FROM:" + address.toString());
            }
            if (fromadd.matches("admin@cronmailservice.appspotmail.com") && msg.getSubject().matches(
                    "ThanksToTsukuba_World-on-my-shoulders-as-I-run-back-to-this-8-Mile-Road_cronmailservice"))
                break;
        }

        if (fromadd.equals("'")) {
            log.log(Level.SEVERE, "Error: no related mail found!" + this.MailId);
            return fetchtest;
        }

        //    Multipart mp = (Multipart) msg.getContent();
        //  BodyPart bp = mp.getBodyPart(0);
        sentdate = msg.getSentDate().toString();

        subject = msg.getSubject();

        Content = msg.getContent().toString();

        log.log(Level.INFO, Content);
        log.log(Level.INFO, sentdate);
        localIntent.putExtra("213123", "Got Server latest update at : " + sentdate + " , Reading the Data...");
        LocalBroadcastManager.getInstance(myis).sendBroadcast(localIntent);

        Multipart multipart = (Multipart) msg.getContent();
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && (bodyPart.getFileName() == null
                    || !bodyPart.getFileName().equals("dataforvgendwithudp.gzip"))) {
                continue; // dealing with attachments only
            }
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            InputStream is = bodyPart.getInputStream();
            //validvgbinary = IOUtils.toByteArray(is);
            int nRead;
            byte[] data = new byte[5000000];

            while ((nRead = is.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }

            buffer.flush();

            validvgbinary = buffer.toByteArray();
            break;
        }

        fetchtest = true;
    } catch (Exception mex) {
        mex.printStackTrace();

    }

    return fetchtest;
}

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

public boolean sendWithUniSender() {
    LOG.info("Init...");
    boolean result = true;
    Object oID_Message = null;/*from   w  ww.  j a v a  2s.co m*/
    StringBuilder sbBody = new StringBuilder();
    try {
        sbBody.append("host: ");
        sbBody.append(getHost());
        sbBody.append(":");
        sbBody.append(getPort());
        sbBody.append("\nAuthUser:");
        sbBody.append(getAuthUser());
        sbBody.append("\nfrom:");
        sbBody.append(getFrom());
        sbBody.append("\nto:");
        sbBody.append(getTo());
        sbBody.append("\nhead:");
        sbBody.append(getHead());

        String sKey_Sender = generalConfig.getKey_UniSender_Mail();
        long nID_Sender = generalConfig.getSendListId_UniSender_Mail();
        if (StringUtils.isBlank(sKey_Sender)) {
            throw new IllegalArgumentException("Please check api_key in UniSender property file configuration");
        }

        LOG.info("oUniSender - {}", oUniSender);
        LOG.info("methodCallRunner - {}", methodCallRunner);
        oUniSender.setMethodCallRunner(methodCallRunner);

        if (getTo().contains(",")) {
            String[] asMail = getTo().split("\\,");
            for (String sMail : asMail) {
                sMail = sMailOnly(sMail);
                UniResponse oUniResponse_Subscribe = oUniSender
                        .subscribe(Collections.singletonList(String.valueOf(nID_Sender)), sMail, getToName());
                LOG.info("(sMail={},oUniResponse_Subscribe={})", sMail, oUniResponse_Subscribe);
            }
        } else {
            String sMail = sMailOnly(getTo());
            UniResponse oUniResponse_Subscribe = oUniSender
                    .subscribe(Collections.singletonList(String.valueOf(nID_Sender)), sMail, getToName());
            LOG.info("(oUniResponse_Subscribe={})", oUniResponse_Subscribe);
        }

        String sBody = getBody();
        //sBody = sBody + "" + "<br>? ?   <a href=\"{{UnsubscribeUrl}}\">??</a>";
        sBody = sBody + ""
                + "<br>   ??  ,  ?, ? <a href=\"{{UnsubscribeUrl}}\"</a>/";

        CreateEmailMessageRequest.Builder oBuilder = CreateEmailMessageRequest
                //.getBuilder(sKey_Sender, "en")
                .getBuilder(sKey_Sender, "ua").setSenderName("no reply").setSenderEmail(getFrom())
                .setSubject(getHead()).setBody(sBody).setListId(String.valueOf(nID_Sender));

        try {
            int nAttachments = oMultiparts.getCount();
            for (int i = 0; i < nAttachments; i++) {
                BodyPart oBodyPart = oMultiparts.getBodyPart(i);
                String sFileName = oBodyPart.getFileName();
                InputStream oInputStream = oBodyPart.getInputStream();
                oBuilder.setAttachment(sFileName, oInputStream);
            }
        } catch (IOException e) {
            throw new Exception("Error while getting attachment.", e);
        } catch (MessagingException e) {
            throw new Exception("Error while getting attachment.", e);
        }

        CreateEmailMessageRequest oCreateEmailMessageRequest = oBuilder.build();

        UniResponse oUniResponse_CreateEmailMessage = oUniSender.createEmailMessage(oCreateEmailMessageRequest);
        LOG.info("(oUniResponse_CreateEmailMessage={})", oUniResponse_CreateEmailMessage);

        if (oUniResponse_CreateEmailMessage != null && oUniResponse_CreateEmailMessage.getResult() != null) {
            Map<String, Object> mParam = oUniResponse_CreateEmailMessage.getResult();
            LOG.info("(mParam={})", mParam);
            oID_Message = mParam.get("message_id");
            if (oID_Message != null) {
                LOG.info("(oID_Message={})", oID_Message);
                CreateCampaignRequest oCreateCampaignRequest = CreateCampaignRequest
                        .getBuilder(sKey_Sender, "en").setMessageId(oID_Message.toString()).build();

                UniResponse oUniResponse_CreateCampaign = oUniSender.createCampaign(oCreateCampaignRequest,
                        getTo());
                LOG.info("(oUniResponse_CreateCampaign={})", oUniResponse_CreateCampaign);
            } else {
                result = false;
                LOG.error("error while email creation " + oUniResponse_CreateEmailMessage.getError());
                //throw new EmailException("error while email creation " + oUniResponse_CreateEmailMessage.getError());
            }
        }
    } catch (Exception oException) {
        result = false;
        LOG.error("FAIL: {} (oID_Message()={},getTo()={})", oException.getMessage(), oID_Message, getTo());
        new Log(oException, LOG)._Case("Mail_FailUS")._Status(Log.LogStatus.ERROR)._Head("First try send fail")
                ._Param("getTo", getTo())._Param("sbBody", sbBody)._Param("oID_Message", oID_Message).save();
    }
    LOG.info("SUCCESS: sent!");
    return result;
}

From source file:org.elasticsearch.river.email.EmailToJson.java

public static List<AttachmentInfo> saveAttachmentToWeedFs(Part message, List<AttachmentInfo> attachments,
        EmailRiverConfig config)/*from w  ww.java  2  s.  c  o m*/
        throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException {
    if (attachments == null) {
        attachments = new ArrayList<AttachmentInfo>();
    }
    boolean hasAttachment = false;
    try {
        hasAttachment = isContainAttachment(message);
    } catch (MessagingException e) {
        logger.error("save attachment", e);
    } catch (IOException e) {
        logger.error("save attachment", e);
    }
    if (hasAttachment) {

        if (message.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) message.getContent();

            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {

                BodyPart bodyPart = multipart.getBodyPart(i);

                String disp = bodyPart.getDisposition();
                if (disp != null
                        && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    InputStream is = bodyPart.getInputStream();

                    BufferedInputStream bis = new BufferedInputStream(is);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();

                    int len = -1;
                    while ((len = bis.read()) != -1) {
                        bos.write(len);
                    }
                    bos.close();
                    bis.close();

                    byte[] data = bos.toByteArray();
                    String fileId = uploadFileToWeedfs(data, config);
                    if (fileId != null) {
                        AttachmentInfo info = new AttachmentInfo();
                        info.fileId = fileId;
                        info.fileName = decodeText(bodyPart.getFileName());
                        info.fileSize = data.length;
                        attachments.add(info);
                    }

                } else if (bodyPart.isMimeType("multipart/*")) {

                    attachments.addAll(saveAttachmentToWeedFs(bodyPart, attachments, config));

                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                        attachments.addAll(saveAttachmentToWeedFs(bodyPart, attachments, config));
                    }
                }
            }
        } else if (message.isMimeType("message/rfc822")) {

            attachments.addAll(saveAttachmentToWeedFs(message, attachments, config));

        }

    }
    return attachments;
}

From source file:org.openhie.openempi.service.MailEngineTest.java

public void testSendMessageWithAttachment() throws Exception {
    final String ATTACHMENT_NAME = "boring-attachment.txt";

    //mock smtp server
    Wiser wiser = new Wiser();
    int port = 2525 + (int) (Math.random() * 100);
    mailSender.setPort(port);/*from  w  ww.  j  a  v a2s.c o  m*/
    wiser.setPort(port);
    wiser.start();

    Date dte = new Date();
    String emailSubject = "grepster testSendMessageWithAttachment: " + dte;
    String emailBody = "Body of the grepster testSendMessageWithAttachment message sent at: " + dte;

    ClassPathResource cpResource = new ClassPathResource("/test-attachment.txt");
    mailEngine.sendMessage(new String[] { "foo@bar.com" }, mailMessage.getFrom(), cpResource, emailBody,
            emailSubject, ATTACHMENT_NAME);

    wiser.stop();
    assertTrue(wiser.getMessages().size() == 1);
    WiserMessage wm = wiser.getMessages().get(0);
    MimeMessage mm = wm.getMimeMessage();

    Object o = wm.getMimeMessage().getContent();
    assertTrue(o instanceof MimeMultipart);
    MimeMultipart multi = (MimeMultipart) o;
    int numOfParts = multi.getCount();

    boolean hasTheAttachment = false;
    for (int i = 0; i < numOfParts; i++) {
        BodyPart bp = multi.getBodyPart(i);
        String disp = bp.getDisposition();
        if (disp == null) { //the body of the email
            Object innerContent = bp.getContent();
            MimeMultipart innerMulti = (MimeMultipart) innerContent;
            assertEquals(emailBody, innerMulti.getBodyPart(0).getContent());
        } else if (disp.equals(Part.ATTACHMENT)) { //the attachment to the email
            hasTheAttachment = true;
            assertEquals(ATTACHMENT_NAME, bp.getFileName());
        } else {
            fail("Did not expect to be able to get here.");
        }
    }
    assertTrue(hasTheAttachment);
    assertEquals(emailSubject, mm.getSubject());
}

From source file:com.canoo.webtest.plugins.emailtest.EmailMessageContentFilter.java

private void extractMultiPartMessage(final Multipart parts, final int partIndex) throws MessagingException {
    try {/*from w ww .  j  ava2  s .com*/
        if (partIndex >= parts.getCount()) {
            throw new StepFailedException("PartIndex too large.", this);
        }
        final BodyPart part = parts.getBodyPart(partIndex);
        final String contentType = part.getContentType();
        if (!StringUtils.isEmpty(getContentType()) && !contentType.equals(getContentType())) {
            throw new MessagingException("Actual contentType of '" + contentType
                    + "' did not match expected contentType of '" + fContentType + "'");
        }
        final String disp = part.getDisposition();
        final String filename = part.getFileName();
        final InputStream inputStream = part.getInputStream();
        if (Part.ATTACHMENT.equals(disp)) {
            fFilename = filename;
        } else {
            fFilename = getClass().getName();
        }
        ContextHelper.defineAsCurrentResponse(getContext(), IOUtils.toString(inputStream), contentType,
                "http://" + fFilename);
    } catch (IOException e) {
        throw new MessagingException("Error extracting part: " + e.getMessage());
    }
}

From source file:org.openmrs.contrib.metadatarepository.service.MailEngineTest.java

@Test
public void testSendMessageWithAttachment() throws Exception {
    final String ATTACHMENT_NAME = "boring-attachment.txt";

    //mock smtp server
    Wiser wiser = new Wiser();
    int port = 2525 + (int) (Math.random() * 100);
    mailSender.setPort(port);//from  w  w  w  .j av  a2s  . c  o m
    wiser.setPort(port);
    wiser.start();

    Date dte = new Date();
    String emailSubject = "grepster testSendMessageWithAttachment: " + dte;
    String emailBody = "Body of the grepster testSendMessageWithAttachment message sent at: " + dte;

    ClassPathResource cpResource = new ClassPathResource("/test-attachment.txt");
    // a null from should work
    mailEngine.sendMessage(new String[] { "foo@bar.com" }, null, cpResource, emailBody, emailSubject,
            ATTACHMENT_NAME);

    mailEngine.sendMessage(new String[] { "foo@bar.com" }, mailMessage.getFrom(), cpResource, emailBody,
            emailSubject, ATTACHMENT_NAME);

    wiser.stop();
    // one without and one with from
    assertTrue(wiser.getMessages().size() == 2);

    WiserMessage wm = wiser.getMessages().get(0);
    MimeMessage mm = wm.getMimeMessage();

    Object o = wm.getMimeMessage().getContent();
    assertTrue(o instanceof MimeMultipart);
    MimeMultipart multi = (MimeMultipart) o;
    int numOfParts = multi.getCount();

    boolean hasTheAttachment = false;
    for (int i = 0; i < numOfParts; i++) {
        BodyPart bp = multi.getBodyPart(i);
        String disp = bp.getDisposition();
        if (disp == null) { //the body of the email
            Object innerContent = bp.getContent();
            MimeMultipart innerMulti = (MimeMultipart) innerContent;
            assertEquals(emailBody, innerMulti.getBodyPart(0).getContent());
        } else if (disp.equals(Part.ATTACHMENT)) { //the attachment to the email
            hasTheAttachment = true;
            assertEquals(ATTACHMENT_NAME, bp.getFileName());
        } else {
            fail("Did not expect to be able to get here.");
        }
    }
    assertTrue(hasTheAttachment);
    assertEquals(emailSubject, mm.getSubject());
}

From source file:com.glaf.mail.business.MailBean.java

/**
 * ?//from   www . jav a 2 s .c  om
 * 
 * @param part
 * @throws MessagingException
 * @throws IOException
 */
public void parseAttachment(Part part) throws MessagingException, IOException {
    String filename = "";
    if (part.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) part.getContent();
        for (int i = 0; i < mp.getCount(); i++) {
            BodyPart mpart = mp.getBodyPart(i);
            String dispostion = mpart.getDisposition();
            if ((dispostion != null)
                    && (dispostion.equals(Part.ATTACHMENT) || dispostion.equals(Part.INLINE))) {
                filename = mpart.getFileName();
                if (filename != null) {
                    logger.debug("orig filename=" + filename);
                    if (filename.indexOf("?") != -1) {
                        filename = new String(filename.getBytes("GBK"), "UTF-8");
                    }
                    if (filename.toLowerCase().indexOf("gb2312") != -1) {
                        filename = MimeUtility.decodeText(filename);
                    }
                    filename = MailUtils.convertString(filename);
                    logger.debug("filename=" + filename);
                    parseFileContent(filename, mpart.getInputStream());
                }
            } else if (mpart.isMimeType("multipart/*")) {
                parseAttachment(mpart);
            } else {
                filename = mpart.getFileName();
                if (filename != null) {
                    logger.debug("orig filename=" + filename);
                    if (filename.indexOf("?") != -1) {
                        filename = new String(filename.getBytes("GBK"), "UTF-8");
                    }
                    if (filename.toLowerCase().indexOf("gb2312") != -1) {
                        filename = MimeUtility.decodeText(filename);
                    }
                    filename = MailUtils.convertString(filename);
                    parseFileContent(filename, mpart.getInputStream());
                    logger.debug("filename=" + filename);
                }
            }
        }

    } else if (part.isMimeType("message/rfc822")) {
        parseAttachment((Part) part.getContent());
    }
}

From source file:org.springintegration.demo.service.EmailTransformer.java

public void handleMultipart(Multipart multipart, javax.mail.Message mailMessage, List<Message<?>> messages) {
    final int count;
    try {//  w  w w  . ja va  2 s . c o  m
        count = multipart.getCount();
    } catch (MessagingException e) {
        throw new IllegalStateException("Error while retrieving the number of enclosed BodyPart objects.", e);
    }

    for (int i = 0; i < count; i++) {

        final BodyPart bp;

        try {
            bp = multipart.getBodyPart(i);
        } catch (MessagingException e) {
            throw new IllegalStateException("Error while retrieving body part.", e);
        }

        final String contentType;
        final String filename;
        final String disposition;
        final String subject;

        try {
            contentType = bp.getContentType();
            filename = bp.getFileName();
            disposition = bp.getDisposition();
            subject = mailMessage.getSubject();

        } catch (MessagingException e) {
            throw new IllegalStateException("Unable to retrieve body part meta data.", e);
        }

        if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
            LOGGER.info("Handdling attachment '{}', type: '{}'", filename, contentType);
        }

        final Object content;

        try {
            content = bp.getContent();
        } catch (IOException e) {
            throw new IllegalStateException("Error while retrieving the email contents.", e);
        } catch (MessagingException e) {
            throw new IllegalStateException("Error while retrieving the email contents.", e);
        }

        if (content instanceof String) {

            final Message<String> message = MessageBuilder.withPayload((String) content)
                    .setHeader(FileHeaders.FILENAME, subject + ".txt").build();

            messages.add(message);

        } else if (content instanceof InputStream) {

            InputStream inputStream = (InputStream) content;
            ByteArrayOutputStream bis = new ByteArrayOutputStream();

            try {
                IOUtils.copy(inputStream, bis);
            } catch (IOException e) {
                throw new IllegalStateException(
                        "Error while copying input stream to the ByteArrayOutputStream.", e);
            }

            Message<byte[]> message = MessageBuilder.withPayload((bis.toByteArray()))
                    .setHeader(FileHeaders.FILENAME, filename).build();

            messages.add(message);

        } else if (content instanceof javax.mail.Message) {
            handleMessage((javax.mail.Message) content, messages);
        } else if (content instanceof Multipart) {
            Multipart mp2 = (Multipart) content;
            handleMultipart(mp2, mailMessage, messages);
        } else {
            throw new IllegalStateException("Content type not handled: " + content.getClass().getSimpleName());
        }
    }

}

From source file:mitm.application.djigzo.james.mailets.BlackberrySMIMEAdapterTest.java

@Test
public void testInvalidEncoding() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig("test");

    SendMailEventListenerImpl listener = new SendMailEventListenerImpl();

    mailetConfig.getMailetContext().setSendMailEventListener(listener);

    Mailet mailet = new BlackberrySMIMEAdapter();

    String template = FileUtils.readFileToString(
            new File("test/resources/templates/blackberry-smime-adapter-invalid-encoding.ftl"));

    autoTransactDelegator.setProperty("test@EXAMPLE.com", "pdfTemplate", template);

    mailetConfig.setInitParameter("log", "starting");
    /* use some dummy template because we must specify the default template */
    mailetConfig.setInitParameter("template", "sms.ftl");
    mailetConfig.setInitParameter("templateProperty", "pdfTemplate");

    mailet.init(mailetConfig);/*from  w w w .  j  av  a2  s  .c  o m*/

    MockMail mail = new MockMail();

    mail.setState(Mail.DEFAULT);

    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/signed-opaque-validcertificate.eml"));

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress("123@EXAMPLE.com"));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("sender@example.com"));

    mailet.service(mail);

    MailUtils.validateMessage(mail.getMessage());

    assertTrue(mail.getMessage().isMimeType("multipart/mixed"));
    assertFalse(mail.getMessage() == message);

    MimeMultipart mp = (MimeMultipart) mail.getMessage().getContent();

    assertEquals(2, mp.getCount());

    BodyPart bp = mp.getBodyPart(0);

    assertTrue(bp.isMimeType("text/plain"));

    bp = mp.getBodyPart(1);

    assertTrue(bp.isMimeType("application/octet-stream"));
    assertEquals("x-rimdevicesmime.p7m", bp.getFileName());
}