예제 #1
0
  private void rePart(Part part) throws Exception {
    if (part.getDisposition() != null) {

      String strFileNmae =
          MimeUtility.decodeText(part.getFileName()); // MimeUtility.decodeText解决附件名乱码问题
      System.out.println("发现附件: " + MimeUtility.decodeText(part.getFileName()));
      System.out.println("内容类型: " + MimeUtility.decodeText(part.getContentType()));
      System.out.println("附件内容:" + part.getContent());
      InputStream in = part.getInputStream(); // 打开附件的输入流
      // 读取附件字节并存储到文件中
      java.io.FileOutputStream out = new FileOutputStream(strFileNmae);
      int data;
      while ((data = in.read()) != -1) {
        out.write(data);
      }
      in.close();
      out.close();
    } else {
      if (part.getContentType().startsWith("text/plain")) {
        System.out.println("文本内容:" + part.getContent());
      } else {
        // System.out.println("HTML内容:" + part.getContent());
      }
    }
  }
 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());
   }
 }
예제 #3
0
  /**
   * Updates the content of the table.
   *
   * <p>This method will be called by an observable element.
   *
   * <ul>
   *   <li>If the observable is a {@link MailSaver} object, a new row will be added to the table,
   *       and the {@link UIModel} will be updated;
   *   <li>If the observable is a {@link ClearAllButton} object, all the cells of the table will be
   *       removed, and the {@link UIModel} will be updated.
   * </ul>
   *
   * @param o the observable element which will notify this class.
   * @param arg optional parameters (an {@code EmailModel} object, for the case of a {@code
   *     MailSaver} observable) containing all the information about the email.
   */
  @Override
  public void update(Observable o, Object arg) {
    if (o instanceof MailSaver) {
      EmailModel email = (EmailModel) arg;
      String subject;
      try {
        subject = MimeUtility.decodeText(email.getSubject());
      } catch (UnsupportedEncodingException e) {
        LOGGER.error("", e);
        subject = email.getSubject();
      }

      model.addRow(
          new Object[] {
            dateFormat.format(email.getReceivedDate()), email.getFrom(), email.getTo(), subject
          });
      UIModel.INSTANCE.getListMailsMap().put(nbElements++, email.getFilePath());
    } else if (o instanceof ClearAllButton) {
      // Delete information from the map
      UIModel.INSTANCE.getListMailsMap().clear();

      // Remove elements from the list
      try {
        while (nbElements > 0) {
          model.removeRow(--nbElements);
        }
      } catch (ArrayIndexOutOfBoundsException e) {
        LOGGER.error("", e);
      }
    }
  }
예제 #4
0
 /**
  * 文本解码
  *
  * @param encodeText 解码MimeUtility.encodeText(String text)方法编码后的文本
  * @return 解码后的文本
  * @throws UnsupportedEncodingException
  */
 public static String decodeText(String encodeText) throws UnsupportedEncodingException {
   if (encodeText == null || "".equals(encodeText)) {
     return "";
   } else {
     return MimeUtility.decodeText(encodeText);
   }
 }
예제 #5
0
 private Object getHeader(MimeMessage message, String name)
     throws MessagingException, IOException {
   String[] header = message.getHeader(BlogRipper + name);
   if (header == null || header.length == 0) {
     header = message.getHeader(name);
   } else {
     log("using " + BlogRipper + name);
   }
   if (header == null || header.length == 0) {
     return null;
   }
   if (DateProperty.equals(name)) {
     SimpleDateFormat df = new SimpleDateFormat(RFC1123Format, Locale.US);
     try {
       return df.parse(header[0]);
     } catch (ParseException ex) {
       throw new IOException(ex);
     }
   }
   if ("Sender".equals(name)) {
     String email = header[0];
     int i1 = email.indexOf('<');
     int i2 = email.indexOf('>');
     if (i1 != -1 && i2 != -1) {
       email = email.substring(i1 + 1, i2);
     }
     return new Email(email);
   }
   return MimeUtility.decodeText(header[0]);
 }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("application/x-download");

    String userId = request.getParameter("id");
    int subjectId = Integer.parseInt(request.getParameter("subjectId"));
    int bodynum = Integer.parseInt(request.getParameter("bodynum"));
    String filename = request.getParameter("filename");

    ReceiveMail receiveMail = new ReceiveMail();
    User user = new User(userId);

    try {
      String newFilename = null;
      if (filename.startsWith("=?")) {
        newFilename =
            new Date().getTime()
                + MimeUtility.decodeText(filename)
                    .substring(MimeUtility.decodeText(filename).lastIndexOf("."));
      } else {
        newFilename = filename;
      }

      Message message = receiveMail.getOneMail(user, subjectId);
      WebMail webMail = MimeMailUtil.parse(message);
      response.setHeader("Content-Disposition", "attachment;filename=" + newFilename);

      MimeBodyPart bodypart = webMail.getAttachments().get(bodynum);

      OutputStream output = response.getOutputStream();
      InputStream input = bodypart.getInputStream();
      byte[] b = new byte[1024];
      int i = 0;
      while ((i = input.read(b)) > 0) {
        output.write(b, 0, i);
      }
      input.close();
      output.flush();
      output.close();
    } catch (Exception e) {
      request.setAttribute("errorInfo", e.getMessage());
      request.getRequestDispatcher("error.jsp").forward(request, response);
    }
  }
예제 #7
0
 /**
  * 字串解码
  *
  * @param text
  * @return
  * @throws java.io.UnsupportedEncodingException
  */
 protected static String decodeText(String text) throws UnsupportedEncodingException {
   if (text == null) return null;
   if (text.startsWith("=?GB") || text.startsWith("=?gb") || text.startsWith("=?UTF")) {
     text = MimeUtility.decodeText(text);
   } else {
     text = new String(text.getBytes("ISO8859_1"), "GBK");
   }
   return text;
 }
예제 #8
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;
 }
  public pl.dudzin.model.Message extract(File source) throws Exception {
    FileInputStream fis = null;

    StringBuffer txtBody = new StringBuffer();
    StringBuffer htmlBody = new StringBuffer();
    ;

    try {
      fis = new FileInputStream(source);
      Message mimeMsg = new Message(fis);

      if (mimeMsg.isMultipart()) {
        Multipart multipart = (Multipart) mimeMsg.getBody();
        parseBodyParts(multipart, txtBody, htmlBody);
      } else {
        String text = getTxtPart(mimeMsg);
        txtBody.append(text);
      }

      String content = MimeUtility.decodeText(html2text(htmlBody.toString()));
      if (StringUtils.isBlank(content)) {
        throw new Exception("For message : " + source.getName() + " content of email is empty!");
      }
      return new pl.dudzin.model.Message(
          MimeUtility.decodeText(mimeMsg.getSubject()), content, mimeMsg.getDate());

    } catch (IOException ex) {

    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (IOException ex) {
          ex.printStackTrace();
        }
      }
    }
    return null;
  }
예제 #10
0
  // 取得邮件列表的信息
  @SuppressWarnings({"rawtypes", "unchecked"})
  public List getMailInfo(Message[] msg) throws Exception {
    List result = new ArrayList();
    Map map = null;
    Multipart mp = null;
    BodyPart part = null;
    String disp = null;
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy年MM月dd日 hh:mm-ss");
    Enumeration enumMail = null;
    // 取出每个邮件的信息
    for (int i = msg.length - 1; i >= 0; i--) {
      if (!msg[i].getFolder().isOpen()) // 判断是否open
      msg[i].getFolder().open(Folder.READ_WRITE);
      map = new HashMap();
      // 读取邮件ID
      enumMail = msg[i].getAllHeaders();
      Header h = null;
      while (enumMail.hasMoreElements()) {
        h = (Header) enumMail.nextElement();
        if (h.getName().equals("Message-ID") || h.getName().equals("Message-Id")) {
          map.put("ID", h.getValue());
        }
      }
      // 读取邮件标题
      map.put("subject", msg[i].getSubject());
      // 读取发件人
      map.put("sender", MimeUtility.decodeText(msg[i].getFrom()[0].toString()));
      // 读取邮件发送日期
      map.put("senddate", fmt.format(msg[i].getSentDate()));
      // 读取邮件大小
      map.put("size", new Integer(msg[i].getSize()));
      map.put("hasAttach", "&nbsp;");
      // 判断是否有附件
      if (msg[i].isMimeType("multipart/*")) {
        mp = (Multipart) msg[i].getContent();
        // 遍历每个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))) {
            // 设置有附件的特征值
            map.put("hasAttach", "√");
          }
        }
      }
      result.add(map);
    }
    return result;
  }
  /**
   * <b>使用IMAP协议接收邮件</b><br>
   *
   * <p>POP3和IMAP协议的区别: <b>POP3</b>协议允许电子邮件客户端下载服务器上的邮件,但是在客户端的操作(如移动邮件、标记已读等),不会反馈到服务器上,<br>
   * 比如通过客户端收取了邮箱中的3封邮件并移动到其它文件夹,邮箱服务器上的这些邮件是没有同时被移动的。<br>
   *
   * <p><b>IMAP</b>协议提供webmail与电子邮件客户端之间的双向通信,客户端的操作都会同步反应到服务器上,对邮件进行的操作,服务
   * 上的邮件也会做相应的动作。比如在客户端收取了邮箱中的3封邮件,并将其中一封标记为已读,将另外两封标记为删除,这些操作会 即时反馈到服务器上。
   *
   * <p>两种协议相比,IMAP 整体上为用户带来更为便捷和可靠的体验。POP3更易丢失邮件或多次下载相同的邮件,但IMAP通过邮件客户端
   * 与webmail之间的双向同步功能很好地避免了这些问题。
   */
  public static void main(String[] args) throws Exception {
    // 准备连接服务器的会话信息
    Properties props = new Properties();
    props.setProperty("mail.store.protocol", "imap");
    props.setProperty("mail.imap.host", "imap.qq.com");
    props.setProperty("mail.imap.port", "143");

    // 创建Session实例对象
    Session session = Session.getInstance(props);

    // 创建IMAP协议的Store对象
    Store store = session.getStore("imap");

    // 连接邮件服务器
    store.connect("*****@*****.**", "asdasd");

    // 获得收件箱
    Folder folder = store.getFolder("INBOX");
    // 以读写模式打开收件箱
    folder.open(Folder.READ_WRITE);

    // 获得收件箱的邮件列表
    Message[] messages = folder.getMessages();

    // 打印不同状态的邮件数量
    System.out.println("收件箱中共" + messages.length + "封邮件!");
    System.out.println("收件箱中共" + folder.getUnreadMessageCount() + "封未读邮件!");
    System.out.println("收件箱中共" + folder.getNewMessageCount() + "封新邮件!");
    System.out.println("收件箱中共" + folder.getDeletedMessageCount() + "封已删除邮件!");

    System.out.println("------------------------开始解析邮件----------------------------------");

    // 解析邮件
    for (Message message : messages) {
      IMAPMessage msg = (IMAPMessage) message;
      String subject = MimeUtility.decodeText(msg.getSubject());
      System.out.println("[" + subject + "]未读,是否需要阅读此邮件(yes/no)?");
      BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
      String answer = reader.readLine();
      if ("yes".equalsIgnoreCase(answer)) {
        Pop3ReceiveMailUtil.parseMessage(msg); // 解析邮件
        // 第二个参数如果设置为true,则将修改反馈给服务器。false则不反馈给服务器
        msg.setFlag(Flags.Flag.SEEN, true); // 设置已读标志
      }
    }

    // 关闭资源
    folder.close(false);
    store.close();
  }
예제 #12
0
  private static Attachment saveAttachment(Part partToAttach, Resource container)
      throws MessagingException, IOException, NoSuchAlgorithmException {
    Attachment attach = new Attachment();
    String fileName = MimeUtility.decodeText(partToAttach.getFileName());
    attach.store(partToAttach.getInputStream(), fileName, container);
    if (!attach.mimeType.equalsIgnoreCase(partToAttach.getContentType())) {
      Logger.info(
          "The email says the content type is '"
              + partToAttach.getContentType()
              + "' but Yobi determines it is '"
              + attach.mimeType
              + "'");
    }

    return attach;
  }
예제 #13
0
  /**
   * Determines the name of the data source if it is not already set.
   *
   * @param part the mail part
   * @param dataSource the data source
   * @return the name of the data source or {@code null} if no name can be determined
   * @throws MessagingException accessing the part failed
   * @throws UnsupportedEncodingException decoding the text failed
   */
  protected String getDataSourceName(final Part part, final DataSource dataSource)
      throws MessagingException, UnsupportedEncodingException {
    String result = dataSource.getName();

    if (result == null || result.length() == 0) {
      result = part.getFileName();
    }

    if (result != null && result.length() > 0) {
      result = MimeUtility.decodeText(result);
    } else {
      result = null;
    }

    return result;
  }
예제 #14
0
 /**
  * For receiving an email, the sender, receiver, reply-to and subject may be messy code. The
  * default encoding of HTTP is ISO8859-1, In this situation, use MimeUtility.decodeTex() to
  * convert these information to GBK encoding.
  *
  * @param res The String to be decoded.
  * @return A decoded String.
  */
 private static String mimeDecodeString(String res) {
   if (res != null) {
     String from = res.trim();
     try {
       if (from.startsWith("=?GB")
           || from.startsWith("=?gb")
           || from.startsWith("=?UTF")
           || from.startsWith("=?utf")) {
         from = MimeUtility.decodeText(from);
       }
     } catch (Exception e) {
       LOGGER.error("Decode string error. Origin string is: " + res, e);
     }
     return from;
   }
   return 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);
 }
  /**
   * Save attachment.
   *
   * @param part
   * @param attachList
   * @throws MessagingException
   * @throws IOException
   */
  protected void saveAttachment(Part part, List<Attachment> attachList)
      throws MessagingException, IOException {
    // generate a new file name with unique UUID.
    String fileName = part.getFileName();
    fileName = MimeUtility.decodeText(fileName);
    Attachment attachment = new Attachment();
    attachment.setFileName(fileName);

    UUID uuid = UUID.randomUUID();
    String prefix = fileName.substring(0, fileName.lastIndexOf(".") + 1);
    String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
    String tempDir = System.getProperty("java.io.tmpdir");
    String filePath = tempDir + prefix + uuid + "." + suffix;

    int fileSize = part.getSize();
    attachment.setFilePath(filePath);
    attachment.setFileType(suffix);
    attachment.setFileSize(fileSize);
    attachList.add(attachment);
    this.saveFile(filePath, part.getInputStream());
  }
예제 #17
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();
    }
예제 #18
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)));
  }