Example usage for javax.mail.internet MimeMessage getContentType

List of usage examples for javax.mail.internet MimeMessage getContentType

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage getContentType.

Prototype

@Override
public String getContentType() throws MessagingException 

Source Link

Document

Returns the value of the RFC 822 "Content-Type" header field.

Usage

From source file:com.zimbra.cs.mime.Mime.java

public static void main(String[] args) throws MessagingException, IOException {
    String s = URLDecoder/*from   w  w w.  j a va 2s.co  m*/
            .decode("Zimbra%20日本語化の考慮点.txt", "utf-8");
    System.out.println(s);
    System.out.println(expandNumericCharacterReferences(
            "Zimbra%20日本語化の考慮点.txt@&;&#;&#x;&#༤&#55"));

    MimeMessage mm = new FixedMimeMessage(JMSession.getSession(),
            new SharedFileInputStream("C:\\Temp\\mail\\24245"));
    InputStream is = new RawContentMultipartDataSource(mm, new ContentType(mm.getContentType()))
            .getInputStream();
    int num;
    byte buf[] = new byte[1024];
    while ((num = is.read(buf)) != -1) {
        System.out.write(buf, 0, num);
    }
}

From source file:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java

public static Body getMessageBody(MimeMessage message, String mimeType) {
    try {//from   w w w . jav  a  2  s  .c  o m

        if (message.getContent() instanceof Multipart) {

            Multipart multipartMessage = (Multipart) message.getContent();

            for (int i = 0; i < multipartMessage.getCount(); i++) {
                BodyPart bodyPart = multipartMessage.getBodyPart(i);

                if (bodyPart.isMimeType(mimeType) && (Part.INLINE.equalsIgnoreCase(bodyPart.getDisposition())
                        || Objects.isNull(bodyPart.getDisposition()))) {

                    return new Body(bodyPart.getContentType(), bodyPart.getContent().toString());

                }
            }
        } else {

            return new Body(message.getContentType(), message.getContent().toString());
        }

    } catch (Exception e) {
        // do nothing
    }

    return null;
}

From source file:mitm.application.djigzo.james.matchers.MailVariableResolver.java

/**
 * Returns the mail value of the mail variable. Returns null if the mail does not support a variable with the given name.
 *///www  . j  a va  2  s .co m
@Override
public String resolveVariable(String variable) throws FunctionException {
    /*
     * Note: non numbers must be single quoted (ie. 'value')
     */
    try {
        /*
         * Mail vars should start with mail.
         */
        if (StringUtils.startsWithIgnoreCase(variable, MAIL_VAR_PREFIX)) {
            if (SIZE.equalsIgnoreCase(variable)) {
                return Long.toString(mail.getMessageSize());
            } else if (RECIPIENTS_SIZE.equalsIgnoreCase(variable)) {
                return Integer.toString(mail.getRecipients().size());
            } else if (CONTENT_TYPE.equalsIgnoreCase(variable)) {
                MimeMessage message = mail.getMessage();

                return message != null ? message.getContentType() : "";
            } else if (StringUtils.startsWithIgnoreCase(variable, MAIL_ATTRIBUTE_PREFIX)) {
                /*
                 * Check to see whether Mail has an attribute with the name
                 */
                String attrName = StringUtils.substringAfter(variable, MAIL_ATTRIBUTE_PREFIX);

                if (StringUtils.isNotEmpty(variable)) {
                    Object attr = mail.getAttribute(attrName);

                    if (attr != null) {
                        return "'" + attr.toString() + "'";
                    }
                }
            }

            return NULL_STRING;
        }

        return null;
    } catch (MessagingException e) {
        throw new FunctionException(e);
    }
}

From source file:eu.peppol.outbound.HttpPostTestIT.java

@Test
public void testPost() throws Exception {

    InputStream resourceAsStream = HttpPostTestIT.class.getClassLoader()
            .getResourceAsStream(PEPPOL_BIS_INVOICE_SBDH_XML);
    assertNotNull(resourceAsStream,//from   w  ww . j  a  v  a  2s.  c  om
            "Unable to locate resource " + PEPPOL_BIS_INVOICE_SBDH_XML + " in class path");

    X509Certificate ourCertificate = keystoreManager.getOurCertificate();

    SMimeMessageFactory SMimeMessageFactory = new SMimeMessageFactory(keystoreManager.getOurPrivateKey(),
            ourCertificate);
    MimeMessage signedMimeMessage = SMimeMessageFactory.createSignedMimeMessage(resourceAsStream,
            new MimeType("application/xml"));

    signedMimeMessage.writeTo(System.out);

    CloseableHttpClient httpClient = createCloseableHttpClient();

    HttpPost httpPost = new HttpPost(OXALIS_AS2_URL);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    signedMimeMessage.writeTo(byteArrayOutputStream);

    X500Principal subjectX500Principal = ourCertificate.getSubjectX500Principal();
    CommonName commonNameOfSender = CommonName.valueOf(subjectX500Principal);
    PeppolAs2SystemIdentifier asFrom = PeppolAs2SystemIdentifier.valueOf(commonNameOfSender);

    httpPost.addHeader(As2Header.AS2_FROM.getHttpHeaderName(), asFrom.toString());
    httpPost.addHeader(As2Header.AS2_TO.getHttpHeaderName(),
            new PeppolAs2SystemIdentifier(PeppolAs2SystemIdentifier.AS2_SYSTEM_ID_PREFIX + "AS2-TEST")
                    .toString());
    httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_OPTIONS.getHttpHeaderName(),
            As2DispositionNotificationOptions.getDefault().toString());
    httpPost.addHeader(As2Header.AS2_VERSION.getHttpHeaderName(), As2Header.VERSION);
    httpPost.addHeader(As2Header.SUBJECT.getHttpHeaderName(), "AS2 TEST MESSAGE");
    httpPost.addHeader(As2Header.MESSAGE_ID.getHttpHeaderName(), UUID.randomUUID().toString());
    httpPost.addHeader(As2Header.DATE.getHttpHeaderName(), As2DateUtil.format(new Date()));

    // Inserts the S/MIME message to be posted
    httpPost.setEntity(
            new ByteArrayEntity(byteArrayOutputStream.toByteArray(), ContentType.create("multipart/signed")));

    CloseableHttpResponse postResponse = null; // EXECUTE !!!!
    try {
        postResponse = httpClient.execute(httpPost);
    } catch (HttpHostConnectException e) {
        fail("The Oxalis server does not seem to be running at " + OXALIS_AS2_URL);
    }

    HttpEntity entity = postResponse.getEntity(); // Any results?
    Assert.assertEquals(postResponse.getStatusLine().getStatusCode(), 200);
    String contents = EntityUtils.toString(entity);

    assertNotNull(contents);
    if (log.isDebugEnabled()) {
        log.debug("Received: \n");
        Header[] allHeaders = postResponse.getAllHeaders();
        for (Header header : allHeaders) {
            log.debug("" + header.getName() + ": " + header.getValue());
        }
        log.debug("\n" + contents);
        log.debug("---------------------------");
    }

    try {

        MimeMessage mimeMessage = MimeMessageHelper.parseMultipart(contents);
        System.out.println("Received multipart MDN response decoded as type : " + mimeMessage.getContentType());

        // Make sure we set content type header for the multipart message (should be multipart/signed)
        String contentTypeFromHttpResponse = postResponse.getHeaders("Content-Type")[0].getValue(); // Oxalis always return only one
        mimeMessage.setHeader("Content-Type", contentTypeFromHttpResponse);
        Enumeration<String> headerlines = mimeMessage.getAllHeaderLines();
        while (headerlines.hasMoreElements()) {
            // Content-Type: multipart/signed;
            // protocol="application/pkcs7-signature";
            // micalg=sha-1;
            // boundary="----=_Part_3_520186210.1399207766925"
            System.out.println("HeaderLine : " + headerlines.nextElement());
        }

        MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage);
        String msg = mdnMimeMessageInspector.getPlainTextPartAsText();
        System.out.println(msg);

    } finally {
        postResponse.close();
    }
}

From source file:com.silverpeas.mailinglist.model.TestMailingListComponent.java

protected void checkSimpleEmail(String address, String subject) throws Exception {
    Mailbox inbox = Mailbox.get(address);
    assertNotNull(inbox);/*from  www .  jav a  2  s. co  m*/
    assertEquals("No message for " + address, 1, inbox.size());
    MimeMessage alert = (MimeMessage) inbox.iterator().next();
    assertNotNull(alert);
    assertEquals(subject, alert.getSubject());
    assertEquals("text/plain; charset=\"UTF-8\"", alert.getContentType());
    assertEquals(textEmailContent, (String) alert.getContent());
}

From source file:org.parancoe.test.LoggingMailSender.java

@Override
protected void doSend(MimeMessage[] mimeMessages, Object[] originalMessages) {
    if (mimeMessages != null) {
        for (MimeMessage mimeMessage : mimeMessages) {
            try {
                logger.info("from: {}", (Object[]) mimeMessage.getFrom());
                logger.info("to: {}", (Object[]) mimeMessage.getRecipients(Message.RecipientType.TO));
                logger.info("cc: {}", (Object[]) mimeMessage.getRecipients(Message.RecipientType.CC));
                logger.info("bcc: {}", (Object[]) mimeMessage.getRecipients(Message.RecipientType.BCC));
                logger.info("subject: {}", mimeMessage.getSubject());
                logger.info("content: {}", mimeMessage.getContent().toString());
                logger.info("content type: {}", mimeMessage.getContentType());
            } catch (Exception ex) {
                logger.error("Can't get message content", ex);
            }//from   w  w w.  ja v a 2s.  c  o  m
        }
    }
}

From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java

private EmailMessage wrapMessage(Message msg, boolean populateContent, Session session)
        throws MessagingException, IOException, ScanException, PolicyException {

    // Prepare subject
    String subject = msg.getSubject();
    if (!StringUtils.isBlank(subject)) {
        AntiSamy as = new AntiSamy();
        CleanResults cr = as.scan(subject, policy);
        subject = cr.getCleanHTML();// w  ww . java  2 s . co  m
    }

    // Prepare content if requested
    EmailMessageContent msgContent = null; // default...
    if (populateContent) {
        // Defend against the dreaded: "Unable to load BODYSTRUCTURE"
        try {
            msgContent = getMessageContent(msg.getContent(), msg.getContentType());
        } catch (MessagingException me) {
            // We are unable to read digitally-signed messages (perhaps
            // others?) in the API-standard way;  we have to use a work around.
            // See: http://www.oracle.com/technetwork/java/faq-135477.html#imapserverbug
            // Logging as DEBUG because this behavior is known & expected.
            log.debug("Difficulty reading a message (digitally signed?). Attempting workaround...");
            try {
                MimeMessage mm = (MimeMessage) msg;
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                mm.writeTo(bos);
                bos.close();
                SharedByteArrayInputStream bis = new SharedByteArrayInputStream(bos.toByteArray());
                MimeMessage copy = new MimeMessage(session, bis);
                bis.close();
                msgContent = getMessageContent(copy.getContent(), copy.getContentType());
            } catch (Throwable t) {
                log.error("Failed to read message body", t);
                msgContent = new EmailMessageContent("UNABLE TO READ MESSAGE BODY: " + t.getMessage(), false);
            }
        }

        // Sanitize with AntiSamy
        String content = msgContent.getContentString();
        if (!StringUtils.isBlank(content)) {
            AntiSamy as = new AntiSamy();
            CleanResults cr = as.scan(content, policy);
            content = cr.getCleanHTML();
        }
        msgContent.setContentString(content);
    }

    int messageNumber = msg.getMessageNumber();

    // Prepare the UID if present
    String uid = null; // default
    if (msg.getFolder() instanceof UIDFolder) {
        uid = Long.toString(((UIDFolder) msg.getFolder()).getUID(msg));
    }

    Address[] addr = msg.getFrom();
    String sender = getFormattedAddresses(addr);
    Date sentDate = msg.getSentDate();

    boolean unread = !msg.isSet(Flag.SEEN);
    boolean answered = msg.isSet(Flag.ANSWERED);
    boolean deleted = msg.isSet(Flag.DELETED);
    // Defend against the dreaded: "Unable to load BODYSTRUCTURE"
    boolean multipart = false; // sensible default;
    String contentType = null; // sensible default
    try {
        multipart = msg.getContentType().toLowerCase().startsWith(CONTENT_TYPE_ATTACHMENTS_PATTERN);
        contentType = msg.getContentType();
    } catch (MessagingException me) {
        // Message was digitally signed and we are unable to read it;
        // logging as DEBUG because this issue is known/expected, and
        // because the user's experience is in no way affected (at this point)
        log.debug("Message content unavailable (digitally signed?);  "
                + "message will appear in the preview table correctly, " + "but the body will not be viewable");
        log.trace(me.getMessage(), me);
    }
    String to = getTo(msg);
    String cc = getCc(msg);
    String bcc = getBcc(msg);
    return new EmailMessage(messageNumber, uid, sender, subject, sentDate, unread, answered, deleted, multipart,
            contentType, msgContent, to, cc, bcc);
}

From source file:gr.abiss.calipso.mail.MailSender.java

/**
 * we bend the rules a little and fire off a new thread for sending
 * an email message.  This has the advantage of not slowing down the item
 * create and update screens, i.e. the system returns the next screen
 * after "submit" without blocking.  This has been used in production
 * for quite a while now, on Tomcat without any problems.  This helps a lot
 * especially when the SMTP server is slow to respond, etc.
 *///from ww  w .  jav  a2  s .com
private void sendInNewThread(final MimeMessage message) {
    //       try {
    //          logger.info("Sending message: " + message.getSubject() + "\n" + message.getContent());
    //      } catch (MessagingException e1) {
    //         // TODO Auto-generated catch block
    //         e1.printStackTrace();
    //      } catch (IOException e1) {
    //         // TODO Auto-generated catch block
    //         e1.printStackTrace();
    //      }
    if (logger.isDebugEnabled()) {
        try {
            logger.debug("Message contenttype: " + message.getContentType());
            logger.debug("Message content: " + message.getContent());
            Enumeration headers = message.getAllHeaders();

            logger.debug("Message Headers...");
            while (headers.hasMoreElements()) {
                Header h = (Header) headers.nextElement();
                logger.error(h.getName() + ": " + h.getValue());
            }
            logger.debug("Message flags: " + message.getFlags());
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    new Thread() {
        @Override
        public void run() {
            logger.debug("send mail thread start");
            try {
                try {
                    sender.send(message);
                    logger.debug("send mail thread successfull");
                } catch (Exception e) {
                    logger.error("send mail thread failed, dumping headers: ");
                    logger.error("mail headers dump start");
                    Enumeration headers = message.getAllHeaders();
                    while (headers.hasMoreElements()) {
                        Header h = (Header) headers.nextElement();
                        logger.error(h.getName() + ": " + h.getValue());
                    }
                    logger.error("mail headers dump end, exception follows", e);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }.start();
}

From source file:com.cubusmail.server.mail.MessageHandler.java

/**
 * @param session/*www .j  av  a  2  s  .c  o  m*/
 * @param message
 */
public void init(Session session, MimeMessage message) {

    this.session = session;
    this.message = message;
    try {
        this.readBefore = this.message.isSet(Flag.SEEN);
        String contentType = message.getContentType();
        ContentType type = new ContentType(contentType);
        String charset = type.getParameter("charset");
        if (charset != null) {
            this.charset = charset;
        } else {
            // this.message.setHeader( name, value )
        }
    } catch (MessagingException e) {
        log.warn(e.getMessage());
    }
}

From source file:com.cubusmail.mail.MessageHandler.java

/**
 * @param session//from w w  w .  ja va2s .  c  om
 * @param message
 */
private void init(Session session, MimeMessage message) {

    this.session = session;
    this.message = message;
    try {
        this.readBefore = this.message.isSet(Flag.SEEN);
        String contentType = message.getContentType();
        ContentType type = new ContentType(contentType);
        String charset = type.getParameter("charset");
        if (charset != null) {
            this.charset = charset;
        } else {
            // this.message.setHeader( name, value )
        }
    } catch (MessagingException e) {
        log.warn(e.getMessage());
    }
}