保存电子邮件附件



有人能建议我如何使用Java保存电子邮件附件吗?它是加密文件(PGP)。我需要保存它并用于解密。我使用这个代码:

String host = "mail.foxbox.lt";
String user = "user";
String password = "pass";
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance(properties);
Store store = session.getStore("pop3");
store.connect(host, user, password);
Folder folder = store.getFolder("inbox");
folder.open(Folder.READ_WRITE);
Message[] message = folder.getMessages();
for (int a = message.length-1; a < message.length; a++) {
     Multipart multipart = (Multipart) message[a].getContent();
     for (int i = 0; i < multipart.getCount(); i++) {
          BodyPart bodyPart = multipart.getBodyPart(i);
          InputStream stream = bodyPart.getInputStream();
          if (Part.ATTACHMENT.equals(bodyPart.getDisposition())) {
               BufferedReader br = new BufferedReader(new InputStreamReader(stream));
               FileWriter fstream = new FileWriter("AAA001.txt.pgp");
               BufferedWriter out = new BufferedWriter(fstream);
               int y;
               while ((y = stream.read()) != -1) {
                    out.write(y);
               }
               stream.close();
               out.close();
          }
     }
     System.out.println();
}
folder.close(true);
store.close();

但它只适用于文本文件(字符串)。在我的情况下,它会更改.pgp文件,并给我解密错误。如何在没有任何流的情况下保存文件?谢谢

问题是您使用了BufferedReaderBufferedWriter。这些用于字符流。将使用默认平台编码将从附件中读取的字节序列转换为Unicode字符代码点(char类型),反之亦然。在编码或解码过程中,不可映射的字符可能会被替换或从流中删除。

必须使用普通InputStream读取附件,使用FileOutputStream写入文件:

InputStream stream = bodyPart.getInputStream();
if (Part.ATTACHMENT.equals(bodyPart.getDisposition())) {
    FileOutputStream fstream = new FileOutputStream("AAA001.txt.pgp");
    byte[] buffer = new byte[1024];
    int len;
    while ((len = stream.read(buffer)) != -1) {
        fstream.write(buffer, 0, len);
    }
    fstream.close();
}
stream.close();

还有其他方法可以将InputStream的内容复制到OutputStream,请参阅此问题和答案。

试试这个:

String host = "host";
String user = "user";
String password = "pass";
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance(properties);
Store store = session.getStore("pop3");
store.connect(host, user, password);
Folder folder = store.getFolder("inbox");
folder.open(Folder.READ_WRITE);
Message[] message = folder.getMessages();
for (int a = message.length-1; a < message.length; a++) {
        Multipart multipart = (Multipart) message[a].getContent();    
  for (int i = 0; i < multipart.getCount(); i++) {
      BodyPart bodyPart = multipart.getBodyPart(i);           
      InputStream is = bodyPart.getInputStream();
      File f = new File("/tmp/" + bodyPart.getFileName());
      FileOutputStream fos = new FileOutputStream(f);
      byte[] buf = new byte[4096];
      int bytesRead;
      while((bytesRead = is.read(buf))!=-1) {
          fos.write(buf, 0, bytesRead);
      }
      fos.close();
      attachments.add(f);
    }
  }
  folder.close(true);
  store.close();
 }

相关内容

  • 没有找到相关文章

最新更新