本文為IMAP下載郵件Java代碼調用樣本。
import java.io.FileOutputStream;
import java.io.File;
import java.util.Properties;
import javax.mail.*;
public class ImapEmailDownloader {
public static void main(String[] args) {
// 郵件伺服器配置
String host = "imap.sg.aliyun.com";
String username = "";
String password = "";
// 串連屬性配置
Properties properties = new Properties();
properties.put("mail.store.protocol", "imap");
properties.put("mail.imap.host", host);
properties.put("mail.imap.port", "993");
properties.put("mail.imap.ssl.enable", "true");
//properties.put("mail.imap.ssl.protocols", "TLSv1.2");//如遇到報錯SSLHandshakeException可去掉注釋後重試
//本地檔案夾路徑,請換成實際的檔案夾路徑。
String folderPath = "D:\\檔案夾1\\檔案夾1-1";
try {
// 建立會話對象
Session session = Session.getDefaultInstance(properties);
// 串連到郵件伺服器
Store store = session.getStore();
store.connect(username, password);
// 開啟收件匣
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
// 擷取郵件清單
Message[] messages = inbox.getMessages();
// 遍曆郵件並下載EML格式的郵件
for (Message message : messages) {
String subject = message.getSubject();
String fileName = subject + ".eml";
//構建本地檔案路徑
String filePath = folderPath + File.separator + fileName;
//下載郵件到本地檔案夾
FileOutputStream fos = new FileOutputStream(filePath);
message.writeTo(fos);
System.out.println("下載郵件:" + fileName);
}
// 關閉串連
inbox.close(false);
store.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}