0
嗨,我一直在研究接收郵件的應用程序。我必須展示主題,正文,附件。問題是當郵件中有可用的附件時,郵件的內容沒有得到顯示。它顯示如[email protected]。我搜索了很多網站,但沒有找到解決方案。請幫助我..接收郵件時出錯[email protected]
我的代碼是
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;
public class EmailAttachReceiver {
String fileName;
public void downloadEmailAttachments(String userName, String password) {
try {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap.gmail.com", userName, password);
Folder folderInbox = store.getFolder("INBOX");
folderInbox.open(Folder.READ_ONLY);
Message[] arrayMessages = folderInbox.getMessages();
for (int i = 0; i < arrayMessages.length; i++) {
//i=arrayMessages.length-1;
Message message = arrayMessages[i];
Address[] fromAddress = message.getFrom();
String from = fromAddress[0].toString();
String subject = message.getSubject();
String sentDate = message.getSentDate().toString();
String contentType = message.getContentType();
String messageContent = "";
String attachFiles = "";
if (contentType.contains("multipart")) {
//System.out.println("contentType 1 "+contentType);
Multipart multiPart = (Multipart) message.getContent();
int numberOfParts = multiPart.getCount();
//System.out.println("numberOfParts 1 "+numberOfParts);
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
// System.out.println("partCount 1 " + partCount);
fileName = part.getFileName();
} else {
// System.out.println("partCount 2 "+partCount);
messageContent = part.getContent().toString();
}
}
} else if (contentType.contains("text/plain")
|| contentType.contains("text/html")) {
//System.out.println("contentType 2 " + contentType);
Object content = message.getContent();
if (content != null) {
messageContent = content.toString();
}
}
System.out.println("Message #" + (i + 1) + ":");
System.out.println("\t From: " + from);
System.out.println("\t Subject: " + subject);
System.out.println("\t Sent Date: " + sentDate);
System.out.println("\t Message: " + messageContent);
System.out.println("\t Attachments: " + fileName);
}
folderInbox.close(false);
store.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
String userName = "";
String password = "";
EmailAttachReceiver receiver = new EmailAttachReceiver();
receiver.downloadEmailAttachments(userName, password);
}
}
明白了......非常感謝你.. – Praveen