Sha*_*anu 4 java pdf imap jakarta-mail email-attachments
我正在使用JavaMail API创建电子邮件客户端。一切正常,就像我能够连接到邮件服务器(使用IMAP),删除邮件,检索收到的邮件并将其显示给用户等。
现在下载“ PDF附件”时出现问题。PDF文件未完全下载...缺少某些文件。
如果当我使用IE或任何其他Web浏览器下载附件时,某些PDF附件的大小为38 Kb,但是当我使用Java代码下载附件时,其大小为37.3 Kb。它不完整因此,当我尝试使用Adobe Reader打开它时,它显示错误消息“文件已损坏...”。
这是我编写的用于下载附件的代码:
public boolean saveFile(String filename,Part part) throws IOException, MessagingException {
boolean ren = true;
FileOutputStream fos = null;
BufferedInputStream fin = null;
InputStream input = part.getInputStream();
File pdffile = new File("d:/"+filename);
try{
if(!pdffile.exists()){
fos = new FileOutputStream(pdffile);
fin = new BufferedInputStream(input);
int size = 512;
byte[] buf = new byte[size];
int len;
while ( (len = fin.read(buf)) != -1 ) {
fos.write(buf, 0, len);
}
input.close();
fos.close();
}else{
System.out.println("File already exists");
}
}catch(Exception e ){
ren = false;
}
return ren;
}
Run Code Online (Sandbox Code Playgroud)
我想念什么吗?任何有用的帮助表示赞赏。
花了几个小时,终于弄明白了。
props.setProperty("mail.imaps.partialfetch", "false");
Run Code Online (Sandbox Code Playgroud)
为我做了。与上面的@Shantanu几乎相同,但是因为我正在使用
store = session.getStore("imaps");
Run Code Online (Sandbox Code Playgroud)
我还需要对部分获取使用“ imap s ”。
奇迹般有效。
完整代码如下:
// Load mail properties
Properties mailProperties = System.getProperties();
mailProperties.put("mail.mime.base64.ignoreerrors", "true");
mailProperties.put("mail.imaps.partialfetch", "false");
// Connect to Gmail
Session session = Session.getInstance(mailProperties, null);
store = session.getStore("imaps");
store.connect("imap.gmail.com", -1, "username", "password");
// Access label folder
Folder defaultFolder = store.getDefaultFolder();
Folder labelFolder = defaultFolder.getFolder("mylabel");
labelFolder.open(Folder.READ_WRITE);
Message[] messages = labelFolder.getMessages();
saveAttachments(messages);
Run Code Online (Sandbox Code Playgroud)
...
private void saveAttachments(Message[] messages) throws Exception {
for (Message msg : messages) {
if (msg.getContent() instanceof Multipart) {
Multipart multipart = (Multipart) msg.getContent();
for (int i = 0; i < multipart.getCount(); i++) {
Part part = multipart.getBodyPart(i);
String disposition = part.getDisposition();
if ((disposition != null) &&
((disposition.equalsIgnoreCase(Part.ATTACHMENT) ||
(disposition.equalsIgnoreCase(Part.INLINE))))) {
MimeBodyPart mimeBodyPart = (MimeBodyPart) part;
String fileName = mimeBodyPart.getFileName();
File fileToSave = new File(fileName);
mimeBodyPart.saveFile(fileToSave);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)