JavaMail学习笔记(五)、使用IMAP协议接收并解析电子邮件

package org.yangxin.study.jm;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;
 
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeUtility;
 
import com.sun.mail.imap.IMAPMessage;
 
/**
 * <b>使用IMAP协议接收邮件</b><br/>
 * <p>POP3和IMAP协议的区别:</p>
 * <b>POP3</b>协议允许电子邮件客户端下载服务器上的邮件,但是在客户端的操作(如移动邮件、标记已读等),不会反馈到服务器上,<br/>
 * 比如通过客户端收取了邮箱中的3封邮件并移动到其它文件夹,邮箱服务器上的这些邮件是没有同时被移动的。<br/>
 * <p><b>IMAP</b>协议提供webmail与电子邮件客户端之间的双向通信,客户端的操作都会同步反应到服务器上,对邮件进行的操作,服务
 * 上的邮件也会做相应的动作。比如在客户端收取了邮箱中的3封邮件,并将其中一封标记为已读,将另外两封标记为删除,这些操作会
 * 即时反馈到服务器上。</p>
 * <p>两种协议相比,IMAP 整体上为用户带来更为便捷和可靠的体验。POP3更易丢失邮件或多次下载相同的邮件,但IMAP通过邮件客户端
 * 与webmail之间的双向同步功能很好地避免了这些问题。</p>
 */
public class IMAPReceiveMailTest {
 
	public static void main(String[] args) throws Exception {
		// 准备连接服务器的会话信息
		Properties props = new Properties();
		props.setProperty("mail.store.protocol", "imap");
		props.setProperty("mail.imap.host", "imap.163.com");
		props.setProperty("mail.imap.port", "143");
		
		// 创建Session实例对象
		Session session = Session.getInstance(props);
		
		// 创建IMAP协议的Store对象
		Store store = session.getStore("imap");
		
		// 连接邮件服务器
		store.connect("xyang0917@163.com", "123456abc");
		
		// 获得收件箱
		Folder folder = store.getFolder("INBOX");
		// 以读写模式打开收件箱
		folder.open(Folder.READ_WRITE);
		
		// 获得收件箱的邮件列表
		Message[] messages = folder.getMessages();
		
		// 打印不同状态的邮件数量
		System.out.println("收件箱中共" + messages.length + "封邮件!");
		System.out.println("收件箱中共" + folder.getUnreadMessageCount() + "封未读邮件!");
		System.out.println("收件箱中共" + folder.getNewMessageCount() + "封新邮件!");
		System.out.println("收件箱中共" + folder.getDeletedMessageCount() + "封已删除邮件!");
		
		System.out.println("------------------------开始解析邮件----------------------------------");
		
		// 解析邮件
		for (Message message : messages) {
			IMAPMessage msg = (IMAPMessage) message;
			String subject = MimeUtility.decodeText(msg.getSubject());
			System.out.println("[" + subject + "]未读,是否需要阅读此邮件(yes/no)?");
			BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
			String answer = reader.readLine();
			if ("yes".equalsIgnoreCase(answer)) {
				POP3ReceiveMailTest.parseMessage(msg);	// 解析邮件
				// 第二个参数如果设置为true,则将修改反馈给服务器。false则不反馈给服务器
				msg.setFlag(Flag.SEEN, true);	//设置已读标志
			}
		}
		
		// 关闭资源
		folder.close(false);
		store.close();
	}
}

测试结果:



原文链接:https://blog.csdn.net/xyang81/article/details/7675162
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
是的,Spring Boot 中可以使用 JavaMail API 来读取 IMAP 邮件的附件并保存附件。JavaMail API 是 Java EE 平台中用于发送和接收电子邮件的标准 API,它提供了一组类和接口,使开发人员可以轻松地编写邮件客户端程序。 以下是一个示例代码,演示如何在 Spring Boot 中使用 JavaMail API 来读取 IMAP 邮件的附件并保存附件: ```java import java.io.File; import java.io.IOException; import java.util.Properties; import javax.mail.BodyPart; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.MimeBodyPart; import javax.mail.search.FlagTerm; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class MailReader { @Value("${mail.username}") private String username; @Value("${mail.password}") private String password; @Value("${mail.imap.host}") private String imapHost; @Value("${mail.imap.port}") private int imapPort; public void readAndSaveAttachments() { try { Properties properties = new Properties(); properties.put("mail.imap.host", imapHost); properties.put("mail.imap.port", imapPort); properties.put("mail.imap.ssl.enable", "true"); Session session = Session.getDefaultInstance(properties); Store store = session.getStore("imap"); store.connect(username, password); Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); // Search for unread messages FlagTerm flagTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false); Message[] messages = inbox.search(flagTerm); for (Message message : messages) { Multipart multipart = (Multipart) message.getContent(); // Get all the attachments for (int i = 0; i < multipart.getCount(); i++) { BodyPart bodyPart = multipart.getBodyPart(i); // If the bodypart is an attachment if (bodyPart.getDisposition() != null && bodyPart.getDisposition().equalsIgnoreCase("attachment")) { MimeBodyPart mimeBodyPart = (MimeBodyPart) bodyPart; File file = new File(mimeBodyPart.getFileName()); // Save the attachment to a file mimeBodyPart.saveFile(file); } } // Mark the message as read message.setFlag(Flags.Flag.SEEN, true); } inbox.close(false); store.close(); } catch (MessagingException | IOException e) { e.printStackTrace(); } } } ``` 在上面的代码中,我们首先创建了一个 Properties 对象,用于配置连接到 IMAP 服务器的参数。然后,我们使用该 Properties 对象创建一个 Session 对象,并使用 Session 对象创建一个 Store 对象来连接到 IMAP 服务器。接下来,我们打开收件箱 Folder 对象,并使用 FlagTerm 对象搜索未读邮件。对于每个未读邮件,我们获取其内容并将其转换为 Multipart 对象。然后,我们遍历 Multipart 对象的所有 BodyPart 对象,并找到所有附件。对于每个附件,我们将其保存到一个文件中,并将消息标记为已读。 请注意,上面的代码中的用户名、密码、IMAP 主机和端口都是从应用程序的配置文件中读取的。在使用此代码时,请确保将这些值替换为您自己的值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值