Exemplo n.º 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());
      }
    }
  }
Exemplo n.º 2
0
  public Header(String name, String value) {
    this.name = name;

    try {
      this.value = MimeUtility.fold(name.length() + 2, MimeUtility.encodeText(value));
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException("Unable to create header", e);
    }
  }
 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());
   }
 }
Exemplo n.º 4
0
  public static void SendMail() {

    final String username = Directory.userName;
    final String password = Directory.password;
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.host", Directory.smtpHost);
    Session session =
        Session.getInstance(
            props,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
              }
            });
    try {
      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress(Directory.fromAddress));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(Directory.toAddress));
      message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(Directory.ccAddress));
      message.setSubject("Execution Result");
      message.setText("PFA");

      message.setText(MimeUtility.encodeText("Pode Has Fallen Down", "utf-8", "B"));
      message.setText(MimeUtility.encodeText("Fallen Down It Has", "utf-8", "B"));
      message.setText(MimeUtility.encodeText("It Has Fallen Down", "utf-8", "B"));

      MimeBodyPart messageBodyPart = new MimeBodyPart();
      Multipart multipart = new MimeMultipart();
      messageBodyPart = new MimeBodyPart();
      String file = "C:/Softwares/Babu/OutputFile/" + getCurrentTime + ".zip";
      String fileName = "Sample File";
      DataSource source = new FileDataSource(file);
      messageBodyPart.setDataHandler(new DataHandler(source));
      messageBodyPart.attachFile(file);
      // messageBodyPart.setFileName(fileName);
      multipart.addBodyPart(messageBodyPart);
      message.setContent(multipart);
      System.out.println("Mail Sending");
      Transport.send(message);
      System.out.println("Done");
    } catch (MessagingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Exemplo n.º 5
0
  /**
   * Evaluate filename and client and encode appropriate disposition
   *
   * @param filename
   * @param request
   * @param response
   * @throws UnsupportedEncodingException
   */
  public static void setBitstreamDisposition(
      String filename, HttpServletRequest request, HttpServletResponse response) {

    String name = filename;

    Matcher m = p.matcher(name);

    if (m.find() && !m.group().equals("")) {
      name = m.group();
    }

    try {
      String agent = request.getHeader("USER-AGENT");

      if (null != agent && -1 != agent.indexOf("MSIE")) {
        name = URLEncoder.encode(name, "UTF8");
      } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
        name = MimeUtility.encodeText(name, "UTF8", "B");
      }

    } catch (UnsupportedEncodingException e) {
      log.error(e.getMessage(), e);
    } finally {
      response.setHeader("Content-Disposition", "attachment;filename=" + name);
    }
  }
Exemplo n.º 6
0
  private Message createMessage() {

    Properties props = new Properties();

    props.setProperty("mail.transport.protocol", "smtp");

    props.setProperty("mail.smtp.auth", "true");
    props.setProperty("mail.smtp.host", host);
    props.setProperty("mail.smtp.port", "25");

    if (useSSL) {
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.setProperty("mail.smtp.port", "465");
    }

    // error:javax.mail.MessagingException: 501 Syntax: HELO hostname
    props.setProperty("mail.smtp.localhost", "127.0.0.1");

    Session session = Session.getInstance(props, this);
    Message message = new MimeMessage(session);

    try {
      message.setFrom(new InternetAddress(MimeUtility.encodeText(name) + "<" + name + ">"));
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    return message;
  }
Exemplo n.º 7
0
 public static byte[] encode(byte[] b) throws Exception {
   ByteArrayOutputStream baos = null;
   OutputStream b64os = null;
   try {
     baos = new ByteArrayOutputStream();
     b64os = MimeUtility.encode(baos, "base64");
     b64os.write(b);
     b64os.close();
     return baos.toByteArray();
   } catch (Exception e) {
     throw new Exception(e);
   } finally {
     try {
       if (baos != null) {
         baos.close();
         baos = null;
       }
     } catch (Exception e) {
     }
     try {
       if (b64os != null) {
         b64os.close();
         b64os = null;
       }
     } catch (Exception e) {
     }
   }
 }
Exemplo n.º 8
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]);
 }
Exemplo n.º 9
0
 /**
  * Encodes a string to "quoted-printable" characters to compare with the contents of an email.
  *
  * @param input String to encode
  * @return Encoded string
  * @throws MessagingException
  * @throws IOException
  */
 protected String encodeQuotedPrintable(String input) throws MessagingException, IOException {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   OutputStream os = MimeUtility.encode(baos, "quoted-printable");
   os.write(input.getBytes());
   os.close();
   return baos.toString();
 }
Exemplo n.º 10
0
  /**
   * 构建邮件的正文和附件
   *
   * @param msgContent
   * @param attachedFileList
   * @return
   * @throws javax.mail.MessagingException
   * @throws java.io.UnsupportedEncodingException
   */
  public static Multipart buildMimeMultipart(String msgContent, Vector<String> attachedFileList)
      throws MessagingException, UnsupportedEncodingException {
    Multipart mPart = new MimeMultipart(); // 多部分实现

    // 邮件正文
    MimeBodyPart mBodyContent = new MimeBodyPart(); // MIME邮件段体
    if (msgContent != null) {
      mBodyContent.setContent(msgContent, messageContentMimeType);
    } else {
      mBodyContent.setContent("", messageContentMimeType);
    }
    mPart.addBodyPart(mBodyContent);

    // 附件
    String file;
    String fileName;
    if (attachedFileList != null) {
      for (Enumeration<String> fileList = attachedFileList.elements();
          fileList.hasMoreElements(); ) {
        file = fileList.nextElement();
        fileName = file.substring(file.lastIndexOf("/") + 1);
        MimeBodyPart mBodyPart = new MimeBodyPart();
        // 远程资源
        // URLDataSource uds=new
        // URLDataSource(http://www.iteye.com/logo.gif);
        FileDataSource fds = new FileDataSource(file);
        mBodyPart.setDataHandler(new DataHandler(fds));
        // mBodyPart.setFileName(fileName);
        mBodyPart.setFileName(MimeUtility.encodeWord(fileName)); // 解决中文附件名问题
        mPart.addBodyPart(mBodyPart);
      }
    }

    return mPart;
  }
Exemplo n.º 11
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);
      }
    }
  }
Exemplo n.º 12
0
 public void setSubject(String subject) {
   try {
     this.subject = MimeUtility.encodeText(subject, enc, "B");
   } catch (UnsupportedEncodingException ex) {
     ex.printStackTrace();
   }
 }
Exemplo n.º 13
0
  public static byte[] decode(byte[] b) throws Exception {
    ByteArrayInputStream bais = null;
    InputStream b64is = null;
    try {
      bais = new ByteArrayInputStream(b);
      b64is = MimeUtility.decode(bais, "base64");
      byte[] tmp = new byte[b.length];
      int n = b64is.read(tmp);
      byte[] res = new byte[n];
      System.arraycopy(tmp, 0, res, 0, n);

      return res;
    } catch (Exception e) {
      throw new Exception(e);
    } finally {
      try {
        if (bais != null) {
          bais.close();
          bais = null;
        }
      } catch (Exception e) {
      }
      try {
        if (b64is != null) {
          b64is.close();
          b64is = null;
        }
      } catch (Exception e) {
      }
    }
  }
Exemplo n.º 14
0
  /** * 处理附件型邮件时,需要为邮件体和附件体分别创建BodyPort对象 然后将其置入MimeMultipart对象中作为一个整体进行发送 */
  @Override
  protected void setContent(MimeMessage message) throws MailException {
    try {
      Multipart multipart = new MimeMultipart();
      // 文本
      BodyPart textBodyPart = new MimeBodyPart();
      multipart.addBodyPart(textBodyPart);
      textBodyPart.setContent(text, "text/html;charset=" + charset);

      // 附件
      for (File attachment : attachments) {
        BodyPart fileBodyPart = new MimeBodyPart();
        multipart.addBodyPart(fileBodyPart);
        FileDataSource fds = new FileDataSource(attachment);
        fileBodyPart.setDataHandler(new DataHandler(fds));
        // 中文乱码
        String attachmentName = fds.getName();
        fileBodyPart.setFileName(MimeUtility.encodeText(attachmentName));
      }
      // 内容
      message.setContent(multipart);
    } catch (Exception e) {
      new MailException(e.getMessage());
    }
  }
Exemplo n.º 15
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);
   }
 }
Exemplo n.º 16
0
 private static String encode(final String string) {
   try {
     return string == null ? "" : MimeUtility.encodeText(string);
   } catch (final UnsupportedEncodingException e) {
     LOG.error(e.getMessage(), e);
     return string;
   }
 }
Exemplo n.º 17
0
 /**
  * Constructor with a String. The MIME type should include a charset parameter specifying the
  * charset to use to encode the string; otherwise, the platform default is used.
  *
  * @param data the string
  * @param type the MIME type
  */
 public ByteArrayDataSource(String data, String type) throws IOException {
   try {
     ContentType ct = new ContentType(type);
     String charset = ct.getParameter("charset");
     String jcharset =
         (charset == null)
             ? MimeUtility.getDefaultJavaCharset()
             : MimeUtility.javaCharset(charset);
     if (jcharset == null) throw new UnsupportedEncodingException(charset);
     this.data = data.getBytes(jcharset);
     this.type = type;
   } catch (ParseException e) {
     IOException e2 = new IOException("can't parse MIME type");
     e2.initCause(e);
     throw e2;
   }
 }
  /** @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);
    }
  }
Exemplo n.º 19
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;
 }
Exemplo n.º 20
0
  @Test
  public void testSMTPSessionAuthentication() throws MessagingException, MalformedURLException {
    String subject = "HTML+Text Message from Seam Mail - " + java.util.UUID.randomUUID().toString();
    mailConfig.setServerHost("localHost");
    mailConfig.setServerPort(8978);

    Wiser wiser = new Wiser(mailConfig.getServerPort());
    wiser
        .getServer()
        .setAuthenticationHandlerFactory(
            new EasyAuthenticationHandlerFactory(new SMTPAuthenticator("test", "test12!")));
    try {
      wiser.start();

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

      mailMessage
          .get()
          .from(fromAddress)
          .to(person.getEmail())
          .subject(subject)
          .put("person", person)
          .put("version", "Seam 3")
          .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(gmailSession);
    } 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(
        "Subject has been modified", subject, MimeUtility.unfold(mess.getHeader("Subject", null)));
  }
Exemplo n.º 21
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;
 }
  protected AddressBkDAO_DB() throws AddressBkDAOException {
    final ConfigDAO configDAO;
    try {
      configDAO = DAOFactory.getInstance().getConfigDAO();
      useDataSource = Boolean.valueOf(configDAO.getProperty("useDataSource")).booleanValue();
      logger.debug("useDataSource set to " + useDataSource);
      if (useDataSource) { // using DataSource
        final String dsjn = configDAO.getProperty("dataSourceJndiName");
        final Context ctx = new InitialContext();
        logger.debug("dataSourceJndiName: " + dsjn);
        dataSource = (DataSource) ctx.lookup(dsjn);
      } else { // using DriverManager
        final String dbDriverClassName = configDAO.getProperty("dbDriverClassName");
        Class.forName(dbDriverClassName).newInstance();
        jdbcUrl = configDAO.getProperty("jdbcUrl");
      }
    } catch (Exception e) {
      throw new AddressBkDAOException(e.toString());
    }
    dbUser = configDAO.getProperty("dbUser");
    dbCredentials = configDAO.getProperty("dbCredentials");
    if ("true".equals(configDAO.getProperty("passwordsBase64Encoded")) && dbCredentials != null) {
      try {
        final InputStream in =
            MimeUtility.decode(
                new ByteArrayInputStream(dbCredentials.getBytes("US-ASCII")), "base64");
        final BufferedReader br = new BufferedReader(new InputStreamReader(in));
        // XXX This assumes there is no new line in the password.
        dbCredentials = br.readLine();
        br.close();
      } catch (MessagingException e) {
        final AddressBkDAOException ae =
            new AddressBkDAOException("MessagingException: " + e.getMessage());
        ae.initCause(e);
        throw ae;

      } catch (UnsupportedEncodingException e) {
        final AddressBkDAOException ae =
            new AddressBkDAOException("UnsupportedEncodingException: " + e.getMessage());
        ae.initCause(e);
        throw ae;

      } catch (IOException e) {
        final AddressBkDAOException ae =
            new AddressBkDAOException("IOException: " + e.getMessage());
        ae.initCause(e);
        throw ae;
      }
    }
    if (dbUser == null
        || dbCredentials == null
        || dbUser.trim().equals("")
        || dbCredentials.trim().equals("")) useDMCredentials = false;
  }
 private ContentType getContentType(Exchange exchange) throws ParseException {
   String contentTypeStr = ExchangeHelper.getContentType(exchange);
   if (contentTypeStr == null) {
     contentTypeStr = DEFAULT_CONTENT_TYPE;
   }
   ContentType contentType = new ContentType(contentTypeStr);
   String contentEncoding = ExchangeHelper.getContentEncoding(exchange);
   // add a charset parameter for text subtypes
   if (contentEncoding != null && contentType.match("text/*")) {
     contentType.setParameter("charset", MimeUtility.mimeCharset(contentEncoding));
   }
   return contentType;
 }
Exemplo n.º 24
0
  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;
  }
Exemplo n.º 25
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;
  }
Exemplo n.º 26
0
  /**
   * <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();
  }
Exemplo n.º 27
0
 @Override
 public void append(final LoggingEvent event) {
   if (evaluator.isTriggeringEvent(event)) {
     try {
       final String subject = limitToFirstLine(String.valueOf(event.getMessage()));
       final String encodedSubject = MimeUtility.encodeText(subject, "UTF-8", null);
       msg.setSubject(encodedSubject);
     } catch (final UnsupportedEncodingException e) {
       // ???
     } catch (final MessagingException e) {
       // ???
     }
   }
   super.append(event);
 }
Exemplo n.º 28
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;
  }
Exemplo n.º 29
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;
  }
Exemplo n.º 30
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;
 }