public void saveEmailFiles(HttpServletRequest request, HttpServletResponse response, Part part)
     throws Exception {
   String fileName = "";
   if (part.isMimeType("multipart/*")) {
     Multipart mp = (Multipart) part.getContent();
     for (int i = 0; i < mp.getCount(); i++) {
       BodyPart mpart = mp.getBodyPart(i);
       String disposition = mpart.getDisposition();
       if ((disposition != null)
           && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE)))) {
         fileName = mpart.getFileName();
         if (fileName != null) {
           if (fileName.toLowerCase().indexOf("gb2312") != -1
               || fileName.toLowerCase().indexOf("gbk") != -1) {
             fileName = MimeUtility.decodeText(fileName);
           }
           if (request.getHeader("User-Agent").contains("Firefox")) {
             response.addHeader("content-disposition", "attachment;filename=" + fileName);
           } else if (request.getHeader("User-Agent").contains("MSIE")) {
             response.addHeader(
                 "content-disposition",
                 "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
           }
           System.out.println("saveFile1");
           saveFile(response, fileName, mpart.getInputStream());
         }
       } else if (mpart.isMimeType("multipart/*")) {
         saveEmailFiles(request, response, mpart);
       } else {
         fileName = mpart.getFileName();
         if (fileName != null) {
           if (fileName.toLowerCase().indexOf("gb2312") != -1
               || fileName.toLowerCase().indexOf("gbk") != -1) {
             fileName = MimeUtility.decodeText(fileName);
           }
           if (request.getHeader("User-Agent").contains("Firefox")) {
             response.addHeader("content-disposition", "attachment;filename=" + fileName);
           } else if (request.getHeader("User-Agent").contains("MSIE")) {
             response.addHeader(
                 "content-disposition",
                 "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
           }
           System.out.println("saveFile2");
           saveFile(response, fileName, mpart.getInputStream());
         }
       }
     }
   } else if (part.isMimeType("message/rfc822")) {
     saveEmailFiles(request, response, (Part) part.getContent());
   }
 }
Пример #2
0
  private void getMultipart(BodyPart bp, Object content) throws IOException, MessagingException {
    if (!(content instanceof Multipart)) {
      if (bp.getFileName() != null && content instanceof InputStream) {
        files.put(bp.getFileName(), (InputStream) content);
      }
      return;
    }

    Multipart mp = (Multipart) content;
    for (int i = 0; i < mp.getCount(); i++) {
      BodyPart newBp = mp.getBodyPart(i);
      getMultipart(newBp, newBp.getContent());
    }
  }
Пример #3
0
  /**
   * 对复杂邮件的解析
   *
   * @param multipart
   * @throws MessagingException
   * @throws IOException
   */
  public static void parseMultipart(Multipart multipart) throws MessagingException, IOException {
    int count = multipart.getCount();
    System.out.println("couont =  " + count);
    for (int idx = 0; idx < count; idx++) {
      BodyPart bodyPart = multipart.getBodyPart(idx);
      System.out.println(bodyPart.getContentType());
      if (bodyPart.isMimeType("text/plain")) {
        System.out.println("plain................." + bodyPart.getContent());
      } else if (bodyPart.isMimeType("text/html")) {
        System.out.println("html..................." + bodyPart.getContent());
      } else if (bodyPart.isMimeType("multipart/*")) {
        Multipart mpart = (Multipart) bodyPart.getContent();
        parseMultipart(mpart);

      } else if (bodyPart.isMimeType("application/octet-stream")) {
        String disposition = bodyPart.getDisposition();
        System.out.println(disposition);
        if (disposition.equalsIgnoreCase(BodyPart.ATTACHMENT)) {
          String fileName = bodyPart.getFileName();
          InputStream is = bodyPart.getInputStream();
          copy(is, new FileOutputStream("D:\\" + fileName));
        }
      }
    }
  }
Пример #4
0
    private String getRawText(Object o) throws MessagingException, IOException {

      String s = null;

      if (o instanceof Multipart) {
        Multipart multi = (Multipart) o;
        for (int i = 0; i < multi.getCount(); i++) {
          s = getRawText(multi.getBodyPart(i));
          if (s != null) {
            if (s.length() > 0) {
              break;
            }
          }
        }
      } else if (o instanceof BodyPart) {
        BodyPart aBodyContent = (BodyPart) o;
        StringTokenizer aTypeTokenizer = new StringTokenizer(aBodyContent.getContentType(), "/");
        String abstractType = aTypeTokenizer.nextToken();
        if (abstractType.compareToIgnoreCase("MESSAGE") == 0) {
          Message inlineMessage = (Message) aBodyContent.getContent();
          s = getRawText(inlineMessage.getContent());
        }
        if (abstractType.compareToIgnoreCase("APPLICATION") == 0) {
          s = "Attached File: " + aBodyContent.getFileName();
        }
        if (abstractType.compareToIgnoreCase("TEXT") == 0) {
          try {
            Object oS = aBodyContent.getContent();
            if (oS instanceof String) {
              s = (String) oS;
            } else {
              throw (new MessagingException("Unkown MIME Type (?): " + oS.getClass()));
            }
          } catch (Exception e) {
            throw (new MessagingException(
                "Unable to read message contents (" + e.getMessage() + ")"));
          }
        }
        if (abstractType.compareToIgnoreCase("MULTIPART") == 0) {
          s = getRawText(aBodyContent.getContent());
        }
      }

      if (o instanceof String) {
        s = (String) o;
      }

      //          else {
      //              if (m.isMimeType("text/html")) {
      //                  s = m.getContent().toString();
      //              }
      //              if (m.isMimeType("text/plain")) {
      //                  s = m.getContent().toString();
      //              }
      //          }

      return s;
    }
Пример #5
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());
  }
 public String getPartFilename(String index) {
   BodyPart part = getPart(index);
   if (part != null) {
     try {
       return part.getFileName();
     } catch (MessagingException e) {
       Debug.logError(e, module);
       return null;
     }
   } else {
     return null;
   }
 }
 /**
  * Saves all attachments to a temp directory, and returns the directory path. Null if no
  * attachments.
  */
 public File saveAttachments(Message message) throws IOException, MessagingException {
   File tmpDir = Files.createTempDir();
   boolean foundAttachments = false;
   Object content = message.getContent();
   if (message.isMimeType(MULTIPART_WILDCARD) && content instanceof Multipart) {
     Multipart mp = (Multipart) content;
     for (int i = 0; i < mp.getCount(); i++) {
       BodyPart bodyPart = mp.getBodyPart(i);
       if (bodyPart instanceof MimeBodyPart && isNotBlank(bodyPart.getFileName())) {
         MimeBodyPart mimeBodyPart = (MimeBodyPart) bodyPart;
         mimeBodyPart.saveFile(new File(tmpDir, mimeBodyPart.getFileName()));
         foundAttachments = true;
       }
     }
   }
   return foundAttachments ? tmpDir : null;
 }
 private String getAttachmentKey(BodyPart bp)
     throws MessagingException, UnsupportedEncodingException {
   // use the filename as key for the map
   String key = bp.getFileName();
   // if there is no file name we use the Content-ID header
   if (key == null && bp instanceof MimeBodyPart) {
     key = ((MimeBodyPart) bp).getContentID();
     if (key != null && key.startsWith("<") && key.length() > 2) {
       // strip <>
       key = key.substring(1, key.length() - 1);
     }
   }
   // or a generated content id
   if (key == null) {
     key = UUID.randomUUID().toString() + "@camel.apache.org";
   }
   return MimeUtility.decodeText(key);
 }
Пример #9
0
 public static Blob readBlob(HttpServletRequest request, BodyPart part)
     throws MessagingException, IOException {
   String ctype = part.getContentType();
   String fname = part.getFileName();
   InputStream pin = part.getInputStream();
   final File tmp = File.createTempFile("nx-automation-upload-", ".tmp");
   FileUtils.copyToFile(pin, tmp);
   Blob blob = Blobs.createBlob(tmp, ctype, null, fname);
   RequestContext.getActiveContext(request)
       .addRequestCleanupHandler(
           new RequestCleanupHandler() {
             @Override
             public void cleanup(HttpServletRequest req) {
               tmp.delete();
             }
           });
   return blob;
 }
Пример #10
0
 // 读取邮件内容
 @SuppressWarnings({"rawtypes", "unchecked"})
 public Map readMail(String id) throws Exception {
   Map map = new HashMap();
   // 找到目标邮件
   Message readmsg = findMail(msg, id);
   // 读取邮件标题
   map.put("subject", readmsg.getSubject());
   // 读取发件人
   map.put("sender", MimeUtility.decodeText(readmsg.getFrom()[0].toString()));
   map.put("attach", "");
   // 取得邮件内容
   if (readmsg.isMimeType("text/*")) {
     map.put("content", readmsg.getContent().toString());
   } else {
     System.out.println("this is not a text mail");
     Multipart mp = (Multipart) readmsg.getContent();
     if (mp == null) {
       System.out.println("the content is null");
     } else System.out.println("--------------------------multipart:" + mp.toString());
     BodyPart part = null;
     String disp = null;
     StringBuffer result = new StringBuffer();
     // 遍历每个Miltipart对象
     for (int j = 0; j < mp.getCount(); j++) {
       part = mp.getBodyPart(j);
       disp = part.getDisposition();
       // 如果有附件
       if (disp != null && (disp.equals(Part.ATTACHMENT) || disp.equals(Part.INLINE))) {
         // 取得附件文件名
         String filename = MimeUtility.decodeText(part.getFileName()); // 解决中文附件名的问题
         map.put("attach", filename);
         // 下载附件
         InputStream in = part.getInputStream(); // 附件输入流
         if (attachFile.isDownload(filename)) attachFile.choicePath(filename, in); // // 下载附件
       } else {
         // 显示复杂邮件正文内容
         result.append(getPart(part, j, 1));
       }
     }
     map.put("content", result.toString());
   }
   return map;
 }
Пример #11
0
    private AttachedFileValue createAttachedFileValue(Date sentDate, BodyPart part)
        throws MessagingException, IOException {
      // Create attachment
      ValueBuilder<AttachedFileValue> attachmentBuilder =
          module.valueBuilderFactory().newValueBuilder(AttachedFileValue.class);

      AttachedFileValue prototype = attachmentBuilder.prototype();
      // check contentType and fetch just the first part if necessary
      String contentType = "";
      if (part.getContentType().indexOf(';') == -1) contentType = part.getContentType();
      else contentType = part.getContentType().substring(0, part.getContentType().indexOf(';'));

      prototype.mimeType().set(contentType);
      prototype.modificationDate().set(sentDate);
      String fileName = part.getFileName();
      prototype.name().set(fileName == null ? "Nofilename" : MimeUtility.decodeText(fileName));
      prototype.size().set((long) part.getSize());

      InputStream inputStream = part.getInputStream();
      String id = attachmentStore.storeAttachment(Inputs.byteBuffer(inputStream, 4096));
      String uri = "store:" + id;
      prototype.uri().set(uri);
      return attachmentBuilder.newInstance();
    }
Пример #12
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);
   }
 }
Пример #13
0
  /**
   * Method that uses the Java Mail API to send an email message.<br>
   * It is recommended to use the <type>com.idega.core.messaging.EmailMessage</type> class rather
   * than calling this method directly.
   *
   * @param from
   * @param to
   * @param cc
   * @param bcc
   * @param replyTo
   * @param host
   * @param subject
   * @param text
   * @param mailType: plain text, HTML etc.
   * @param attachedFiles
   * @throws MessagingException
   */
  public static void send(
      String from,
      String to,
      String cc,
      String bcc,
      String replyTo,
      String host,
      String subject,
      String text,
      String mailType,
      File... attachedFiles)
      throws MessagingException {

    // Charset usually either "UTF-8" or "ISO-8859-1". If not set the system default set is taken
    IWMainApplicationSettings settings =
        IWMainApplication.getDefaultIWApplicationContext().getApplicationSettings();
    String charset = settings.getCharSetForSendMail();
    boolean useSmtpAuthentication =
        settings.getBoolean(MessagingSettings.PROP_SYSTEM_SMTP_USE_AUTHENTICATION, Boolean.FALSE);
    boolean useSSL = settings.getBoolean(MessagingSettings.PROP_SYSTEM_SMTP_USE_SSL, Boolean.FALSE);
    String username =
        settings.getProperty(MessagingSettings.PROP_SYSTEM_SMTP_USER_NAME, CoreConstants.EMPTY);
    String password =
        settings.getProperty(MessagingSettings.PROP_SYSTEM_SMTP_PASSWORD, CoreConstants.EMPTY);
    String port =
        settings.getProperty(MessagingSettings.PROP_SYSTEM_SMTP_PORT, CoreConstants.EMPTY);
    if (StringUtil.isEmpty(host)) {
      host = settings.getProperty(MessagingSettings.PROP_SYSTEM_SMTP_MAILSERVER);
      if (StringUtil.isEmpty(host)) {
        throw new MessagingException("Mail server is not configured.");
      }
    }

    if (StringUtil.isEmpty(username)) {
      useSmtpAuthentication = false;
    }

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", host);

    // Set the smtp server port
    if (!StringUtil.isEmpty(port)) {
      props.put("mail.smtp.port", port);
    }

    // Start a session
    Session session;

    if (useSmtpAuthentication) {
      props.put("mail.smtp.auth", Boolean.TRUE.toString());
      Authenticator auth = new SMTPAuthenticator(username, password);

      if (useSSL) {
        props.put("mail.smtp.ssl.enable", Boolean.TRUE.toString());
      }

      session = Session.getInstance(props, auth);
    } else {
      session = Session.getInstance(props, null);
    }

    // Set debug if needed
    session.setDebug(settings.isDebugActive());

    // Construct a message
    if (StringUtil.isEmpty(from)) {
      throw new MessagingException("From address is null.");
    }
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));

    // Process to, cc and bcc
    addRecipients(message, Message.RecipientType.TO, to);
    addRecipients(message, Message.RecipientType.CC, cc);
    addRecipients(message, Message.RecipientType.BCC, bcc);

    if (!StringUtil.isEmpty(replyTo)) {
      message.setReplyTo(InternetAddress.parse(replyTo));
    }

    message.setSubject(subject, charset);

    if (ArrayUtil.isEmpty(attachedFiles)) {
      setMessageContent(message, text, mailType, charset);
    } else {
      MimeBodyPart body = new MimeBodyPart();
      setMessageContent(body, text, mailType, charset);

      MimeMultipart multipart = new MimeMultipart();
      multipart.addBodyPart(body);

      for (File attachedFile : attachedFiles) {
        if (attachedFile == null) {
          continue;
        }

        BodyPart attachment = new MimeBodyPart();
        DataSource attachmentSource = new FileDataSource(attachedFile);
        DataHandler attachmentHandler = new DataHandler(attachmentSource);
        attachment.setDataHandler(attachmentHandler);
        attachment.setFileName(attachedFile.getName());
        attachment.setDescription("Attached file: " + attachment.getFileName());
        LOGGER.info("Adding attachment " + attachment);
        multipart.addBodyPart(attachment);
      }

      message.setContent(multipart);
    }

    // Send the message and close the connection
    Transport.send(message);
  }
Пример #14
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());
  }
Пример #15
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());
  }
Пример #16
0
 private Collection<Future<HTTPResponse>> handleBodyPart(
     HttpServletRequest request, Entity blog, BodyPart bodyPart, final Settings settings)
     throws MessagingException, IOException {
   ImagesService imagesService = ImagesServiceFactory.getImagesService();
   DS ds = DS.get();
   Collection<Future<HTTPResponse>> futures = new ArrayList<>();
   String contentType = bodyPart.getContentType();
   log(contentType);
   Object content = bodyPart.getContent();
   if (content instanceof InputStream) {
     String filename = bodyPart.getFileName();
     byte[] bytes = getBytes(bodyPart);
     String digestString = DS.getDigest(bytes);
     Entity metadata = createMetadata(digestString, filename, contentType, bytes);
     if (contentType.startsWith("image/")) {
       int oWidth;
       int oHeight;
       int wWidth;
       int wHeight;
       Image image = ImagesServiceFactory.makeImage(bytes);
       if (settings.isFixPic()) {
         Transform makeImFeelingLucky = ImagesServiceFactory.makeImFeelingLucky();
         image = imagesService.applyTransform(makeImFeelingLucky, image);
       }
       oWidth = image.getWidth();
       oHeight = image.getHeight();
       if (image.getHeight() > settings.getPicMaxHeight()
           || image.getWidth() > settings.getPicMaxWidth()) {
         log(
             "shrinking ["
                 + image.getHeight()
                 + ", "
                 + image.getWidth()
                 + "] > ["
                 + settings.getPicMaxHeight()
                 + ", "
                 + settings.getPicMaxWidth()
                 + "]");
         Transform makeResize =
             ImagesServiceFactory.makeResize(
                 settings.getPicMaxHeight(), settings.getPicMaxWidth());
         Image shrinken = imagesService.applyTransform(makeResize, image);
         wWidth = shrinken.getWidth();
         wHeight = shrinken.getHeight();
         Future<HTTPResponse> res =
             postBlobs(
                 filename,
                 contentType,
                 digestString,
                 shrinken.getImageData(),
                 WebSizeProperty,
                 request,
                 wWidth,
                 wHeight);
         futures.add(res);
       } else {
         wWidth = image.getWidth();
         wHeight = image.getHeight();
         Future<HTTPResponse> res =
             postBlobs(
                 filename,
                 contentType,
                 digestString,
                 bytes,
                 WebSizeProperty,
                 request,
                 wWidth,
                 wHeight);
         futures.add(res);
       }
       Future<HTTPResponse> res =
           postBlobs(
               filename,
               contentType,
               digestString,
               bytes,
               OriginalSizeProperty,
               request,
               oWidth,
               oHeight);
       futures.add(res);
       String[] cids = bodyPart.getHeader("Content-ID");
       if (cids != null && cids.length > 0) {
         String alt = (String) metadata.getProperty(UserCommentProperty);
         if (alt == null) {
           alt = "";
         }
         replaceBlogRef(blog, cids[0], digestString, wWidth, wHeight, alt);
       }
     }
     if (contentType.startsWith("application/vnd.google-earth.kml+xml")
         || filename.endsWith(".kml")) {
       try {
         InputStream is = (InputStream) content;
         KML kml = new KML(is);
         PlacemarkUpdater pu = new PlacemarkUpdater(ds, kml, LocatorLevel.Field);
         pu.visit(kml, null);
       } catch (JAXBException ex) {
         log("reading kml failed", ex);
       }
     }
     if (contentType.startsWith("application/vnd.google-earth.kmz") || filename.endsWith(".kmz")) {
       try {
         InputStream is = (InputStream) content;
         KMZ kmz = new KMZ(is);
         PlacemarkUpdater pu = new PlacemarkUpdater(ds, kmz, LocatorLevel.Field);
         pu.visit(kmz, null);
       } catch (JAXBException ex) {
         log("reading kmz failed", ex);
       }
     }
     if (filename.endsWith(".gpx")) {
       try {
         InputStream is = (InputStream) content;
         final GPX gpx = new GPX(is);
         final OpenCPNTrackHandler handler = new OpenCPNTrackHandler(ds);
         RunInNamespace rin =
             new RunInNamespace() {
               @Override
               protected Object run() {
                 gpx.browse(
                     settings.getTrackBearingTolerance(),
                     settings.getTrackMinimumDistance(),
                     settings.getTrackMaxSpeed(),
                     handler);
                 return null;
               }
             };
         rin.doIt(null, settings.isCommonPlacemarks());
       } catch (JAXBException ex) {
         log("reading gpx failed", ex);
       }
     }
     if (filename.endsWith(".trc")) {
       InputStream is = (InputStream) content;
       final TrackInput trackInput = new TrackInput(is);
       final CompressedTrackHandler cth = new CompressedTrackHandler(ds);
       RunInNamespace rin =
           new RunInNamespace() {
             @Override
             protected Object run() {
               try {
                 cth.handle(trackInput);
               } catch (IOException ex) {
                 log(ex.getMessage(), ex);
               }
               return null;
             }
           };
       rin.doIt(null, settings.isCommonPlacemarks());
     }
     if (contentType.startsWith("application/X-jsr179-location-nmea")
         || filename.endsWith(".nmea")) {
       log("NMEA not yet supported");
     }
   }
   return futures;
 }