この記事では、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 = "";
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");
// ローカルフォルダのパスです。実際のフォルダパスに置き換えてください。
String folderPath = "D:\\Folder 1\\Folder 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();
}
}
}