Example usage for javax.mail.internet MimeMessage writeTo

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

Introduction

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

Prototype

@Override
public void writeTo(OutputStream os) throws IOException, MessagingException 

Source Link

Document

Output the message as an RFC 822 format stream.

Usage

From source file:app.logica.gestores.GestorEmail.java

/**
 * Create a message from an email./*from   w ww. j ava 2 s  .  c o m*/
 *
 * @param emailContent
 *            Email to be set to raw of message
 * @return a message containing a base64url encoded email
 * @throws IOException
 * @throws MessagingException
 */
private Message createMessageWithEmail(MimeMessage emailContent) throws MessagingException, IOException {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    emailContent.writeTo(buffer);
    byte[] bytes = buffer.toByteArray();
    String encodedEmail = Base64.encodeBase64URLSafeString(bytes);
    Message message = new Message();
    message.setRaw(encodedEmail);
    return message;
}

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  w  w  . jav  a  2s  . com*/
            "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.threewks.thundr.gmail.GmailMailer.java

/**
  * Create a Message from an email/*from ww w. j a  va 2  s .  c om*/
  *
  * @param email Email to be set to raw of message
  * @return Message containing base64url encoded email.
  * @throws IOException
  * @throws MessagingException
  */
protected Message createMessageWithEmail(MimeMessage email) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    try {
        email.writeTo(bytes);
    } catch (MessagingException | IOException e) {
        Logger.error("Could not write email to output stream: %s", e.getMessage());
        throw new GmailException(e);
    }
    String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());
    Message message = new Message();
    message.setRaw(encodedEmail);
    return message;
}

From source file:com.hs.mail.smtp.message.SmtpMessage.java

public void setContent(MimeMessage msg) throws IOException, MessagingException {
    OutputStream os = null;//from   w  w  w .j  a  v a2 s. c  om
    try {
        os = new BufferedOutputStream(new FileOutputStream(getDataFile()));
        msg.writeTo(os);
    } finally {
        IOUtils.closeQuietly(os);
    }
}

From source file:org.apache.james.jdkim.mailets.DKIMSign.java

public void service(Mail mail) throws MessagingException {
    DKIMSigner signer = new DKIMSigner(getSignatureTemplate(), getPrivateKey());
    SignatureRecord signRecord = signer.newSignatureRecordTemplate(getSignatureTemplate());
    try {/*from  www  .j  av  a2 s . c  o  m*/
        BodyHasher bhj = signer.newBodyHasher(signRecord);
        MimeMessage message = mail.getMessage();
        Headers headers = new MimeMessageHeaders(message);
        try {
            OutputStream os = new HeaderSkippingOutputStream(bhj.getOutputStream());
            if (forceCRLF)
                os = new CRLFOutputStream(os);
            message.writeTo(os);
            bhj.getOutputStream().close();
        } catch (IOException e) {
            throw new MessagingException("Exception calculating bodyhash: " + e.getMessage(), e);
        }
        String signatureHeader = signer.sign(headers, bhj);
        // Unfortunately JavaMail does not give us a method to add headers
        // on top.
        // message.addHeaderLine(signatureHeader);
        prependHeader(message, signatureHeader);
    } catch (PermFailException e) {
        throw new MessagingException("PermFail while signing: " + e.getMessage(), e);
    }

}

From source file:com.openkm.servlet.frontend.DownloadServlet.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.debug("service({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String path = request.getParameter("path");
    String uuid = request.getParameter("uuid");
    String[] uuidList = request.getParameterValues("uuidList");
    String[] pathList = request.getParameterValues("pathList");
    String checkout = request.getParameter("checkout");
    String ver = request.getParameter("ver");
    boolean export = request.getParameter("export") != null;
    boolean inline = request.getParameter("inline") != null;
    File tmp = File.createTempFile("okm", ".tmp");
    InputStream is = null;/*from   w  ww. j a  v  a  2s  .  c  o m*/
    updateSessionManager(request);

    try {
        // Now an document can be located by UUID
        if (uuid != null && !uuid.equals("")) {
            uuid = FormatUtil.sanitizeInput(uuid);
            path = OKMRepository.getInstance().getNodePath(null, uuid);
        } else if (path != null) {
            path = FormatUtil.sanitizeInput(path);
            path = new String(path.getBytes("ISO-8859-1"), "UTF-8");
        }

        if (export) {
            if (exportZip) {
                FileOutputStream os = new FileOutputStream(tmp);
                String fileName = "export.zip";

                if (path != null) {
                    exportFolderAsZip(path, os);
                    fileName = PathUtils.getName(path) + ".zip";
                } else if (uuidList != null || pathList != null) {
                    // Export into a zip file multiple documents
                    List<String> paths = new ArrayList<String>();

                    if (uuidList != null) {
                        for (String uuidElto : uuidList) {
                            String foo = new String(uuidElto.getBytes("ISO-8859-1"), "UTF-8");
                            paths.add(OKMRepository.getInstance().getNodePath(null, foo));
                        }
                    } else if (pathList != null) {
                        for (String pathElto : pathList) {
                            String foo = new String(pathElto.getBytes("ISO-8859-1"), "UTF-8");
                            paths.add(foo);
                        }
                    }

                    fileName = PathUtils.getName(PathUtils.getParent(paths.get(0)));
                    exportDocumentsAsZip(paths, os, fileName);
                    fileName += ".zip";
                }

                os.flush();
                os.close();
                is = new FileInputStream(tmp);

                // Send document
                WebUtils.sendFile(request, response, fileName, MimeTypeConfig.MIME_ZIP, inline, is);
            } else if (exportJar) {
                // Get document
                FileOutputStream os = new FileOutputStream(tmp);
                exportFolderAsJar(path, os);
                os.flush();
                os.close();
                is = new FileInputStream(tmp);

                // Send document
                String fileName = PathUtils.getName(path) + ".jar";
                WebUtils.sendFile(request, response, fileName, "application/x-java-archive", inline, is);
            }
        } else {
            if (OKMDocument.getInstance().isValid(null, path)) {
                // Get document
                Document doc = OKMDocument.getInstance().getProperties(null, path);

                if (ver != null && !ver.equals("")) {
                    is = OKMDocument.getInstance().getContentByVersion(null, path, ver);
                } else {
                    is = OKMDocument.getInstance().getContent(null, path, checkout != null);
                }

                // Send document
                String fileName = PathUtils.getName(doc.getPath());
                WebUtils.sendFile(request, response, fileName, doc.getMimeType(), inline, is);
            } else if (OKMMail.getInstance().isValid(null, path)) {
                // Get mail
                Mail mail = OKMMail.getInstance().getProperties(null, path);

                // Send mail
                ServletOutputStream sos = response.getOutputStream();
                String fileName = PathUtils.getName(mail.getSubject() + ".eml");
                WebUtils.prepareSendFile(request, response, fileName, MimeTypeConfig.MIME_EML, inline);
                response.setContentLength((int) mail.getSize());
                MimeMessage m = MailUtils.create(null, mail);
                m.writeTo(sos);
                sos.flush();
                sos.close();
            }
        }
    } catch (PathNotFoundException e) {
        log.warn(e.getMessage(), e);
        throw new ServletException(new OKMException(
                ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_PathNotFound),
                e.getMessage()));
    } catch (RepositoryException e) {
        log.warn(e.getMessage(), e);
        throw new ServletException(
                new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_Repository),
                        e.getMessage()));
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new ServletException(new OKMException(
                ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_IO), e.getMessage()));
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        throw new ServletException(new OKMException(
                ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_Database), e.getMessage()));
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new ServletException(new OKMException(
                ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_General), e.getMessage()));
    } finally {
        IOUtils.closeQuietly(is);
        FileUtils.deleteQuietly(tmp);
    }

    log.debug("service: void");
}

From source file:com.adaptris.core.mail.RawMailConsumer.java

@Override
protected List<AdaptrisMessage> createMessages(MimeMessage mime) throws MailException, CoreException {

    List<AdaptrisMessage> result = new ArrayList<AdaptrisMessage>();
    try {//from   w w w.  j a v a  2s.  c  om
        log.trace("Start Processing [{}]", mime.getMessageID());
        AdaptrisMessage msg = defaultIfNull(getMessageFactory()).newMessage();
        String uuid = msg.getUniqueId();
        try (OutputStream out = msg.getOutputStream()) {
            mime.writeTo(out);
        }
        if (useEmailMessageIdAsUniqueId()) {
            msg.setUniqueId(StringUtils.defaultIfBlank(mime.getMessageID(), uuid));
        }
        headerHandler().handle(mime, msg);
        result.add(msg);
    } catch (MessagingException | IOException e) {
        throw new MailException(e.getMessage(), e);
    }
    return result;
}

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);//w  w w  .  j a  v a  2s . c om

    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.xwiki.mail.test.ui.MailTest.java

private void assertReceivedMessages(int expectedMatchingCount, String... expectedLines) throws Exception {
    StringBuilder builder = new StringBuilder();
    int count = 0;
    for (MimeMessage message : this.mail.getReceivedMessages()) {
        if (this.alreadyAssertedMessages.contains(message.getMessageID())) {
            continue;
        }//from w  w  w .  ja va  2 s  . c  o  m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        message.writeTo(baos);
        String fullContent = baos.toString();
        boolean match = true;
        for (int i = 0; i < expectedLines.length; i++) {
            if (!fullContent.contains(expectedLines[i])) {
                match = false;
                break;
            }
        }
        if (!match) {
            builder.append("- Content [" + fullContent + "]").append('\n');
        } else {
            count++;
        }
        this.alreadyAssertedMessages.add(message.getMessageID());
    }
    StringBuilder expected = new StringBuilder();
    for (int i = 0; i < expectedLines.length; i++) {
        expected.append("- '" + expectedLines[i] + "'").append('\n');
    }
    assertEquals(
            String.format(
                    "We got [%s] mails matching the expected content instead of [%s]. We were expecting "
                            + "the following content:\n%s\nWe got the following:\n%s",
                    count, expectedMatchingCount, expected.toString(), builder.toString()),
            expectedMatchingCount, count);
}

From source file:eu.peppol.outbound.transmission.As2MessageSender.java

/**
 * Handles the HTTP 200 POST response (the MDN with status indications)
 *
 * @param transmissionId the transmissionId (used in HTTP headers as Message-ID)
 * @param outboundMic    the calculated mic of the payload (should be verified against the one returned in MDN)
 * @param postResponse   the http response to be decoded as MDN
 * @return//w ww  . j av  a 2 s  .c om
 */
MimeMessage handleTheHttpResponse(TransmissionId transmissionId, Mic outboundMic,
        CloseableHttpResponse postResponse, SmpLookupManager.PeppolEndpointData peppolEndpointData) {

    try {

        HttpEntity entity = postResponse.getEntity(); // Any textual results?
        if (entity == null) {
            throw new IllegalStateException(
                    "No contents in HTTP response with rc=" + postResponse.getStatusLine().getStatusCode());
        }

        String contents = EntityUtils.toString(entity);

        if (traceEnabled) {
            log.debug("HTTP-headers:");
            Header[] allHeaders = postResponse.getAllHeaders();
            for (Header header : allHeaders) {
                log.debug("" + header.getName() + ": " + header.getValue());
            }
            log.debug("Contents:\n" + contents);
            log.debug("---------------------------");
        }

        Header contentTypeHeader = postResponse.getFirstHeader("Content-Type");
        if (contentTypeHeader == null) {
            throw new IllegalStateException("No Content-Type header in response, probably a server error");
        }
        String contentType = contentTypeHeader.getValue();

        MimeMessage mimeMessage = null;
        try {
            mimeMessage = MimeMessageHelper.parseMultipart(contents, new MimeType(contentType));

            try {
                mimeMessage.writeTo(System.out);
            } catch (MessagingException e) {
                throw new IllegalStateException("Unable to print mime message");
            }

        } catch (MimeTypeParseException e) {
            throw new IllegalStateException("Invalid Content-Type header");
        }

        // verify the signature of the MDN, we warn about dodgy signatures
        try {
            SignedMimeMessage signedMimeMessage = new SignedMimeMessage(mimeMessage);
            X509Certificate cert = signedMimeMessage.getSignersX509Certificate();
            cert.checkValidity();

            // Verify if the certificate used by the receiving Access Point in
            // the response message does not match its certificate published by the SMP
            if (peppolEndpointData.getCommonName() == null || !CommonName
                    .valueOf(cert.getSubjectX500Principal()).equals(peppolEndpointData.getCommonName())) {
                throw new CertificateException(
                        "Common name in certificate from SMP does not match common name in AP certificate");
            }

            log.debug("MDN signature was verfied for : " + cert.getSubjectDN().toString());
        } catch (Exception ex) {
            log.warn("Exception when verifying MDN signature : " + ex.getMessage());
        }

        // Verifies the actual MDN
        MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage);
        String msg = mdnMimeMessageInspector.getPlainTextPartAsText();

        if (mdnMimeMessageInspector.isOkOrWarning(outboundMic)) {

            return mimeMessage;
        } else {
            log.error("AS2 transmission failed with some error message, msg :" + msg);
            log.error(contents);
            throw new IllegalStateException("AS2 transmission failed : " + msg);
        }

    } catch (IOException e) {
        throw new IllegalStateException("Unable to obtain the contents of the response: " + e.getMessage(), e);
    } finally {
        try {
            postResponse.close();
        } catch (IOException e) {
            throw new IllegalStateException("Unable to close http connection: " + e.getMessage(), e);
        }
    }

}