private void writeMultipartToNode(Session session, Node message, MimeMultipart multipart)
     throws RepositoryException, MessagingException, IOException {
   int count = multipart.getCount();
   for (int i = 0; i < count; i++) {
     createChildNodeForPart(session, i, multipart.getBodyPart(i), message);
   }
 }
예제 #2
0
  @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);
    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[] {"*****@*****.**"}, null, cpResource, emailBody, emailSubject, ATTACHMENT_NAME);

    mailEngine.sendMessage(
        new String[] {"*****@*****.**"},
        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());
  }
예제 #3
0
  private static void readMultiPart(MultipartResult res, MimeMultipart multipart)
      throws MessagingException {
    for (int i = 0; i < multipart.getCount(); i++) {
      BodyPart part = multipart.getBodyPart(i);

      try {
        if (part.isMimeType("image/*") || part.isMimeType("application/*")) continue;
        Object content = null;
        try {
          content = part.getContent();
        } catch (UnsupportedEncodingException ex) {
          String body = ConvertUtil.inputStreamToString(part.getInputStream());
          res.body = body;
          continue;
        }

        if (part.isMimeType("text/plain")) {
          res.body = content.toString();
        } else if (part.isMimeType("text/*")) {
          res.bodyHtml = content.toString();
        } else if (content instanceof MimeMultipart) {
          readMultiPart(res, (MimeMultipart) content);
        } else if (content instanceof IMAPNestedMessage) {
          res.body = getBody((IMAPNestedMessage) content);
          return;
        } else if (content instanceof InputStream) {
          if (content instanceof IMAPInputStream) {
            String body = ConvertUtil.inputStreamToString(part.getInputStream());
            res.body = body;
          } else
            System.out.println(
                String.format(
                    "Ignoring binary content in mail: %s [%s]",
                    part.getContentType(), content.getClass()));
        } else if (part.isMimeType("message/*")) {
          res.body = content.toString();
        } else {
          System.out.println(
              String.format(
                  "Unknown content type in mail: %s [%s]",
                  part.getContentType(), content.getClass()));
        }

      } catch (IllegalStateException ex) {
        System.out.println(
            String.format("Could not read contents in mail: %s", part.getContentType()));
      } catch (UnsupportedDataTypeException ex) {
        System.out.println(
            String.format("Could not read contents in mail: %s", part.getContentType()));
      } catch (FolderClosedException ex) {
        throw ex;
      } catch (Throwable ex) {
        System.out.println(
            String.format("Error while reading mail part: %s", part.getClass().toString()));
      }
    }
  }
예제 #4
0
  public static void collectMultipartContent(MimeMultipart multipart, MBMailMessage collector)
      throws Exception {

    for (int i = 0; i < multipart.getCount(); i++) {
      BodyPart part = multipart.getBodyPart(i);

      collectPartContent(part, collector);
    }
  }
  @Override
  public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception {

    if (askGmailPassword || gmailPassword == null || gmailUsername == null) {
      Pair<String, String> credentials =
          GuiUtils.askCredentials(
              ConfigFetch.getSuperParentFrame(),
              "Enter Gmail Credentials",
              getGmailUsername(),
              getGmailPassword());
      if (credentials == null) return null;
      setGmailUsername(credentials.first());
      setGmailPassword(credentials.second());
      PluginUtils.saveProperties("conf/rockblock.props", this);
      askGmailPassword = false;
    }

    Properties props = new Properties();
    props.put("mail.store.protocol", "imaps");
    ArrayList<IridiumMessage> messages = new ArrayList<>();
    try {
      Session session = Session.getDefaultInstance(props, null);
      Store store = session.getStore("imaps");
      store.connect("imap.gmail.com", getGmailUsername(), getGmailPassword());

      Folder inbox = store.getFolder("Inbox");
      inbox.open(Folder.READ_ONLY);
      int numMsgs = inbox.getMessageCount();

      for (int i = numMsgs; i > 0; i--) {
        Message m = inbox.getMessage(i);
        if (m.getReceivedDate().before(timeSince)) {
          break;
        } else {
          MimeMultipart mime = (MimeMultipart) m.getContent();
          for (int j = 0; j < mime.getCount(); j++) {
            BodyPart p = mime.getBodyPart(j);
            Matcher matcher = pattern.matcher(p.getContentType());
            if (matcher.matches()) {
              InputStream stream = (InputStream) p.getContent();
              byte[] data = IOUtils.toByteArray(stream);
              IridiumMessage msg = process(data, matcher.group(1));
              if (msg != null) messages.add(msg);
            }
          }
        }
      }
    } catch (NoSuchProviderException ex) {
      ex.printStackTrace();
      System.exit(1);
    } catch (MessagingException ex) {
      ex.printStackTrace();
      System.exit(2);
    }

    return messages;
  }
예제 #6
0
 private static Content getJoinedContent(MimePart part) throws IOException, MessagingException {
   Content result = new Content();
   MimeMultipart mp = (MimeMultipart) part.getContent();
   for (int i = 0; i < mp.getCount(); i++) {
     MimeBodyPart p = (MimeBodyPart) mp.getBodyPart(i);
     result.merge(processPart(p, part));
   }
   return result;
 }
예제 #7
0
 public static String getBodyPartContentType(MimeMultipart mimeMultipart)
     throws MessagingException {
   for (int i = 0; i < mimeMultipart.getCount(); i++) {
     BodyPart bodyPart = mimeMultipart.getBodyPart(i);
     // ignore attachment
     if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
       return bodyPart.getContentType();
     }
   }
   return StringUtils.EMPTY;
 }
 @Override
 protected void verifyMessage(MimeMultipart content) throws Exception {
   assertEquals(3, content.getCount());
   verifyMessage((String) content.getBodyPart(0).getContent());
   List<String> expectedTypes = Arrays.asList("text/plain", "text/xml");
   for (int i = 0; i < 3; i++) {
     BodyPart part = content.getBodyPart(i);
     String type = part.getContentType();
     MimeType mt = new MimeType(type);
     assertTrue(expectedTypes.contains(mt.getPrimaryType() + "/" + mt.getSubType()));
   }
 }
예제 #9
0
 private static Content getContentOfBestPart(MimePart part, MimePart parent)
     throws IOException, MessagingException {
   MimeBodyPart best = null;
   MimeMultipart mp = (MimeMultipart) part.getContent();
   for (int i = 0; i < mp.getCount(); i++) {
     // Prefer HTML if the parent is a multipart/related part which may contain
     // inline images, because text/plain cannot embed the images.
     boolean isHtmlPreferred = parent != null && parent.isMimeType(MimeType.MULTIPART_RELATED);
     best = better((MimeBodyPart) mp.getBodyPart(i), best, isHtmlPreferred);
   }
   return processPart(best, part);
 }
예제 #10
0
 private MimeMultipart getMultipartMessage(DataSource ds) {
   MimeMultipart mmp;
   try {
     mmp = new MimeMultipart(ds);
     // if it's not a real mimemultipart, getCount crashes, which is too late, so crash here
     // instead
     mmp.getCount();
     return mmp;
   } catch (MessagingException e) {
     logger.info("Can not create multipart.");
     return null;
   }
 }
예제 #11
0
 private static Content getContentWithAttachments(MimePart part)
     throws MessagingException, IOException {
   Content result = new Content();
   String rootId = new ContentType(part.getContentType()).getParameter("start");
   MimeMultipart mp = (MimeMultipart) part.getContent();
   for (int i = 0; i < mp.getCount(); i++) {
     MimePart p = (MimePart) mp.getBodyPart(i);
     if (isRootPart(p, i, rootId)) {
       result = result.merge(processPart(p, part));
     } else {
       result.attachments.add(p);
     }
   }
   return result;
 }
예제 #12
0
 private static String getBody(Part msg, String contentType)
     throws MessagingException, IOException, SAXException {
   if (msg.getContentType().startsWith(contentType)) {
     return msg.getContent().toString();
   } else if (msg.getContentType().startsWith("multipart/")) {
     MimeMultipart multi = (MimeMultipart) msg.getContent();
     for (int i = 0; i < multi.getCount(); i++) {
       BodyPart part = multi.getBodyPart(i);
       String content = getBody(part);
       if (content != null) {
         return content;
       }
     }
   }
   return null;
 }
예제 #13
0
 public static InputStream getAttachment(Part part, String filename) {
   try {
     if (filename.equals(part.getFileName())) return part.getInputStream();
     if (part.getContentType().toLowerCase().startsWith("multipart")) {
       MimeMultipart multipart;
       multipart = (MimeMultipart) part.getContent();
       int count = multipart.getCount();
       for (int i = 0; i < count; i++) {
         InputStream in = getAttachment(multipart.getBodyPart(i), filename);
         if (in != null) return in;
       }
     }
   } catch (Throwable ex) {
     throw new RuntimeException(ex);
   }
   return null;
 }
예제 #14
0
 @Override
 public void processInputStream(InputStream is) throws Exception {
   try {
     MimeMultipart multiPart =
         new MimeMultipart(new ByteArrayDataSource(is, MULTI_PART_MIME_TYPE));
     int count = multiPart.getCount();
     for (int part = 0; part < count; part++) {
       BodyPart body = multiPart.getBodyPart(part);
       if (body.isMimeType(OUTPUT_MIME_TYPE)) {
         this.inputStream = body.getInputStream();
         break;
       }
     }
   } catch (Exception e) {
     this.inputStream = getErrorResponseStream();
   }
 }
  /**
   * Retrieve message from retriever and check the attachment and text content
   *
   * @param retriever Retriever to read from
   * @param to Account to retrieve
   */
  private void retrieveAndCheck(Retriever retriever, String to)
      throws MessagingException, IOException {
    Message[] messages = retriever.getMessages(to);
    assertEquals(1, messages.length);
    Message message = messages[0];
    assertTrue(message.getContentType().startsWith("multipart/mixed"));
    MimeMultipart body = (MimeMultipart) message.getContent();
    assertTrue(body.getContentType().startsWith("multipart/mixed"));
    assertEquals(2, body.getCount());

    // Message text
    final BodyPart textPart = body.getBodyPart(0);
    String text = (String) textPart.getContent();
    assertEquals(createLargeString(), text);

    final BodyPart attachment = body.getBodyPart(1);
    assertTrue(attachment.getContentType().equalsIgnoreCase("application/blubb; name=file"));
    InputStream attachmentStream = (InputStream) attachment.getContent();
    byte[] bytes = IOUtils.toByteArray(attachmentStream);
    assertArrayEquals(createLargeByteArray(), bytes);
  }
예제 #16
0
  @Test
  public void testSmtpServerReceiveMultipart() throws Exception {
    assertEquals(0, greenMail.getReceivedMessages().length);

    String subject = GreenMailUtil.random();
    String body = GreenMailUtil.random();
    GreenMailUtil.sendAttachmentEmail(
        "*****@*****.**",
        "*****@*****.**",
        subject,
        body,
        new byte[] {0, 1, 2},
        "image/gif",
        "testimage_filename",
        "testimage_description",
        ServerSetupTest.SMTP);
    greenMail.waitForIncomingEmail(1500, 1);
    Message[] emails = greenMail.getReceivedMessages();
    assertEquals(1, emails.length);
    assertEquals(subject, emails[0].getSubject());

    Object o = emails[0].getContent();
    assertTrue(o instanceof MimeMultipart);
    MimeMultipart mp = (MimeMultipart) o;
    assertEquals(2, mp.getCount());
    BodyPart bp;
    bp = mp.getBodyPart(0);
    assertEquals(body, GreenMailUtil.getBody(bp).trim());

    bp = mp.getBodyPart(1);
    assertEquals("AAEC", GreenMailUtil.getBody(bp).trim());

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    GreenMailUtil.copyStream(bp.getInputStream(), bout);
    byte[] gif = bout.toByteArray();
    for (int i = 0; i < gif.length; i++) {
      assertEquals(i, gif[i]);
    }
  }
예제 #17
0
 public static Set<String> getAttachmentFilenames(Part part) {
   try {
     Set<String> result = new HashSet<String>();
     if (part.getContentType().toLowerCase().startsWith("multipart")) {
       MimeMultipart multipart;
       try {
         multipart = (MimeMultipart) part.getContent();
         int count = multipart.getCount();
         for (int i = 0; i < count; i++) {
           result.addAll(getAttachmentFilenames(multipart.getBodyPart(i)));
         }
       } catch (NullPointerException ex) {
         // part.getContent() throws NullPointerException
         LOG.info(ex);
       }
     } else {
       String filename = part.getFileName();
       if (filename != null) result.add(Str.decodeQuotedPrintable(filename));
     }
     return result;
   } catch (Exception ex) {
     throw new RuntimeException(ex);
   }
 }
예제 #18
0
  @Test
  public void sendMimeMail() throws InterruptedException, MessagingException, IOException {
    mimeMailService.sendNotificationMail("calvin");

    greenMail.waitForIncomingEmail(2000, 1);
    MimeMessage[] messages = greenMail.getReceivedMessages();
    MimeMessage message = messages[messages.length - 1];

    assertEquals("*****@*****.**", message.getFrom()[0].toString());
    assertEquals("用户修改通知", message.getSubject());

    MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();

    assertEquals(2, mimeMultipart.getCount());

    // Html格式的主邮件
    String mainPartText = getMainPartText(mimeMultipart.getBodyPart(0));
    System.out.println(mainPartText);
    assertTrue(mainPartText.contains("<h1>用户calvin被修改.</h1>"));

    // 附件
    assertEquals(
        "Hello,i am a attachment.", GreenMailUtil.getBody(mimeMultipart.getBodyPart(1)).trim());
  }
예제 #19
0
 @Override
 public ExecutionRequest readFrom(
     Class<ExecutionRequest> arg0,
     Type arg1,
     Annotation[] arg2,
     MediaType arg3,
     MultivaluedMap<String, String> headers,
     InputStream in)
     throws IOException, WebApplicationException {
   ExecutionRequest req = null;
   try {
     List<String> ctypes = headers.get("Content-Type");
     String ctype = ctypes.get(0);
     // we need to copy first the stream into a file otherwise it may
     // happen that
     // javax.mail fail to receive some parts - I am not sure why -
     // perhaps the stream is no more available when javax.mail need it?
     File tmp = File.createTempFile("nx-automation-mp-upload-", ".tmp");
     FileUtils.copyToFile(in, tmp);
     // get the input from the saved file
     in = new SharedFileInputStream(tmp);
     try {
       MimeMultipart mp = new MimeMultipart(new InputStreamDataSource(in, ctype));
       BodyPart part = mp.getBodyPart(0); // use content ids
       InputStream pin = part.getInputStream();
       JsonParser jp = factory.createJsonParser(pin);
       req = JsonRequestReader.readRequest(jp, headers, getCoreSession());
       int cnt = mp.getCount();
       if (cnt == 2) { // a blob
         req.setInput(readBlob(request, mp.getBodyPart(1)));
       } else if (cnt > 2) { // a blob list
         BlobList blobs = new BlobList();
         for (int i = 1; i < cnt; i++) {
           blobs.add(readBlob(request, mp.getBodyPart(i)));
         }
         req.setInput(blobs);
       } else {
         log.error("Not all parts received.");
         for (int i = 0; i < cnt; i++) {
           log.error(
               "Received parts: "
                   + mp.getBodyPart(i).getHeader("Content-ID")[0]
                   + " -> "
                   + mp.getBodyPart(i).getContentType());
         }
         throw WebException.newException(
             new IllegalStateException("Received only " + cnt + " part in a multipart request"));
       }
     } finally {
       try {
         in.close();
       } catch (IOException e) {
         // do nothing
       }
       tmp.delete();
     }
   } catch (MessagingException | IOException e) {
     throw WebException.newException("Failed to parse multipart request", e);
   }
   return req;
 }
예제 #20
0
  @Test
  public void testTextMailMessageSpecialCharacters() throws MessagingException, IOException {

    String uuid = java.util.UUID.randomUUID().toString();
    String subject = "Special Char ü from ${version} Mail - " + uuid;
    String version = "Seam 3";
    String mergedSubject = "Special Char ü from " + version + " Mail - " + uuid;
    String specialTextBody = "This is a Text Body with a special character - ü - ${version}";
    String mergedSpecialTextBody = "This is a Text Body with a special character - ü - " + version;

    String messageId = "*****@*****.**";

    Wiser wiser = new Wiser(mailConfig.getServerPort());
    wiser.setHostname(mailConfig.getServerHost());
    try {
      wiser.start();

      person.setName(toName);
      person.setEmail(toAddress);

      mailMessage
          .get()
          .from(MailTestUtil.getAddressHeader(fromName, fromAddress))
          .replyTo(replyToAddress)
          .to(MailTestUtil.getAddressHeader(toName, toAddress))
          .subject(new FreeMarkerTemplate(subject))
          .bodyText(new FreeMarkerTemplate(specialTextBody))
          .importance(MessagePriority.HIGH)
          .messageId(messageId)
          .put("version", version)
          .send(session.get());
    } finally {
      stop(wiser);
    }

    Assert.assertTrue(
        "Didn't receive the expected amount of messages. Expected 1 got "
            + wiser.getMessages().size(),
        wiser.getMessages().size() == 1);

    MimeMessage mess = wiser.getMessages().get(0).getMimeMessage();

    System.out.println(subject);
    System.out.println(MimeUtility.decodeText(MimeUtility.unfold(mess.getHeader("Subject", null))));
    System.out.println(mergedSubject);

    Assert.assertEquals(
        "Subject has been modified",
        mergedSubject,
        MimeUtility.decodeText(MimeUtility.unfold(mess.getHeader("Subject", null))));

    MimeMultipart mixed = (MimeMultipart) mess.getContent();
    BodyPart text = mixed.getBodyPart(0);

    Assert.assertTrue(mixed.getContentType().startsWith("multipart/mixed"));
    Assert.assertEquals(1, mixed.getCount());

    Assert.assertTrue(text.getContentType().startsWith("text/plain; charset=UTF-8"));
    Assert.assertEquals(
        mergedSpecialTextBody, MimeUtility.decodeText(MailTestUtil.getStringContent(text)));
  }
예제 #21
0
  @Test
  public void testFreeMarkerHTMLTextAltMailMessage() throws MessagingException, IOException {
    String subject = "HTML+Text Message from Seam Mail - " + java.util.UUID.randomUUID().toString();
    String version = "Seam 3";
    EmailMessage emailMessage;

    Wiser wiser = new Wiser(mailConfig.getServerPort());
    wiser.setHostname(mailConfig.getServerHost());
    try {
      wiser.start();

      person.setName(toName);
      person.setEmail(toAddress);

      emailMessage =
          mailMessage
              .get()
              .from(MailTestUtil.getAddressHeader(fromName, fromAddress))
              .to(MailTestUtil.getAddressHeader(person.getName(), person.getEmail()))
              .subject(subject)
              .put("person", person)
              .put("version", version)
              .bodyHtmlTextAlt(
                  new FreeMarkerTemplate(
                      resourceProvider.loadResourceStream("template.html.freemarker")),
                  new FreeMarkerTemplate(
                      resourceProvider.loadResourceStream("template.text.freemarker")))
              .importance(MessagePriority.LOW)
              .deliveryReceipt(fromAddress)
              .readReceipt("seam.test")
              .addAttachment(
                  "template.html.freemarker",
                  "text/html",
                  ContentDisposition.ATTACHMENT,
                  resourceProvider.loadResourceStream("template.html.freemarker"))
              .addAttachment(
                  new URLAttachment(
                      "http://design.jboss.org/seam/logo/final/seam_mail_85px.png",
                      "seamLogo.png",
                      ContentDisposition.INLINE))
              .send();
    } finally {
      stop(wiser);
    }

    Assert.assertTrue(
        "Didn't receive the expected amount of messages. Expected 1 got "
            + wiser.getMessages().size(),
        wiser.getMessages().size() == 1);

    MimeMessage mess = wiser.getMessages().get(0).getMimeMessage();

    Assert.assertEquals(
        MailTestUtil.getAddressHeader(fromName, fromAddress), mess.getHeader("From", null));
    Assert.assertEquals(
        MailTestUtil.getAddressHeader(toName, toAddress), mess.getHeader("To", null));
    Assert.assertEquals(
        "Subject has been modified", subject, MimeUtility.unfold(mess.getHeader("Subject", null)));
    Assert.assertEquals(MessagePriority.LOW.getPriority(), mess.getHeader("Priority", null));
    Assert.assertEquals(MessagePriority.LOW.getX_priority(), mess.getHeader("X-Priority", null));
    Assert.assertEquals(MessagePriority.LOW.getImportance(), mess.getHeader("Importance", null));
    Assert.assertTrue(mess.getHeader("Content-Type", null).startsWith("multipart/mixed"));

    MimeMultipart mixed = (MimeMultipart) mess.getContent();
    MimeMultipart related = (MimeMultipart) mixed.getBodyPart(0).getContent();
    MimeMultipart alternative = (MimeMultipart) related.getBodyPart(0).getContent();
    BodyPart attachment = mixed.getBodyPart(1);
    BodyPart inlineAttachment = related.getBodyPart(1);

    BodyPart textAlt = alternative.getBodyPart(0);
    BodyPart html = alternative.getBodyPart(1);

    Assert.assertTrue(mixed.getContentType().startsWith("multipart/mixed"));
    Assert.assertEquals(2, mixed.getCount());

    Assert.assertTrue(related.getContentType().startsWith("multipart/related"));
    Assert.assertEquals(2, related.getCount());

    Assert.assertTrue(html.getContentType().startsWith("text/html"));
    Assert.assertEquals(
        expectedHtmlBody(emailMessage, person.getName(), person.getEmail(), version),
        MailTestUtil.getStringContent(html));

    Assert.assertTrue(textAlt.getContentType().startsWith("text/plain"));
    Assert.assertEquals(
        expectedTextBody(person.getName(), version), MailTestUtil.getStringContent(textAlt));

    Assert.assertTrue(attachment.getContentType().startsWith("text/html"));
    Assert.assertEquals("template.html.freemarker", attachment.getFileName());

    Assert.assertTrue(inlineAttachment.getContentType().startsWith("image/png;"));
    Assert.assertEquals("seamLogo.png", inlineAttachment.getFileName());
  }
예제 #22
0
  @Override
  public Object evaluate() throws TMLExpressionException {
    Binary b = (Binary) getOperand(0);
    DataSource ds = new BinaryDataSource(b);
    Navajo result = NavajoFactory.getInstance().createNavajo();
    Message mail = NavajoFactory.getInstance().createMessage(result, "Mail");
    result.addMessage(mail);
    Message parts =
        NavajoFactory.getInstance().createMessage(result, "Parts", Message.MSG_TYPE_ARRAY);
    mail.addMessage(parts);
    try {
      MimeMultipart mmp = getMultipartMessage(ds);
      if (mmp != null) {
        for (int i = 0; i < mmp.getCount(); i++) {
          BodyPart bp = mmp.getBodyPart(i);
          String type = bp.getContentType();
          Binary partBinary = new Binary(bp.getInputStream(), false);

          if (i == 0) {
            //					Property content = NavajoFactory.getInstance().createProperty(result, "Content",
            // Property.BINARY_PROPERTY, null, 0,"",Property.DIR_OUT);
            Property mimeType =
                NavajoFactory.getInstance()
                    .createProperty(
                        result,
                        "ContentType",
                        Property.STRING_PROPERTY,
                        type,
                        0,
                        "",
                        Property.DIR_OUT);
            //					mail.addProperty(content);
            mail.addProperty(mimeType);
            //					content.setAnyValue(partBinary);
            partBinary.setMimeType(type);
          }
          Message element =
              parts.addElement(
                  NavajoFactory.getInstance()
                      .createMessage(result, "Parts", Message.MSG_TYPE_ARRAY_ELEMENT));
          Property content =
              NavajoFactory.getInstance()
                  .createProperty(
                      result, "Content", Property.BINARY_PROPERTY, null, 0, "", Property.DIR_OUT);
          element.addProperty(content);
          Property mimeType =
              NavajoFactory.getInstance()
                  .createProperty(
                      result,
                      "ContentType",
                      Property.STRING_PROPERTY,
                      type,
                      0,
                      "",
                      Property.DIR_OUT);
          element.addProperty(mimeType);
          content.setAnyValue(partBinary);
          partBinary.setMimeType(type);
          content.addSubType("browserMime=" + type);
        }
      } else {
        String type = b.guessContentType();
        MimeMessage mm =
            new MimeMessage(Session.getDefaultInstance(new Properties()), b.getDataAsStream());

        //				mm.get

        Binary body = new Binary(mm.getInputStream(), false);
        //				mm.getC
        Message element =
            parts.addElement(
                NavajoFactory.getInstance()
                    .createMessage(result, "Parts", Message.MSG_TYPE_ARRAY_ELEMENT));
        Property content =
            NavajoFactory.getInstance()
                .createProperty(
                    result, "Content", Property.BINARY_PROPERTY, null, 0, "", Property.DIR_OUT);
        element.addProperty(content);
        Property mimeType =
            NavajoFactory.getInstance()
                .createProperty(
                    result, "ContentType", Property.STRING_PROPERTY, type, 0, "", Property.DIR_OUT);
        Property messageMimeType =
            NavajoFactory.getInstance()
                .createProperty(
                    result, "ContentType", Property.STRING_PROPERTY, type, 0, "", Property.DIR_OUT);
        mail.addProperty(messageMimeType);
        element.addProperty(mimeType);
        content.setAnyValue(body);
        b.setMimeType(mm.getContentType());
        content.addSubType("browserMime=" + type);
      }
      return result;
    } catch (MessagingException e) {
      logger.error("Error: ", e);
    } catch (IOException e) {
      logger.error("Error: ", e);
    }
    return null;
  }
예제 #23
0
 /** Description of the Method */
 public boolean sendMessage() {
   MimeMultipart mp = new MimeMultipart();
   try {
     // if there is a text and an html section
     if (sendingText.getCount() > 1) {
       sendingText.setSubType("alternative");
     }
     // if we are sending attachments
     if (sendingAttachments.getCount() > 0) {
       MimeBodyPart bp = new MimeBodyPart();
       bp.setContent(sendingAttachments);
       mp.addBodyPart(bp, 0);
       bp = new MimeBodyPart();
       bp.setContent(sendingText);
       mp.addBodyPart(bp, 0);
     } else {
       mp = sendingText;
     }
     Logger.debug(this, "Getting the MailContext.");
     /*
      *
      * Get the mail session from
      *
      * the container Context
      */
     Session session = null;
     Context ctx = null;
     try {
       ctx = (Context) new InitialContext().lookup("java:comp/env");
       session = (javax.mail.Session) ctx.lookup("mail/MailSession");
     } catch (Exception e1) {
       try {
         Logger.debug(this, "Using the jndi intitialContext().");
         ctx = new InitialContext();
         session = (javax.mail.Session) ctx.lookup("mail/MailSession");
       } catch (Exception e) {
         Logger.error(this, "Exception occured finding a mailSession in JNDI context.");
         Logger.error(this, e1.getMessage(), e1);
         return false;
       }
     }
     if (session == null) {
       Logger.debug(this, "No Mail Session Available.");
       return false;
     }
     Logger.debug(
         this, "Delivering mail using: " + session.getProperty("mail.smtp.host") + " as server.");
     MimeMessage message = new MimeMessage(session);
     message.addHeader("X-RecipientId", String.valueOf(getRecipientId()));
     if ((fromEmail != null) && (fromName != null) && (0 < fromEmail.trim().length())) {
       message.setFrom(new InternetAddress(fromEmail, fromName));
     } else if ((fromEmail != null) && (0 < fromEmail.trim().length())) {
       message.setFrom(new InternetAddress(fromEmail));
     }
     if (toName != null) {
       String[] recipients = toEmail.split("[;,]");
       for (String recipient : recipients) {
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient, toName));
       }
     } else {
       String[] recipients = toEmail.split("[;,]");
       for (String recipient : recipients) {
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
       }
     }
     if (UtilMethods.isSet(cc)) {
       String[] recipients = cc.split("[;,]");
       for (String recipient : recipients) {
         message.addRecipient(Message.RecipientType.CC, new InternetAddress(recipient));
       }
     }
     if (UtilMethods.isSet(bcc)) {
       String[] recipients = bcc.split("[;,]");
       for (String recipient : recipients) {
         message.addRecipient(Message.RecipientType.BCC, new InternetAddress(recipient));
       }
     }
     message.setSubject(subject, encoding);
     message.setContent(mp);
     Transport.send(message);
     result = "Send Ok";
     return true;
   } catch (javax.mail.SendFailedException f) {
     String error = String.valueOf(f);
     errorMessage =
         error.substring(
             error.lastIndexOf("javax.mail.SendFailedException:")
                 + "javax.mail.SendFailedException:".length(),
             (error.length() - 1));
     result = "Failed:" + error;
     Logger.error(Mailer.class, f.toString(), f);
     return false;
   } catch (MessagingException f) {
     String error = String.valueOf(f);
     errorMessage =
         error.substring(
             error.lastIndexOf("javax.mail.MessagingException:")
                 + "javax.mail.MessagingException:".length(),
             (error.length() - 1));
     result = "Failed:" + error;
     Logger.error(Mailer.class, f.toString(), f);
     return false;
   } catch (UnsupportedEncodingException f) {
     String error = String.valueOf(f);
     errorMessage =
         error.substring(
             error.lastIndexOf("java.io.UnsupportedEncodingException:")
                 + "java.io.UnsupportedEncodingException:".length(),
             (error.length() - 1));
     result = "Failed:" + error;
     Logger.error(Mailer.class, f.toString(), f);
     return false;
   }
 }
예제 #24
0
 public static String getTextContent(Part part, String type) {
   if (part == null) return null;
   try {
     String contentType;
     try {
       contentType = part.getContentType();
     } catch (Throwable t) {
       contentType = "unknown";
     }
     if (contentType.toLowerCase().startsWith("text/" + type)) {
       // ContentType ct = new ContentType(contentType);
       // String charset = ct.getParameter("charset");
       try {
         Object content = part.getContent();
         if (content == null) return null;
         if (content instanceof String) return (String) content;
         if (content instanceof InputStream) {
           String encoding = charset;
           if (contentType.toLowerCase().contains("UTF")) encoding = IO.UTF_8;
           if (contentType.toLowerCase().contains("ISO")) encoding = IO.ISO_LATIN_1;
           return IO.readToString((InputStream) content, encoding);
         }
         return Utl.toStringWithType(content);
       } catch (UnsupportedEncodingException ex) {
         LOG.warn(ex);
         return null;
       } catch (IOException e) {
         String message = e.getMessage();
         if (message != null) {
           if ("No content".equals(message)) {
             return null;
           }
           if (message.toLowerCase().startsWith("unknown encoding")) {
             LOG.warn(e);
             return null;
           }
         }
         throw e;
       } catch (Throwable t) {
         LOG.warn(t);
         return Str.getStackTrace(t);
       }
     }
     if (contentType.toLowerCase().startsWith("multipart")) {
       MimeMultipart multipart;
       try {
         multipart = (MimeMultipart) part.getContent();
       } catch (NullPointerException ex) {
         LOG.warn(ex);
         return null;
       }
       int count = multipart.getCount();
       for (int i = 0; i < count; i++) {
         BodyPart subPart = multipart.getBodyPart(i);
         String filename = subPart.getFileName();
         if (filename != null) continue;
         String text = getTextContent(subPart, type);
         if (text != null) return text.trim();
       }
       return null;
     }
     return null;
   } catch (Exception ex) {
     throw new RuntimeException(ex);
   }
 }
예제 #25
0
  @Test
  public void testFreeMarkerTextMailMessage() throws MessagingException, IOException {
    String uuid = java.util.UUID.randomUUID().toString();
    String subject = "Text Message from ${version} Mail - " + uuid;
    String version = "Seam 3";
    String mergedSubject = "Text Message from " + version + " Mail - " + uuid;

    Wiser wiser = new Wiser(mailConfig.getServerPort());
    wiser.setHostname(mailConfig.getServerHost());
    try {
      wiser.start();

      person.setName(toName);
      person.setEmail(toAddress);

      mailMessage
          .get()
          .from(MailTestUtil.getAddressHeader(fromName, fromAddress))
          .replyTo(replyToAddress)
          .to(MailTestUtil.getAddressHeader(toName, toAddress))
          .subject(new FreeMarkerTemplate(subject))
          .bodyText(
              new FreeMarkerTemplate(
                  resourceProvider.loadResourceStream("template.text.freemarker")))
          .put("person", person)
          .put("version", version)
          .importance(MessagePriority.HIGH)
          .send(session.get());
    } finally {
      stop(wiser);
    }

    Assert.assertTrue(
        "Didn't receive the expected amount of messages. Expected 1 got "
            + wiser.getMessages().size(),
        wiser.getMessages().size() == 1);

    MimeMessage mess = wiser.getMessages().get(0).getMimeMessage();

    Assert.assertEquals(
        MailTestUtil.getAddressHeader(fromName, fromAddress), mess.getHeader("From", null));
    Assert.assertEquals(
        MailTestUtil.getAddressHeader(replyToAddress), mess.getHeader("Reply-To", null));
    Assert.assertEquals(
        MailTestUtil.getAddressHeader(toName, toAddress), mess.getHeader("To", null));
    Assert.assertEquals(
        "Subject has been modified",
        mergedSubject,
        MimeUtility.unfold(mess.getHeader("Subject", null)));
    Assert.assertEquals(MessagePriority.HIGH.getPriority(), mess.getHeader("Priority", null));
    Assert.assertEquals(MessagePriority.HIGH.getX_priority(), mess.getHeader("X-Priority", null));
    Assert.assertEquals(MessagePriority.HIGH.getImportance(), mess.getHeader("Importance", null));
    Assert.assertTrue(mess.getHeader("Content-Type", null).startsWith("multipart/mixed"));

    MimeMultipart mixed = (MimeMultipart) mess.getContent();
    BodyPart text = mixed.getBodyPart(0);

    Assert.assertTrue(mixed.getContentType().startsWith("multipart/mixed"));
    Assert.assertEquals(1, mixed.getCount());

    Assert.assertTrue(text.getContentType().startsWith("text/plain; charset=UTF-8"));
    Assert.assertEquals(
        expectedTextBody(person.getName(), version), MailTestUtil.getStringContent(text));
  }
 @Override
 public Object unmarshal(Exchange exchange, InputStream stream)
     throws IOException, MessagingException {
   MimeBodyPart mimeMessage;
   String contentType;
   Message camelMessage;
   Object content = null;
   if (headersInline) {
     mimeMessage = new MimeBodyPart(stream);
     camelMessage = exchange.getOut();
     MessageHelper.copyHeaders(exchange.getIn(), camelMessage, true);
     contentType = mimeMessage.getHeader(CONTENT_TYPE, null);
     // write the MIME headers not generated by javamail as Camel headers
     Enumeration<?> headersEnum = mimeMessage.getNonMatchingHeaders(STANDARD_HEADERS);
     while (headersEnum.hasMoreElements()) {
       Object ho = headersEnum.nextElement();
       if (ho instanceof Header) {
         Header header = (Header) ho;
         camelMessage.setHeader(header.getName(), header.getValue());
       }
     }
   } else {
     // check if this a multipart at all. Otherwise do nothing
     contentType = exchange.getIn().getHeader(CONTENT_TYPE, String.class);
     if (contentType == null) {
       return stream;
     }
     try {
       ContentType ct = new ContentType(contentType);
       if (!ct.match("multipart/*")) {
         return stream;
       }
     } catch (ParseException e) {
       LOG.warn("Invalid Content-Type " + contentType + " ignored");
       return stream;
     }
     camelMessage = exchange.getOut();
     MessageHelper.copyHeaders(exchange.getIn(), camelMessage, true);
     ByteArrayOutputStream bos = new ByteArrayOutputStream();
     IOHelper.copyAndCloseInput(stream, bos);
     InternetHeaders headers = new InternetHeaders();
     extractHeader(CONTENT_TYPE, camelMessage, headers);
     extractHeader(MIME_VERSION, camelMessage, headers);
     mimeMessage = new MimeBodyPart(headers, bos.toByteArray());
     bos.close();
   }
   DataHandler dh;
   try {
     dh = mimeMessage.getDataHandler();
     if (dh != null) {
       content = dh.getContent();
       contentType = dh.getContentType();
     }
   } catch (MessagingException e) {
     LOG.warn("cannot parse message, no unmarshalling done");
   }
   if (content instanceof MimeMultipart) {
     MimeMultipart mp = (MimeMultipart) content;
     content = mp.getBodyPart(0);
     for (int i = 1; i < mp.getCount(); i++) {
       BodyPart bp = mp.getBodyPart(i);
       DefaultAttachment camelAttachment = new DefaultAttachment(bp.getDataHandler());
       @SuppressWarnings("unchecked")
       Enumeration<Header> headers = bp.getAllHeaders();
       while (headers.hasMoreElements()) {
         Header header = headers.nextElement();
         camelAttachment.addHeader(header.getName(), header.getValue());
       }
       camelMessage.addAttachmentObject(getAttachmentKey(bp), camelAttachment);
     }
   }
   if (content instanceof BodyPart) {
     BodyPart bp = (BodyPart) content;
     camelMessage.setBody(bp.getInputStream());
     contentType = bp.getContentType();
     if (contentType != null && !DEFAULT_CONTENT_TYPE.equals(contentType)) {
       camelMessage.setHeader(CONTENT_TYPE, contentType);
       ContentType ct = new ContentType(contentType);
       String charset = ct.getParameter("charset");
       if (charset != null) {
         camelMessage.setHeader(Exchange.CONTENT_ENCODING, MimeUtility.javaCharset(charset));
       }
     }
   } else {
     // If we find no body part, try to leave the message alone
     LOG.info("no MIME part found");
   }
   return camelMessage;
 }
예제 #27
0
  @Test
  public void testHTMLMailMessage() throws MessagingException, IOException {
    String subject = "HTML Message from Seam Mail - " + java.util.UUID.randomUUID().toString();
    String version = "Seam 3";
    EmailMessage emailMessage;
    mailConfig.setServerHost("localHost");
    mailConfig.setServerPort(8977);

    Wiser wiser = new Wiser(mailConfig.getServerPort());
    try {
      wiser.start();

      person.setName(toName);
      person.setEmail(toAddress);

      emailMessage =
          mailMessage
              .get()
              .from(fromAddress, fromName)
              .replyTo(replyToAddress, replyToName)
              .to(person)
              .subject(subject)
              .bodyHtml(new RenderTemplate(templateCompiler.get(), htmlTemplatePath))
              .put("person", person)
              .put("version", version)
              .importance(MessagePriority.HIGH)
              .addAttachment(
                  new URLAttachment(
                      "http://design.jboss.org/seam/logo/final/seam_mail_85px.png",
                      "seamLogo.png",
                      ContentDisposition.INLINE))
              .send(session.get());
    } finally {
      stop(wiser);
    }

    Assert.assertTrue(
        "Didn't receive the expected amount of messages. Expected 1 got "
            + wiser.getMessages().size(),
        wiser.getMessages().size() == 1);

    MimeMessage mess = wiser.getMessages().get(0).getMimeMessage();

    Assert.assertEquals(
        MailTestUtil.getAddressHeader(fromName, fromAddress), mess.getHeader("From", null));
    Assert.assertEquals(
        MailTestUtil.getAddressHeader(replyToName, replyToAddress),
        mess.getHeader("Reply-To", null));
    Assert.assertEquals(
        MailTestUtil.getAddressHeader(toName, toAddress), mess.getHeader("To", null));
    Assert.assertEquals(
        "Subject has been modified", subject, MimeUtility.unfold(mess.getHeader("Subject", null)));
    Assert.assertEquals(MessagePriority.HIGH.getPriority(), mess.getHeader("Priority", null));
    Assert.assertEquals(MessagePriority.HIGH.getX_priority(), mess.getHeader("X-Priority", null));
    Assert.assertEquals(MessagePriority.HIGH.getImportance(), mess.getHeader("Importance", null));
    Assert.assertTrue(mess.getHeader("Content-Type", null).startsWith("multipart/mixed"));

    MimeMultipart mixed = (MimeMultipart) mess.getContent();
    MimeMultipart related = (MimeMultipart) mixed.getBodyPart(0).getContent();
    BodyPart html = related.getBodyPart(0);
    BodyPart attachment1 = related.getBodyPart(1);

    Assert.assertTrue(mixed.getContentType().startsWith("multipart/mixed"));
    Assert.assertEquals(1, mixed.getCount());

    Assert.assertTrue(related.getContentType().startsWith("multipart/related"));
    Assert.assertEquals(2, related.getCount());

    Assert.assertTrue(html.getContentType().startsWith("text/html"));
    Assert.assertEquals(
        expectedHtmlBody(emailMessage, person.getName(), person.getEmail(), version),
        MailTestUtil.getStringContent(html));

    Assert.assertTrue(attachment1.getContentType().startsWith("image/png;"));
    Assert.assertEquals("seamLogo.png", attachment1.getFileName());
  }