/**
   * @param auth
   * @param msg
   * @param request
   * @throws Exception
   */
  private void saveDraft(AuthProfile auth, MimeMessage msg, HttpServletRequest request)
      throws Exception {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    msg.writeTo(bos);
    byte bMsg[] = bos.toByteArray();

    // serialize the message byte array
    ObjectOutputStream os = new ObjectOutputStream(bos);
    os.writeObject(bMsg);

    // create an email db item
    MsgDbObject item = new MsgDbObject();
    item.setEmail(bMsg);
    String md5Header = new String(MD5.getHashString(bMsg)).toUpperCase(new Locale("en", "US"));

    ConnectionMetaHandler handler = getConnectionHandler(request);
    ConnectionProfile profile = getConnectionProfile(request);

    FolderControllerFactory factory = new FolderControllerFactory(auth, profile, handler);
    FolderController foldCont = factory.getFolderController();
    FolderDbObject fItem = foldCont.getDraftsFolder();

    item.setUniqueId(md5Header);
    item.setFolderId(fItem.getId());
    item.setUnread(new Boolean(false));
    item.setUsername(auth.getUsername());
    item.setMsgSize(new Long(bMsg.length));

    // save the email db item.
    MailControllerFactory mailFact =
        new MailControllerFactory(auth, profile, handler, fItem.getFolderName());
    MailController mailCont = mailFact.getMailController();
    mailCont.appendEmail(item);
  }
  public static void main(String args[]) throws Exception {
    //
    // create the generator for creating an smime/compressed message
    //
    SMIMECompressedGenerator gen = new SMIMECompressedGenerator();

    //
    // create the base for our message
    //
    MimeBodyPart msg = new MimeBodyPart();

    msg.setText("Hello world!");

    MimeBodyPart mp = gen.generate(msg, new ZlibCompressor());

    //
    // Get a Session object and create the mail message
    //
    Properties props = System.getProperties();
    Session session = Session.getDefaultInstance(props, null);

    Address fromUser = new InternetAddress("\"Eric H. Echidna\"<*****@*****.**>");
    Address toUser = new InternetAddress("*****@*****.**");

    MimeMessage body = new MimeMessage(session);
    body.setFrom(fromUser);
    body.setRecipient(Message.RecipientType.TO, toUser);
    body.setSubject("example compressed message");
    body.setContent(mp.getContent(), mp.getContentType());
    body.saveChanges();

    body.writeTo(new FileOutputStream("compressed.message"));
  }
  @Override
  public final void pre_commit(boolean dirty) throws DataFault {

    /* All commits to this object forces a write back of the message
     * as it is hard to tell if the message has changed.
     *
     */
    hash = -1;
    try {
      if (m != null) {
        // StreamData sd = new MessageStreamData(m);
        StreamData sd = new ByteArrayStreamData();
        // can't call saveChanges on imported imap message
        if (auto_save) {
          m.saveChanges();
        }
        m.writeTo(sd.getOutputStream());
        // getLogger().debug("update value to "+sd);
        record.setProperty(MESSAGE, sd);
        m = null; // force re-read
      }
    } catch (Exception e) {
      getContext().error(e, "Error writing mail message");
    }
  }
  public void setMessage(MimeMessage message) {
    if (message != null) {
      // serialize the message
      this.message = message;
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      try {
        message.writeTo(baos);
        baos.flush();
        serializedBytes = baos.toByteArray();
        this.contentType = message.getContentType();

        // see if this is a multi-part message
        Object content = message.getContent();
        if (content instanceof Multipart) {
          Multipart mp = (Multipart) content;
          this.parts = mp.getCount();
        } else {
          this.parts = 0;
        }
      } catch (MessagingException e) {
        Debug.logError(e, module);
      } catch (IOException e) {
        Debug.logError(e, module);
      } finally {
        try {
          baos.close();
        } catch (IOException e) {
          Debug.logError(e, module);
        }
      }
    }
  }
 /**
  * Create a Message from an email
  *
  * @param email Email to be set to raw of message
  * @return Message containing base64 encoded email.
  * @throws IOException
  * @throws MessagingException
  */
 private Message createMessageWithEmail(MimeMessage email) throws MessagingException, IOException {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   email.writeTo(baos);
   String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
   Message message = new Message();
   message.setRaw(encodedEmail);
   return message;
 }
Example #6
0
 public OutputStream exportMessage(String username, String accountId, Message message)
     throws Exception {
   Properties props = System.getProperties();
   Session session = Session.getDefaultInstance(props, null);
   MimeMessage mimeMessage = new MimeMessage(session);
   mimeMessage = Utils.mergeToMimeMessage(message, mimeMessage);
   OutputStream outputStream = new ByteArrayOutputStream();
   mimeMessage.writeTo(outputStream);
   return outputStream;
 }
Example #7
0
  /**
   * Extracts an email from the queue and consumes the email.
   *
   * @return Text of the email
   * @throws MessagingException
   * @throws IOException
   */
  protected String popEmail() throws MessagingException, IOException {
    List<WiserMessage> wiserMessageList = wiser.getMessages();
    if (wiserMessageList.isEmpty()) {
      return null;
    }
    WiserMessage wiserMessage = wiserMessageList.get(wiserMessageList.size() - 1);
    wiserMessageList.remove(wiserMessageList.size() - 1);
    MimeMessage message = wiserMessage.getMimeMessage();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    message.writeTo(os);
    String body = os.toString();

    return body;
  }
Example #8
0
 private void writeFailureWithExplanation(
     HttpServletResponse response, Exception e, MimeMessage mimeMessage, MdnData mdnData)
     throws IOException {
   try {
     setHeadersForMDN(response, mdnData, mimeMessage);
     response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
     mimeMessage.writeTo(response.getOutputStream());
     log.error("Returned MDN with failure: " + MimeMessageHelper.toString(mimeMessage), e);
     log.error(
         "---------- REQUEST FAILURE INFORMATION ENDS HERE --------------"); // Being helpful to
                                                                             // those who must read
                                                                             // the error logs
   } catch (MessagingException e1) {
     String msg = "Unable to return failure to sender; " + e1.getMessage();
     log.error(msg);
     response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
     response.getWriter().write(msg);
   }
 }
  private void dump(MimeMessage m) throws MessagingException, IOException, FileNotFoundException {

    File file = new File(m.getMessageNumber() + ".eml");

    // InputStream in = m.getInputStream();
    //
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
    //
    // byte[] buffer = new byte[32 * 1024];
    // int bytesRead = 0;
    // while ((bytesRead = in.read(buffer)) != -1) {
    // out.write(buffer, 0, bytesRead);
    // }

    m.writeTo(out);

    // in.close();
    out.close();
  }
 @Override
 public void marshal(Exchange exchange, Object graph, OutputStream stream)
     throws NoTypeConversionAvailableException, MessagingException, IOException {
   if (multipartWithoutAttachment || headersInline || exchange.getIn().hasAttachments()) {
     ContentType contentType = getContentType(exchange);
     // remove the Content-Type header. This will be wrong afterwards...
     exchange.getOut().removeHeader(Exchange.CONTENT_TYPE);
     byte[] bodyContent = ExchangeHelper.convertToMandatoryType(exchange, byte[].class, graph);
     Session session = Session.getInstance(System.getProperties());
     MimeMessage mm = new MimeMessage(session);
     MimeMultipart mp = new MimeMultipart(multipartSubType);
     BodyPart part = new MimeBodyPart();
     writeBodyPart(bodyContent, part, contentType);
     mp.addBodyPart(part);
     for (Map.Entry<String, Attachment> entry :
         exchange.getIn().getAttachmentObjects().entrySet()) {
       String attachmentFilename = entry.getKey();
       Attachment attachment = entry.getValue();
       part = new MimeBodyPart();
       part.setDataHandler(attachment.getDataHandler());
       part.setFileName(MimeUtility.encodeText(attachmentFilename, "UTF-8", null));
       String ct = attachment.getDataHandler().getContentType();
       contentType = new ContentType(ct);
       part.setHeader(CONTENT_TYPE, ct);
       if (!contentType.match("text/*") && binaryContent) {
         part.setHeader(CONTENT_TRANSFER_ENCODING, "binary");
       }
       // Set headers to the attachment
       for (String headerName : attachment.getHeaderNames()) {
         List<String> values = attachment.getHeaderAsList(headerName);
         for (String value : values) {
           part.setHeader(headerName, value);
         }
       }
       mp.addBodyPart(part);
       exchange.getOut().removeAttachment(attachmentFilename);
     }
     mm.setContent(mp);
     // copy headers if required and if the content can be converted into
     // a String
     if (headersInline && includeHeaders != null) {
       for (Map.Entry<String, Object> entry : exchange.getIn().getHeaders().entrySet()) {
         if (includeHeaders.matcher(entry.getKey()).matches()) {
           String headerStr =
               ExchangeHelper.convertToType(exchange, String.class, entry.getValue());
           if (headerStr != null) {
             mm.setHeader(entry.getKey(), headerStr);
           }
         }
       }
     }
     mm.saveChanges();
     Enumeration<?> hl = mm.getAllHeaders();
     List<String> headers = new ArrayList<String>();
     if (!headersInline) {
       while (hl.hasMoreElements()) {
         Object ho = hl.nextElement();
         if (ho instanceof Header) {
           Header h = (Header) ho;
           exchange.getOut().setHeader(h.getName(), h.getValue());
           headers.add(h.getName());
         }
       }
       mm.saveChanges();
     }
     mm.writeTo(stream, headers.toArray(new String[0]));
   } else {
     // keep the original data
     InputStream is = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph);
     IOHelper.copyAndCloseInput(is, stream);
   }
 }
 private String getContent(MimeMessage msg) throws Exception {
   ByteArrayOutputStream buf = new ByteArrayOutputStream();
   msg.writeTo(buf);
   return new String(buf.toByteArray());
 }
Example #12
0
  /**
   * Receives the POST'ed AS2 message.
   *
   * <p>Important to note that the HTTP headers contains the MIME headers for the payload. Since the
   * the request can only be read once, using getReader()/getInputStream()
   */
  protected void doPost(final HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    /*
    https://www.rfc-editor.org/rfc/rfc2311.txt section 3.4
    There are two formats for signed messages defined for S/MIME:
    application/pkcs7-mime and SignedData, and multipart/signed. In
    general, the multipart/signed form is preferred for sending, and
    receiving agents SHOULD be able to handle both.

       Signing Using application/pkcs7-mime and SignedData

       This signing format uses the application/pkcs7-mime MIME type. The
       steps to create this format are:

         Step 1. The MIME entity is prepared according to section 3.1

         Step 2. The MIME entity and other required data is processed into a
                 PKCS #7 object of type signedData

         Step 3. The PKCS #7 object is inserted into an
                 application/pkcs7-mime MIME entity

       The smime-type parameter for messages using application/pkcs7-mime
       and SignedData is "signed-data". The file extension for this type of
       message is ".p7m".

       Creating a multipart/signed Message

         Step 1. The MIME entity to be signed is prepared according to
                 section 3.1, taking special care for clear-signing.

         Step 2. The MIME entity is presented to PKCS #7 processing in order
                 to obtain an object of type signedData with an empty
                 contentInfo field.

         Step 3. The MIME entity is inserted into the first part of a
                 multipart/signed message with no processing other than that
                 described in section 3.1.

         Step 4. Transfer encoding is applied to the detached signature and
                 it is inserted into a MIME entity of type
                 application/pkcs7-signature

         Step 5. The MIME entity of the application/pkcs7-signature is
                 inserted into the second part of the multipart/signed
                 entity

       The multipart/signed Content type has two required parameters: the
       protocol parameter and the micalg parameter.

       The protocol parameter MUST be "application/pkcs7-signature". Note
       that quotation marks are required around the protocol parameter
       because MIME requires that the "/" character in the parameter value
       MUST be quoted.

    */

    InternetHeaders headers = copyHttpHeadersIntoMap(request);

    // Receives the data, validates the headers, signature etc., invokes the persistence handler
    // and finally returns the MdnData to be sent back to the caller
    try {

      // Performs the actual reception of the message by parsing the HTTP POST request
      MdnData mdnData =
          inboundMessageReceiver.receive(
              headers,
              request.getInputStream(),
              messageRepository,
              rawStatisticsRepository,
              ourAccessPointIdentifier);

      // Creates the S/MIME message to be returned to the sender
      MimeMessage mimeMessage = mdnMimeMessageFactory.createMdn(mdnData, headers);

      // Add MDN headers to http response
      setHeadersForMDN(response, mdnData, mimeMessage);
      response.setStatus(HttpServletResponse.SC_OK);

      // Try to write the MDN mime message to http response
      try {
        mimeMessage.writeTo(response.getOutputStream());
        response.getOutputStream().flush();
        log.debug("Served request, status=OK:\n" + MimeMessageHelper.toString(mimeMessage));
        log.debug("------------- INFO ON PROCESSED REQUEST ENDS HERE -----------");
      } catch (MessagingException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().write("Severe error during write of MDN " + e.getMessage());
      }

    } catch (ErrorWithMdnException e) {
      // Reception of AS2 message failed, send back a MDN indicating failure (always use HTTP 200
      // for MDN)
      log.warn("AS2 reception error: " + e.getMessage(), e);
      log.warn("Returning negative MDN with explanatory message");
      MdnData mdnData = e.getMdnData();
      MimeMessage mimeMessage = mdnMimeMessageFactory.createMdn(mdnData, headers);
      writeMimeMessageWithNegativeMdn(response, e, mimeMessage, mdnData);
    } catch (Exception e) {
      // Unexpected internal error, cannot proceed, return HTTP 500 and partly MDN to indicating the
      // problem
      log.error("Internal error occured: " + e.getMessage(), e);
      log.error("Attempting to return MDN with explanatory message and HTTP 500 status");
      MdnData mdnData =
          MdnData.Builder.buildProcessingErrorFromHeaders(headers, null, e.getMessage());
      MimeMessage mimeMessage = mdnMimeMessageFactory.createMdn(mdnData, headers);
      writeFailureWithExplanation(response, e, mimeMessage, mdnData);
    }
  }
Example #13
0
 // 测试生成邮件
 public static void main(String[] args) throws Exception {
   WithAttachmentMessage mail = new WithAttachmentMessage();
   Session session = Session.getDefaultInstance(new Properties());
   MimeMessage message = mail.createMessage(session);
   message.writeTo(new FileOutputStream("withAttachmentMail.eml"));
 }