• Index

接收 Email

Last updated: ... / Reads: 43 Edit

要在Java中接收电子邮件,你可以使用JavaMail API。下面是一个简单的示例代码,演示如何通过POP3协议接收电子邮件:

import java.util.Properties;
import javax.mail.*;

public class EmailReceiver {
    public static void main(String[] args) {
        // 邮箱配置信息
        String host = "pop.example.com"; // POP3服务器地址
        String username = "your_username"; // 邮箱用户名
        String password = "your_password"; // 邮箱密码

        try {
            // 创建会话对象
            Properties properties = new Properties();
            properties.put("mail.store.protocol", "pop3");
            Session session = Session.getDefaultInstance(properties);

            // 连接到邮箱
            Store store = session.getStore("pop3");
            store.connect(host, username, password);

            // 打开收件箱
            Folder inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);

            // 获取收件箱中的邮件数量
            int messageCount = inbox.getMessageCount();
            System.out.println("Total Messages: " + messageCount);

            // 遍历并打印每封邮件的主题和发件人
            Message[] messages = inbox.getMessages();
            for (int i = 0; i < messages.length; i++) {
                Message message = messages[i];
                System.out.println("Subject: " + message.getSubject());
                System.out.println("From: " + message.getFrom()[0]);
            }

            // 关闭连接
            inbox.close(false);
            store.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

请确保将上述代码中的 host、username 和 password 替换为你自己的邮箱服务器地址、用户名和密码。此外,你还需要将 JavaMail API 添加到项目的依赖中。

这段代码连接到指定的POP3服务器,并使用提供的用户名和密码进行身份验证。然后,它打开收件箱并获取邮件数量。最后,它遍历每封邮件并打印主题和发件人信息。

请注意,根据你所使用的电子邮件服务提供商和安全设置,可能需要对代码进行一些调整。具体来说,你可能需要更改服务器地址、端口号以及使用 SSL/TLS 进行加密等设置。


Comments

Make a comment

  • Index