Class OpenEmail

java.lang.Object
cloud.opencode.base.email.OpenEmail

public final class OpenEmail extends Object
Email Utility Facade Class 邮件工具门面类

Unified entry point for email sending and receiving operations.

邮件发送和接收操作的统一入口。

Features | 主要功能:

  • Send plain text emails - 发送纯文本邮件
  • Send HTML emails - 发送HTML邮件
  • Send template-based emails - 发送模板邮件
  • Async sending with CompletableFuture - 异步发送
  • Batch sending support - 批量发送支持
  • Receive emails via IMAP/POP3 - 通过IMAP/POP3接收邮件
  • Email query and filtering - 邮件查询和过滤
  • Email management (mark read, delete, move) - 邮件管理(标记已读、删除、移动)
  • Real-time monitoring (IMAP IDLE) - 实时监控(IMAP IDLE)
  • Global configuration - 全局配置

Usage Examples | 使用示例:

// Configure
OpenEmail.configure(EmailConfig.builder()
    .host("smtp.example.com")
    .port(587)
    .username("user@example.com")
    .password("password")
    .starttls(true)
    .defaultFrom("noreply@example.com", "System")
    .build());

// Send simple text email
OpenEmail.sendText("user@example.com", "Hello", "Hello World!");

// Send HTML email
OpenEmail.sendHtml("user@example.com", "Welcome",
    "<h1>Welcome</h1><p>Thanks for signing up!</p>");

// Send template email
OpenEmail.sendTemplate("user@example.com", "Order Confirmation",
    "order-confirm.html",
    Map.of("orderNo", "12345", "amount", "99.00"));

// Send with builder
OpenEmail.send(OpenEmail.email()
    .to("user@example.com")
    .subject("Report")
    .html("<p>See attached report</p>")
    .attach(Path.of("report.pdf"))
    .build());

// Async send
OpenEmail.sendAsync(email)
    .thenRun(() -> log.info("Sent successfully"))
    .exceptionally(e -> { log.error("Failed", e); return null; });

Security | 安全性:

  • Thread-safe: Yes - 线程安全: 是
Since:
JDK 25, opencode-base-email V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • configure

      public static void configure(EmailConfig config)
      Configure default email sender 配置默认邮件发送器
      Parameters:
      config - the email configuration | 邮件配置
    • configure

      public static void configure(String host, int port, String username, String password)
      Quick configuration 快速配置
      Parameters:
      host - SMTP host | SMTP主机
      port - SMTP port | SMTP端口
      username - username | 用户名
      password - password | 密码
    • configure

      public static void configure(EmailConfig config, cloud.opencode.base.email.internal.EmailSender sender)
      Configure with custom sender 使用自定义发送器配置
      Parameters:
      config - the configuration | 配置
      sender - the custom sender | 自定义发送器
    • setTemplateEngine

      public static void setTemplateEngine(cloud.opencode.base.email.internal.EmailTemplate engine)
      Set custom template engine 设置自定义模板引擎
      Parameters:
      engine - the template engine | 模板引擎
    • enableRateLimiting

      public static void enableRateLimiting()
      Configure rate limiter with default limits 使用默认限制配置频率限制器

      Default limits: 10/minute, 100/hour, 1000/day

    • enableRateLimiting

      public static void enableRateLimiting(int maxPerMinute, int maxPerHour, int maxPerDay)
      Configure rate limiter with custom limits 使用自定义限制配置频率限制器
      Parameters:
      maxPerMinute - max emails per minute | 每分钟最大邮件数
      maxPerHour - max emails per hour | 每小时最大邮件数
      maxPerDay - max emails per day | 每天最大邮件数
    • disableRateLimiting

      public static void disableRateLimiting()
      Disable rate limiting 禁用频率限制
    • isRateLimitingEnabled

      public static boolean isRateLimitingEnabled()
      Check if rate limiting is enabled 检查是否启用了频率限制
      Returns:
      true if enabled | 启用返回true
    • getRateLimitQuota

      public static EmailRateLimiter.RateLimitQuota getRateLimitQuota()
      Get remaining rate limit quota (global) 获取剩余频率限制配额(全局)
      Returns:
      the quota or null if rate limiting disabled | 配额,禁用时返回null
    • getRateLimitQuota

      public static EmailRateLimiter.RateLimitQuota getRateLimitQuota(String recipient)
      Get remaining rate limit quota for recipient 获取收件人的剩余频率限制配额
      Parameters:
      recipient - the recipient email | 收件人邮箱
      Returns:
      the quota or null if rate limiting disabled | 配额,禁用时返回null
    • isConfigured

      public static boolean isConfigured()
      Check if configured 检查是否已配置
      Returns:
      true if configured | 已配置返回true
    • getConfig

      public static EmailConfig getConfig()
      Get current configuration 获取当前配置
      Returns:
      the configuration | 配置
    • send

      public static void send(Email email)
      Send email 发送邮件
      Parameters:
      email - the email to send | 要发送的邮件
      Throws:
      EmailException - if sending fails | 发送失败时抛出
    • sendWithResult

      public static SendResult sendWithResult(Email email)
      Send email and return result with message ID 发送邮件并返回包含消息ID的结果
      Parameters:
      email - the email to send | 要发送的邮件
      Returns:
      the send result containing message ID | 包含消息ID的发送结果
      Throws:
      EmailException - if sending fails | 发送失败时抛出
    • sendText

      public static void sendText(String to, String subject, String content)
      Send simple text email 发送简单文本邮件
      Parameters:
      to - recipient email | 收件人邮箱
      subject - email subject | 邮件主题
      content - text content | 文本内容
    • sendHtml

      public static void sendHtml(String to, String subject, String htmlContent)
      Send HTML email 发送HTML邮件
      Parameters:
      to - recipient email | 收件人邮箱
      subject - email subject | 邮件主题
      htmlContent - HTML content | HTML内容
    • sendTemplate

      public static void sendTemplate(String to, String subject, String template, Map<String,Object> variables)
      Send template email 发送模板邮件
      Parameters:
      to - recipient email | 收件人邮箱
      subject - email subject | 邮件主题
      template - template content or path | 模板内容或路径
      variables - template variables | 模板变量
    • sendToMultiple

      public static void sendToMultiple(List<String> recipients, String subject, String content)
      Send to multiple recipients 发送给多个收件人
      Parameters:
      recipients - recipient emails | 收件人邮箱列表
      subject - email subject | 邮件主题
      content - text content | 文本内容
    • sendBatch

      public static BatchSendResult sendBatch(List<Email> emails)
      Send multiple emails using a single SMTP connection (batch mode) 使用单个SMTP连接批量发送邮件

      More efficient than sending individually when sending to multiple recipients.

      当发送给多个收件人时,比逐个发送更高效。

      Parameters:
      emails - the emails to send | 要发送的邮件列表
      Returns:
      the batch result | 批量结果
    • testConnection

      public static ConnectionTestResult testConnection()
      Test SMTP connection with current configuration 使用当前配置测试SMTP连接
      Returns:
      the test result | 测试结果
    • sendAsync

      public static CompletableFuture<Void> sendAsync(Email email)
      Send email asynchronously 异步发送邮件
      Parameters:
      email - the email to send | 要发送的邮件
      Returns:
      future that completes when sent | 发送完成时的future
    • sendAsync

      public static CompletableFuture<Void> sendAsync(Email email, BiConsumer<Email, Throwable> callback)
      Send email asynchronously with callback 使用回调异步发送邮件
      Parameters:
      email - the email to send | 要发送的邮件
      callback - callback on completion | 完成时的回调
      Returns:
      future that completes when sent | 发送完成时的future
    • sendTextAsync

      public static CompletableFuture<Void> sendTextAsync(String to, String subject, String content)
      Send simple text email asynchronously 异步发送简单文本邮件
      Parameters:
      to - recipient email | 收件人邮箱
      subject - email subject | 邮件主题
      content - text content | 文本内容
      Returns:
      future that completes when sent | 发送完成时的future
    • sendHtmlAsync

      public static CompletableFuture<Void> sendHtmlAsync(String to, String subject, String htmlContent)
      Send HTML email asynchronously 异步发送HTML邮件
      Parameters:
      to - recipient email | 收件人邮箱
      subject - email subject | 邮件主题
      htmlContent - HTML content | HTML内容
      Returns:
      future that completes when sent | 发送完成时的future
    • sendAllAsync

      public static List<CompletableFuture<Void>> sendAllAsync(List<Email> emails)
      Send multiple emails asynchronously 异步发送多封邮件
      Parameters:
      emails - the emails to send | 要发送的邮件列表
      Returns:
      list of futures | future列表
    • sendAllAndWait

      public static CompletableFuture<Void> sendAllAndWait(List<Email> emails)
      Send multiple emails and wait for completion 发送多封邮件并等待完成
      Parameters:
      emails - the emails to send | 要发送的邮件列表
      Returns:
      future that completes when all sent | 全部发送完成时的future
    • configureReceiver

      public static void configureReceiver(EmailReceiveConfig config)
      Configure email receiver 配置邮件接收器
      Parameters:
      config - the receive configuration | 接收配置
    • configureReceiver

      public static void configureReceiver(String host, String username, String password, boolean useImap)
      Quick receiver configuration 快速接收器配置
      Parameters:
      host - mail server host | 邮件服务器主机
      username - username | 用户名
      password - password | 密码
      useImap - true for IMAP, false for POP3 | true使用IMAP,false使用POP3
    • configureReceiver

      public static void configureReceiver(EmailReceiveConfig config, cloud.opencode.base.email.internal.EmailReceiver receiver)
      Configure receiver with custom implementation 使用自定义实现配置接收器
      Parameters:
      config - the configuration | 配置
      receiver - the custom receiver | 自定义接收器
    • isReceiverConfigured

      public static boolean isReceiverConfigured()
      Check if receiver is configured 检查接收器是否已配置
      Returns:
      true if configured | 已配置返回true
    • getReceiveConfig

      public static EmailReceiveConfig getReceiveConfig()
      Get current receive configuration 获取当前接收配置
      Returns:
      the receive configuration | 接收配置
    • receiveUnread

      public static List<ReceivedEmail> receiveUnread()
      Receive unread emails from default folder 从默认文件夹接收未读邮件
      Returns:
      list of received emails | 接收到的邮件列表
    • receive

      public static List<ReceivedEmail> receive(EmailQuery query)
      Receive emails with query 使用查询接收邮件
      Parameters:
      query - the email query | 邮件查询
      Returns:
      list of received emails | 接收到的邮件列表
    • receiveAll

      public static List<ReceivedEmail> receiveAll()
      Receive all emails from default folder 从默认文件夹接收所有邮件
      Returns:
      list of received emails | 接收到的邮件列表
    • receiveById

      public static ReceivedEmail receiveById(String messageId)
      Receive email by message ID 通过消息ID接收邮件
      Parameters:
      messageId - the message ID | 消息ID
      Returns:
      the received email or null | 接收到的邮件或null
    • getMessageCount

      public static int getMessageCount(String folder)
      Get message count in folder 获取文件夹中的消息数量
      Parameters:
      folder - the folder name | 文件夹名称
      Returns:
      the message count | 消息数量
    • getUnreadCount

      public static int getUnreadCount(String folder)
      Get unread message count in folder 获取文件夹中的未读消息数量
      Parameters:
      folder - the folder name | 文件夹名称
      Returns:
      the unread count | 未读数量
    • markAsRead

      public static void markAsRead(String messageId)
      Mark email as read 标记邮件为已读
      Parameters:
      messageId - the message ID | 消息ID
    • markAsUnread

      public static void markAsUnread(String messageId)
      Mark email as unread 标记邮件为未读
      Parameters:
      messageId - the message ID | 消息ID
    • setFlagged

      public static void setFlagged(String messageId, boolean flagged)
      Set email flagged status 设置邮件标记状态
      Parameters:
      messageId - the message ID | 消息ID
      flagged - true to flag, false to unflag | true为标记,false为取消标记
    • delete

      public static void delete(String messageId)
      Delete email 删除邮件
      Parameters:
      messageId - the message ID | 消息ID
    • moveToFolder

      public static void moveToFolder(String messageId, String targetFolder)
      Move email to folder (IMAP only) 移动邮件到文件夹(仅IMAP)
      Parameters:
      messageId - the message ID | 消息ID
      targetFolder - the target folder | 目标文件夹
    • listFolders

      public static List<String> listFolders()
      List available folders 列出可用文件夹
      Returns:
      list of folder names | 文件夹名称列表
    • receiveUnreadAsync

      public static CompletableFuture<List<ReceivedEmail>> receiveUnreadAsync()
      Receive unread emails asynchronously 异步接收未读邮件
      Returns:
      future containing received emails | 包含接收邮件的future
    • receiveAsync

      public static CompletableFuture<List<ReceivedEmail>> receiveAsync(EmailQuery query)
      Receive emails asynchronously with query 使用查询异步接收邮件
      Parameters:
      query - the email query | 邮件查询
      Returns:
      future containing received emails | 包含接收邮件的future
    • receiveAsync

      public static CompletableFuture<List<ReceivedEmail>> receiveAsync(EmailQuery query, BiConsumer<List<ReceivedEmail>, Throwable> callback)
      Receive emails asynchronously with callback 使用回调异步接收邮件
      Parameters:
      query - the email query | 邮件查询
      callback - callback on completion | 完成时的回调
      Returns:
      future containing received emails | 包含接收邮件的future
    • markAsReadAsync

      public static CompletableFuture<Void> markAsReadAsync(String messageId)
      Mark email as read asynchronously 异步标记邮件为已读
      Parameters:
      messageId - the message ID | 消息ID
      Returns:
      future that completes when done | 完成时的future
    • deleteAsync

      public static CompletableFuture<Void> deleteAsync(String messageId)
      Delete email asynchronously 异步删除邮件
      Parameters:
      messageId - the message ID | 消息ID
      Returns:
      future that completes when done | 完成时的future
    • createMonitor

      public static EmailIdleMonitor createMonitor(EmailListener listener)
      Create email monitor for real-time notifications 创建邮件监控器用于实时通知
      Parameters:
      listener - the email listener | 邮件监听器
      Returns:
      the monitor | 监控器
    • createMonitor

      public static EmailIdleMonitor createMonitor(String folder, EmailListener listener)
      Create email monitor for specific folder 为特定文件夹创建邮件监控器
      Parameters:
      folder - the folder to monitor | 要监控的文件夹
      listener - the email listener | 邮件监听器
      Returns:
      the monitor | 监控器
    • query

      public static EmailQuery.Builder query()
      Create email query builder 创建邮件查询构建器
      Returns:
      the query builder | 查询构建器
    • receiveConfig

      public static EmailReceiveConfig.Builder receiveConfig()
      Create receive configuration builder 创建接收配置构建器
      Returns:
      the receive config builder | 接收配置构建器
    • email

      public static Email.Builder email()
      Create email builder with default from address 创建带默认发件人的邮件构建器
      Returns:
      the email builder | 邮件构建器
    • config

      public static EmailConfig.Builder config()
      Create configuration builder 创建配置构建器
      Returns:
      the config builder | 配置构建器
    • shutdown

      public static void shutdown()
      Shutdown all resources (call on application shutdown) 关闭所有资源(应用关闭时调用)
    • shutdownSender

      public static void shutdownSender()
      Shutdown only sender resources 仅关闭发送器资源
    • shutdownReceiver

      public static void shutdownReceiver()
      Shutdown only receiver resources 仅关闭接收器资源