Class ImapClient
- All Implemented Interfaces:
AutoCloseable
Implements the IMAP4rev1 protocol (RFC 3501) for mailbox access, message retrieval, folder management, and IDLE push notifications. Supports LOGIN and XOAUTH2 authentication, STARTTLS upgrade, and literal data handling.
实现 IMAP4rev1 协议 (RFC 3501),支持邮箱访问、邮件检索、文件夹管理和 IDLE 推送通知。支持 LOGIN 和 XOAUTH2 认证、STARTTLS 升级及字面量数据处理。
try (var client = new ImapClient("imap.example.com", 993, true, false,
Duration.ofSeconds(10), Duration.ofSeconds(30))) {
client.connect();
client.login("user@example.com", "password");
int[] counts = client.select("INBOX");
System.out.println("Messages: " + counts[0] + ", Recent: " + counts[1]);
List<Integer> unseen = client.search("UNSEEN");
for (int seq : unseen) {
String data = client.fetch(seq, "(ENVELOPE BODY[HEADER])");
System.out.println(data);
}
client.logout();
}
- Since:
- JDK 25, opencode-base-email V1.0.3
- Author:
- Leon Soo
- See Also:
-
Constructor Summary
ConstructorsConstructorDescriptionImapClient(String host, int port, boolean ssl, boolean starttls, Duration connectionTimeout, Duration readTimeout) Create a new IMAP client 创建新的 IMAP 客户端 -
Method Summary
Modifier and TypeMethodDescriptionvoidauthenticateXOAuth2(String username, String token) Authenticate using XOAUTH2 mechanism 使用 XOAUTH2 机制进行认证voidclose()Close the IMAP client, logging out if connected 关闭 IMAP 客户端,如已连接则先注销voidconnect()Connect to the IMAP server and read the greeting 连接到 IMAP 服务器并读取问候语voidCopy a message to another folder 复制邮件到另一个文件夹int[]Examine a folder for read-only access 以只读方式检查文件夹voidexpunge()Permanently remove messages marked with \Deleted flag 永久删除标记为 \Deleted 的邮件Fetch data for a single message 获取单条邮件的数据fetchRange(int from, int to, String fetchItems) Fetch data for a range of messages 获取一系列邮件的数据Get all server capabilities 获取所有服务器能力intGet the total number of messages in the selected folder 获取所选文件夹中的邮件总数Get the currently selected folder name 获取当前选中的文件夹名称intGet the count of unread (unseen) messages in the selected folder 获取所选文件夹中未读(未查看)邮件的数量booleanhasCapability(String cap) Check if the server advertises the given capability 检查服务器是否公布了给定的能力Enter IDLE mode and wait for server notifications 进入 IDLE 模式等待服务器通知booleanCheck if the client is connected to the server 检查客户端是否已连接到服务器List folders matching a pattern 列出匹配模式的文件夹voidAuthenticate using LOGIN command 使用 LOGIN 命令进行认证voidlogout()Logout from the server and close the connection 从服务器注销并关闭连接voidnoop()Send NOOP command to keep the connection alive 发送 NOOP 命令以保持连接活跃Search for messages matching the given criteria 搜索匹配给定条件的邮件int[]Select a folder for read-write access 选择文件夹以读写方式打开voidStore flags on a message 设置邮件的标志
-
Constructor Details
-
ImapClient
public ImapClient(String host, int port, boolean ssl, boolean starttls, Duration connectionTimeout, Duration readTimeout) Create a new IMAP client 创建新的 IMAP 客户端- Parameters:
host- the IMAP server hostname | IMAP 服务器主机名port- the IMAP server port | IMAP 服务器端口ssl- true for implicit SSL/TLS (e.g., port 993) | true 使用隐式 SSL/TLS(如 993 端口)starttls- true to upgrade via STARTTLS after connect | true 连接后通过 STARTTLS 升级connectionTimeout- connection timeout | 连接超时readTimeout- read timeout | 读取超时- Throws:
IllegalArgumentException- if host is null/blank, port is invalid, or timeouts are null/negative | 主机为空、端口无效或超时为空/负值时抛出
-
-
Method Details
-
connect
Connect to the IMAP server and read the greeting 连接到 IMAP 服务器并读取问候语Connects the underlying socket, reads the server greeting (which must start with
* OK), and parses any capabilities advertised in the greeting. If STARTTLS is enabled, upgrades to TLS before proceeding.连接底层套接字,读取服务器问候语(必须以
* OK开头), 并解析问候语中公布的能力。如果启用了 STARTTLS,则在继续之前升级到 TLS。- Throws:
ProtocolException- if connection or greeting fails | 连接或问候语失败时抛出
-
login
Authenticate using LOGIN command 使用 LOGIN 命令进行认证Sends the IMAP LOGIN command with the given username and password. Credentials are quoted according to IMAP string quoting rules.
使用给定的用户名和密码发送 IMAP LOGIN 命令。 凭证按照 IMAP 字符串引用规则进行转义。
- Parameters:
username- the login username | 登录用户名password- the login password | 登录密码- Throws:
ProtocolException- if authentication fails | 认证失败时抛出
-
authenticateXOAuth2
Authenticate using XOAUTH2 mechanism 使用 XOAUTH2 机制进行认证Sends the IMAP AUTHENTICATE XOAUTH2 command with a Base64-encoded SASL client response containing the username and OAuth2 bearer token.
使用 Base64 编码的 SASL 客户端响应发送 IMAP AUTHENTICATE XOAUTH2 命令, 响应中包含用户名和 OAuth2 Bearer 令牌。
- Parameters:
username- the email address | 电子邮件地址token- the OAuth2 access token | OAuth2 访问令牌- Throws:
ProtocolException- if authentication fails | 认证失败时抛出- See Also:
-
select
Select a folder for read-write access 选择文件夹以读写方式打开Issues the IMAP SELECT command to open the specified folder for read-write access. Parses EXISTS and RECENT counts from the response.
发出 IMAP SELECT 命令以读写方式打开指定文件夹。 从响应中解析 EXISTS 和 RECENT 计数。
- Parameters:
folder- the folder name (e.g., "INBOX") | 文件夹名称(如 "INBOX")- Returns:
- an array of
[exists, recent]counts | 包含[exists, recent]计数的数组 - Throws:
ProtocolException- if the SELECT fails | SELECT 失败时抛出
-
examine
Examine a folder for read-only access 以只读方式检查文件夹Issues the IMAP EXAMINE command to open the specified folder for read-only access. Parses EXISTS and RECENT counts from the response.
发出 IMAP EXAMINE 命令以只读方式打开指定文件夹。 从响应中解析 EXISTS 和 RECENT 计数。
- Parameters:
folder- the folder name (e.g., "INBOX") | 文件夹名称(如 "INBOX")- Returns:
- an array of
[exists, recent]counts | 包含[exists, recent]计数的数组 - Throws:
ProtocolException- if the EXAMINE fails | EXAMINE 失败时抛出
-
search
Search for messages matching the given criteria 搜索匹配给定条件的邮件Issues the IMAP SEARCH command with the specified criteria string. Returns message sequence numbers matching the criteria.
使用指定的条件字符串发出 IMAP SEARCH 命令。 返回匹配条件的邮件序列号。
- Parameters:
criteria- the IMAP search criteria (e.g., "UNSEEN", "SINCE 1-Jan-2024") | IMAP 搜索条件(如 "UNSEEN"、"SINCE 1-Jan-2024")- Returns:
- a list of message sequence numbers | 邮件序列号列表
- Throws:
ProtocolException- if the SEARCH fails | SEARCH 失败时抛出
-
fetch
Fetch data for a single message 获取单条邮件的数据Issues the IMAP FETCH command for the specified message sequence number. Returns the raw response data including any literal content.
对指定的邮件序列号发出 IMAP FETCH 命令。 返回原始响应数据,包含字面量内容。
- Parameters:
msgSeq- the message sequence number (1-based) | 邮件序列号(从 1 开始)fetchItems- the fetch data items, e.g., "(ENVELOPE BODY[] FLAGS)" | 获取的数据项,如 "(ENVELOPE BODY[] FLAGS)"- Returns:
- the raw FETCH response data | 原始 FETCH 响应数据
- Throws:
ProtocolException- if the FETCH fails | FETCH 失败时抛出
-
fetchRange
Fetch data for a range of messages 获取一系列邮件的数据Issues a single IMAP FETCH command for a range of message sequence numbers. Returns a map from sequence number to the raw response data for that message.
对一系列邮件序列号发出单个 IMAP FETCH 命令。 返回序列号到该邮件原始响应数据的映射。
- Parameters:
from- the starting sequence number (inclusive) | 起始序列号(包含)to- the ending sequence number (inclusive) | 结束序列号(包含)fetchItems- the fetch data items | 获取的数据项- Returns:
- a map of sequence number to raw response data | 序列号到原始响应数据的映射
- Throws:
ProtocolException- if the FETCH fails | FETCH 失败时抛出
-
store
Store flags on a message 设置邮件的标志Issues the IMAP STORE command to modify flags on the specified message.
发出 IMAP STORE 命令以修改指定邮件的标志。
- Parameters:
msgSeq- the message sequence number (1-based) | 邮件序列号(从 1 开始)action- the flag action: "+FLAGS", "-FLAGS", or "FLAGS" | 标志操作:"+FLAGS"、"-FLAGS" 或 "FLAGS"flags- the flags, e.g., "(\\Seen)" or "(\\Deleted)" | 标志,如 "(\\Seen)" 或 "(\\Deleted)"- Throws:
ProtocolException- if the STORE fails | STORE 失败时抛出
-
copy
Copy a message to another folder 复制邮件到另一个文件夹Issues the IMAP COPY command to copy the specified message to the target folder.
发出 IMAP COPY 命令将指定邮件复制到目标文件夹。
- Parameters:
msgSeq- the message sequence number (1-based) | 邮件序列号(从 1 开始)targetFolder- the destination folder name | 目标文件夹名称- Throws:
ProtocolException- if the COPY fails | COPY 失败时抛出
-
expunge
Permanently remove messages marked with \Deleted flag 永久删除标记为 \Deleted 的邮件Issues the IMAP EXPUNGE command to permanently remove all messages in the selected folder that have the \Deleted flag set.
发出 IMAP EXPUNGE 命令以永久删除所选文件夹中 设置了 \Deleted 标志的所有邮件。
- Throws:
ProtocolException- if the EXPUNGE fails | EXPUNGE 失败时抛出
-
list
List folders matching a pattern 列出匹配模式的文件夹Issues the IMAP LIST command to list folders matching the given reference and pattern. Returns each folder as a
[flags, delimiter, name]array.发出 IMAP LIST 命令列出匹配给定引用和模式的文件夹。 每个文件夹以
[flags, delimiter, name]数组形式返回。- Parameters:
reference- the reference name (e.g., "" for root) | 引用名(如 "" 表示根目录)pattern- the folder pattern (e.g., "*" for all) | 文件夹模式(如 "*" 表示全部)- Returns:
- a list of
[flags, delimiter, name]arrays |[flags, delimiter, name]数组列表 - Throws:
ProtocolException- if the LIST fails | LIST 失败时抛出
-
idle
Enter IDLE mode and wait for server notifications 进入 IDLE 模式等待服务器通知Issues the IMAP IDLE command to enter push notification mode. Blocks until the server sends untagged responses (e.g., new mail notifications) or the specified timeout is reached. Automatically sends DONE to exit IDLE mode before returning.
发出 IMAP IDLE 命令进入推送通知模式。 阻塞直到服务器发送未标记响应(如新邮件通知)或达到指定超时时间。 返回前自动发送 DONE 以退出 IDLE 模式。
- Parameters:
timeout- the maximum time to remain in IDLE mode | IDLE 模式的最大等待时间- Returns:
- the untagged responses received during IDLE | IDLE 期间接收到的未标记响应
- Throws:
ProtocolException- if IDLE is not supported or fails | 不支持 IDLE 或失败时抛出
-
noop
Send NOOP command to keep the connection alive 发送 NOOP 命令以保持连接活跃Issues the IMAP NOOP command which has no effect on the server state but resets idle timers and may trigger pending untagged notifications.
发出 IMAP NOOP 命令,该命令不影响服务器状态, 但会重置空闲计时器并可能触发待处理的未标记通知。
- Throws:
ProtocolException- if the NOOP fails | NOOP 失败时抛出
-
getMessageCount
Get the total number of messages in the selected folder 获取所选文件夹中的邮件总数Issues a STATUS command on the currently selected folder to retrieve the MESSAGES count.
对当前选中的文件夹发出 STATUS 命令以获取 MESSAGES 计数。
- Returns:
- the message count | 邮件数量
- Throws:
ProtocolException- if the command fails | 命令失败时抛出
-
getUnreadCount
Get the count of unread (unseen) messages in the selected folder 获取所选文件夹中未读(未查看)邮件的数量Issues a SEARCH UNSEEN command and returns the count of matching message sequence numbers.
发出 SEARCH UNSEEN 命令并返回匹配的邮件序列号数量。
- Returns:
- the unread message count | 未读邮件数量
- Throws:
ProtocolException- if the SEARCH fails | SEARCH 失败时抛出
-
logout
Logout from the server and close the connection 从服务器注销并关闭连接Issues the IMAP LOGOUT command, reads the BYE response, and closes the underlying socket connection.
发出 IMAP LOGOUT 命令,读取 BYE 响应,并关闭底层套接字连接。
- Throws:
ProtocolException- if the LOGOUT fails | LOGOUT 失败时抛出
-
close
public void close()Close the IMAP client, logging out if connected 关闭 IMAP 客户端,如已连接则先注销Attempts a graceful LOGOUT before closing the connection. Any errors during logout are silently ignored.
在关闭连接前尝试正常注销。注销过程中的任何错误将被静默忽略。
- Specified by:
closein interfaceAutoCloseable
-
hasCapability
Check if the server advertises the given capability 检查服务器是否公布了给定的能力- Parameters:
cap- the capability name (case-insensitive) | 能力名称(不区分大小写)- Returns:
- true if the capability is present | 如果存在该能力返回 true
-
getCapabilities
-
isConnected
public boolean isConnected()Check if the client is connected to the server 检查客户端是否已连接到服务器- Returns:
- true if connected | 已连接返回 true
-
getSelectedFolder
Get the currently selected folder name 获取当前选中的文件夹名称- Returns:
- the selected folder name, or null if none is selected | 选中的文件夹名称,未选中则返回 null
-