当前位置: 首页 > news >正文

高端网站建设,恩愉科技新余市网站建设

高端网站建设,恩愉科技,新余市网站建设,阿里云服务器安装网站,海口高端品牌网站建设一、概述 1.1 简述 JavaMail API 顾名思义#xff0c;提供给开发者处理电子邮件相关的编程接口#xff0c;它是Sun发布的用来处理email的API#xff0c;其提供独立于平台且与协议无关的框架来构建邮件和消息传递应用。JavaMail API 提供了一组抽象类#xff0c;用于定义组… 一、概述 1.1 简述 JavaMail API 顾名思义提供给开发者处理电子邮件相关的编程接口它是Sun发布的用来处理email的API其提供独立于平台且与协议无关的框架来构建邮件和消息传递应用。JavaMail API 提供了一组抽象类用于定义组成邮件系统的对象它是一个可选包(标准扩展)用于阅读撰写和发送电子信息。 1.2 邮件协议 JavaMail 提供了用于构造消息系统接口的元素包括系统组件和接口。虽然本规范没有定义任何特定的实现但 JavaMail 确实包含了几个实现 RFC822 和 MIME Internet 消息传递标准的类这些类是作为 JavaMail 类包的一部分提供的。在收发邮件的过程中需要遵守相关的协议JavaMail并不是绝对支持每一个协议其中主要有 协议说明SMTP单间邮件传输协议用于发送电子邮件的传输协议POP3用于接受电子邮件的标准协议IMAP互联网消息协议是POP3的替代协议 1.2.1 什么是SMTP SMTP 全称为Simple Mail Transfer Protocol即简单邮件传输协议它是一组用于从源地址到目的地址传输邮件的规范通过它来控制邮件的中转方式。SMTP 认证要求必须提供账号和密码才能登陆服务器其设计目的在于避免用户受到垃圾邮件的侵扰。   针对不同的的邮件协议JavaMail规定了服务提供者必须支持一系列属性下表是针对SMTP协议的一些常见属性。 名称类型描述mail.smtp.userStringSMTP默认的登录用户名mail.smtp.hostStringSMTP服务器地址如smtp.sina.com.cnmail.smtp.portintSMTP服务器端口号默认为25mail.smtp.fromString默认的邮件发送源地址mail.smtp.authbooleanSMTP服务器是否需要用户认证默认为falsemail.smtp.connectiontimeoutint套接字连接超时值以毫秒为单位.默认为无限超时mail.smtp.timeoutint套接字I/O超时值毫秒默认为无限超时mail.smtp.ssl.enableboolean如果设置为true则默认情况下使用SSL连接并使用SSL端口。对于smtp协议默认为false;对于smtps协议默认为true. 1.2.2 什么是IMAP IMAP全称为 Internet Message Access Protocol即互联网邮件访问协议IMAP允许从邮件服务器上获取邮件的信息、下载邮件等。IMAP 与 POP 类似都是一种邮件获取协议。针对不同的的邮件协议JavaMail规定了服务提供者必须支持一系列属性下表是针对IMAP协议的一些常见属性。 名称类型说明mail.imap.userStringIMAP的默认用户名mail.imap.hostString要连接的IMAP服务器mail.imap.portint要连接的IMAP服务器端口默认为143mail.imap.connectiontimeoutint套接字连接超时值以毫秒为单位.默认为无限超时mail.imap.timeoutint套接字I/O超时值毫秒默认为无限超时mail.imap.statuscachetimeoutint缓存的超时值(以毫秒为单位)默认值为1000(1秒)零禁用缓存mail.imap.appendbuffersizeint要缓冲的邮件的最大大小附加到IMAP文件夹时的内存mail.imap.connectionpoolsizeint最大可用数量连接池中的连接默认值为1mail.imap.connectionpooltimeoutint连接池连接的超时值(以毫秒为单位)默认值为45000(45秒).mail.imap.ssl.enableboolean如果设置如果为true则默认使用SSL连接并使用SSL端口。imap协议默认为falseimaps协议默认为true. 1.2.3 什么是POP3 POP3 全称为 Post Office Protocol 3即邮局协议POP3 支持客户端远程管理服务器端的邮件。POP3 常用于 离线 邮件处理即允许客户端下载服务器邮件然后服务器上的邮件将会被删除。目前很多 POP3 的邮件服务器只提供下载邮件功能服务器本身并不删除邮件这种属于改进版的 POP3 协议。   IMAP 和 POP3 协议两者最大的区别在于IMAP 允许双向通信即在客户端的操作会反馈到服务器上例如在客户端收取邮件、标记已读等操作服务器会跟着同步这些操作。而对于 POP 协议虽然也允许客户端下载服务器邮件但是在客户端的操作并不会同步到服务器上面的例如在客户端收取或标记已读邮件服务器不会同步这些操作。   针对不同的的邮件协议JavaMail规定了服务提供者必须支持一系列属性下表是针对POP3协议的一些常见属性。 名称类型说明mail.pop3.userStringPOP3的默认用户名mail.pop3.hostString要连接的POP3服务器mail.pop3.portint要连接的POP3服务器端口默认为110mail.pop3.connectiontimeoutint套接字连接超时值以毫秒为单位默认为无限超时mail.pop3.timeoutint套接字I/O超时值毫秒默认为无限超时mail.pop3.ssl.enableboolean如果设置为true则默认情况下使用SSL连接并使用SSL端口。pop3协议默认为falsepop3s协议默认为true 1.3 API 环境设置 开发人员使用 JavaMail 编写邮件程序时不再需要考虑底层的通讯细节如Socket而是关注在逻辑层面。JavaMail可以发送各种复杂MIME格式的邮件内容注意JavaMail仅支持JDK4及以上版本。虽然JavaMail是JDK的API但它并没有直接加入JDK中所以我们需要另外添加依赖。 使用javax.mail的坐标依赖包 !-- JavaMail基本包 -- dependencygroupIdjavax.mail/groupIdartifactIdmail/artifactIdversion1.4.7/version /dependency !-- 邮件发送的扩展包 -- dependencygroupIdjavax.activation/groupIdartifactIdactivation/artifactIdversion1.1.1/version /dependency使用com.sun.mail的坐标依赖包 !-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -- !-- 使用Sun提供的Email工具包 -- dependencygroupIdcom.sun.mail/groupIdartifactIdjavax.mail/artifactIdversionx.y.z/version /dependency使用Jakarta Mail发送邮件 dependencygroupIdcom.sun.mail/groupIdartifactIdjakarta.mail/artifactIdversionx.y.z/version /dependency个人推荐使用 javax.JavaMail 方式。 二、JavaMail 的关键对象 JavaMail 对收发邮件进行了高级的抽象形成了一些关键的的接口和类它们构成了程序的基础JavaMail API 包含一些用于发送、读取和删除电子邮件的接口和类。虽然 JavaMail API 中有许多软件包但它们将涵盖 JavaMail API 中经常使用的两个主要软件包javax.mail 和 javax.mail.internet 软件包这些包包含所有JavaMail核心类它们是 Class说明javax.mail.SessionAPI的关键类多线程对象表示连接工厂javax.mail.Message为电子邮件建模的抽象类子类提供实际的实现javax.mail.Address抽象类用于对消息中的地址进行建模子类提供特定的实现javax.mail.Authenticator用于保护邮件服务器上邮件资源的抽象类javax.mail.Transport抽象类它模拟用于发送电子邮件的邮件传输机制javax.mail.Store为消息存储建模的抽象类及其访问协议用于存储和检索消息javax.mail.Folder表示邮件消息文件夹的抽象类它可以包含子文件夹 2.1 Properties 由于 JavaMail 需要和邮件服务器进行通信这就要求程序提供许多诸如服务器地址、端口、用户名、密码等信息JavaMail通过Properties对象封装这些属性西信息。如下面的代码封装了两个属性信息 Properties properties new Properties(); props.put(mail.smtp.host, smtp.sina.com); props.put(mail.smtp.auth, true);针对不同的的邮件协议JavaMail规定了服务提供者必须支持一系列属性。 2.1 Session 类 javax.mail.Session 类定义了一个基本邮件会话(session)的主要类用于定义整个应用程序所需的环境信息以及客户端与邮件服务器建立网络连接的会话信息。它不创建子类但所有其它类都是经由这个 session 才得以生效。Session 对象用 Java.util.Properties 对象接收各种配置属性信息例如邮件服务器的主机名、端口号、采用的邮件发送和接收协议等根据这些信息构建用于邮件收发的 Transport 和 Store 对象以及为客户端创建 Message 对象时提供信息支持。   Session通过JavaMail配置文件以及程序中设置的Properties对象构建一个邮件处理环境后续的处理将在Session基础上进行。Session拥有多个静态工厂方法用于创建Session实例如下所示 /*** 当JVM中已经存在默认的Session实例中直接返回这个实例否则创建一个新的Session实例并将其作为JVM中默认Session实例*/ public static Session getDefaultInstance(Properties props)/*** 返回JVM中默认的Session实例如果第一次创建Session未指定Authenticator入参后续调用可以使用该访问获取Session*/ public static Session getDefaultInstance(Properties props,Authenticator authenticator)/*** 根据相关属性创建一个新的Session实例未使用安全认证信息*/ public static Session getInstance(Properties props)/*** 创建一个新的Session实例它不会在JVM中被作为默认实例共享*/ public static Session getInstance(Properties props,Authenticator authenticator)Session 是 JavaMail 提供者配置文件以及设置属性信息的“容器”Session 本身不会和邮件服务器进行任何的通信。所以在一般情况下我们仅需要通过getDefaultInstance() 获取一个共享的 Session 实例就可以了下面的代码创建了一个Session实例 Properties props System.getProperties(); props.setProperty(mail.transport.protocol, smtp); …… Session session Session.getDefaultInstance(props);2.2 Message 类 javax.mail.Message 类是创建和解析邮件的核心API一旦获得Session对象就可以继续创建要发送的消息这由 Message 类来完成。这是一个抽象类通常使用它的子类 javax.mail.internet.MimeMessage 类。客户端程序发送邮件时首先使用创建邮件的 JavaMail API 创建出封装了邮件数据的 Message 对象然后把这个对象传递给邮件发送API——Transport 类进行发送。客户端程序接收邮件时邮件接收API把接收到的邮件数据封装在Message 类的实例中客户端程序在使用邮件解析API从这个对象中解析收到的邮件数据。   为了建立一个MimeMessage对象我们必须将Session对象作为MimeMessage构造方法的参数传入 // 通过session对象来创建一个MimeMessage对象 MimeMessage messagenew MimeMessage(session);message 对象一旦创建就需要填充一些信息。Meesage类实现了 javax.mail.Part 接口而MimeMessage类实现了 javax.mail.internet.MimePart 接口如下表所示 方法描述void setFrom(Address address)用于设置发送者的邮件地址void addRecipient(Message.RecipientType type,String address)设置邮件的收件人、抄送人、密送人通过type区分void addRecipients(Message.RecipientType type,Address[] addresses)设置邮件的多个收件人、抄送人、密送人通过type区分void setSubject(String subject)设置邮件标题void setText(String textmessage)如果邮件内容是纯文本可以使用此接口设置文本内容。void setContent(Object obj,String type)设置邮件内容通过 type 指定类型。 纯文本“text/plain”html格式text/html;charsetUTF-8 2.3 Address 类 一旦创建了Session和Message并将内容填入消息后需要通过 Address 来设置信件的地址信息。由于 Address 是个抽象类因此大多数是使用它的实现类 javax.mial.internet.InternetAddress。 // 若地址只包含电子邮件地址直接通过一个邮箱地址来创建 Address address new InternetAddress(dllwhcrawlersina.com);// 也可以通过邮箱地址和邮寄人姓名来创建 Address address new InternetAddress(dllwhcrawlersina.com, dllwhcrawler);一旦创建了 address将它们与消息连接的方法有两种。如果要识别发件人您可以用 setFrom() 方法。 message.setFrom(address);// 需要消息显示多个 from 地址可以使用 addFrom() 方法 Address[] address; message.addFrom(address);为了设置收信人我们使用addRecipient()方法增加收件人此方法需要使用 Message.RecipientType 的常量来区分收信人的类型 message.addRecipient(type, address)下面是Message.RecipientType的三个常量: public static class RecipientType implements Serializable {/*** 收信人*/public static final RecipientType TO new RecipientType(To);/*** 抄送*/public static final RecipientType CC new RecipientType(Cc);/*** 私密抄送*/public static final RecipientType BCC new RecipientType(Bcc); }2.4 Authenticator 类 JavaMail API 利用 Authenticator 通过用户名和密码访问受保护的资源。对于JavaMail API 来说这些资源就是邮件服务器。Authenticator 位于 javax.mail 包中代表一个知道如何获得网络连接认证的对象是个抽象类通过创建它的子类 PasswordAuthentication从 getPasswordAuthentication() 方法中返回 PasswordAuthentication 实例。创建完成后必需向 session 注册 Authenticator。 Properties props new Properties(); Authenticator auth new Authenticator() {Overridepublic PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(发件人邮箱名, SDFA授权码);} }; Session session Session.getDefaultInstance(props, auth);2.5 Transport 类 javax.mail.Transport 是 发送邮件的核心API 类它的实例对象代表实现了某个邮件发送协议的邮件发送对象通常使用SMTP协议来发送消息。客户端程序创建好 Message 对象后只需要使用邮件发送API 得到 Transport 对象然后把 Message 对象传递给 Transport 对象并调用它的发送方法就可以把邮件发送给指定的 SMTP 服务器。 Transport.send(message);指定stmp协议和transport类型后Session就会使用com.sun.mail.smtp.SMTPTransport实现类创建一个Transport实例Transport 将根据 Session 中Properties 属性设置情况进行工作属性包括 属性名说明mail.transport.protocol默认的邮件传输协议例如smtpmail.host默认的邮件服务地址例如smtp.sina.commail.user默认的登陆用户名例如dllwhcrawlersina.commail.port默认的邮件服务端口发送消息的另一种方法是通过从会话的协议得到一个特定的实例传递下去的用户名和密码空白如果不必要的发送消息并关闭连接。 // 当Session实例设置了mail.transport.protocol属性时通过 getTransport() 获取对应的Transport实例 // 如果Session没有设置mail.transport.protocol属性可以通过该方法返回指定类型的Transport Transport transport session.getTransport(smtp); // smtp验证就是用来发邮件的邮箱用户名密码若在之前的properties中指定默认值这里可以不用再次设置 transport.connect(host, username, password); // 发送邮件 transport.sendMessage(message, message.getAllRecipients()); transport.close();这种方法在发送多条消息时最好因为它能保持邮件服务器在消息间的活动状态基本 send() 机制为每个方法的调用设置与服务器独立的连接。 注意要观察传到邮件服务器上的邮件命令请用 session.setDebug(true) 设置调试标志。 2.6 Store 类 javax.mail.Store 是 接收邮件的核心 API 类它的实例对象代表实现了某个邮件接收协议的邮件接收对象用来存储和查询消息。客户端程序接收邮件时只需要使用邮件接收 API 得到 Store 对象然后调用 Store 对象的接收方法就可以从指定的 POP3 服务器获得邮件数据并把这些邮件数据封装到表示邮件的 Message 对象中。 // 获得实现了数据访问协议的Store对象 Store store session.getStore(pop3); // connect方法进行身份验证 store.connect(host, username, password);指定pop3协议和store类型时则会使用 com.sun.mail.pop3.POP3Store 实例类创建一个 Store 实例Store 将根据 Session 中 Properties 属性设置情况进行工作属性包括 属性名说明mail.store.protocol默认的存储邮件协议例如pop3mail.host默认的邮件服务地址例如imap.sina.commail.user默认的登陆用户名例如dllwhcrawlersina.commail.port默认的邮件服务端口 2.7 Folder 类 javax.mail.Folder 是个抽象类代表邮件消息的一个文件夹其子类实现了特定的Folders文件夹可以包含子文件夹以及消息从而提供了一种分层结构。其实例 public abstract class Folder implements AutoCloseable由于 Folder 类唯一的构造函数是受保护的但Session、Store都有一个类似的getFolder()方法获取Folder对象 public abstract Folder getFolder(String name) throws MessagingException;三、JavaMail API 基本操作 3.1 准备工作 创建一个邮件服务器的基本信息类BaseMailConfig如下 import lombok.*;Data AllArgsConstructor RequiredArgsConstructor public class BaseMailConfig {/*** 服务器是否要验证用户的身份信息*/private boolean validate false;/*** 是否开启Session的debug模式开启后可以查看到程序发送Email的运行状态*/private boolean debugMode false;/*** 发送邮件的服务器的IP或主机地址*/private String mailServerHost;/*** 发送邮件的服务器的端口*/private int mailServerPort 25;/*** 邮件发送服务器的用户名(指的是邮箱地址)*/private String mailServerUser;/*** 邮件发送服务器的密码或者授权码*/private String mailServerPassword;/*** 发件人昵称*/private String nickName;/*** 邮件发送的协议*/private String transportType smtp;/*** 邮件存储的协议*/private String storeType pop3; }3.2 发送邮件 现在我们对 JavaMail API 及其核心类有一个清晰的概念现在让我们写这将发送简单的电子邮件邮件带有附件、电子邮件、HTML内容和内嵌图像的邮件一个简单的程序。发送电子邮件消息这一过程包括获取一个会话创建并填充一则消息然后发送。得到 Session 时经由设置传递的 Properties 对象中的 mail.smtp.host 属性可以指定 SMTP 服务器如下图所示 发送邮件首先需要有一个邮箱账号和密码以新浪邮箱为例邮箱账号必须要开启 SMTP 服务在浏览器网页登录邮箱后一般在邮箱的“设置”选项中可以开启并记下邮箱的 SMTP 服务器地址如下所示其他邮箱大同小异: 邮件发送涉及多端本地代码端、邮件发送服务器端、邮件接收服务器端把邮件提交到邮件发送服务器发送的服务器可以拒绝服务比如认为发送的内容是垃圾广告或者你频繁请求发送有时邮件就算发送成功了对方也有可能接收不到成功发送到对方的邮件接收服务器后对方的服务器可以根据内容拒绝收邮件比如认为内容是广告诈骗等信息或者发送过于频繁对方的服务器可能直接把你的邮件扔垃圾箱或者直接忽略。 3.2.1 发送简单邮件 即纯文本邮件没有除文字以外的其他所有文件。 import org.apache.commons.lang3.*; import javax.activation.*; import javax.mail.*; import javax.mail.internet.*; import java.io.*; import java.util.*;public class SendEmailHelper {private final static String CHARSET UTF-8;/*** 根据参数配置创建用于连接邮件服务器的参数配置发送邮件时才需要用到*/private static Properties getProperties(MailSenderInfo mailSenderInfo) {Properties properties new Properties();// 默认的邮件传输协议properties.setProperty(mail.transport.protocol, mailSenderInfo.getTransportType());// 默认的存储邮件协议properties.setProperty(mail.store.protocol, mailSenderInfo.getStoreType());// 设置邮件服务器主机名properties.put(mail.host, mailSenderInfo.getMailServerHost());properties.put(mail.port, mailSenderInfo.getMailServerPort());properties.put(mail.user, mailSenderInfo.getMailServerUser());// 设置是否安全验证,默认为false,一般情况都设置为trueproperties.put(mail.smtp.auth, mailSenderInfo.isValidate());return properties;}/*** 获得会话 Session*/private static Session getSession(MailSenderInfo mailSenderInfo) {Properties properties getProperties(mailSenderInfo);// 基本邮件会话是Java Mail API的入口Session sendMailSession;Authenticator authenticator null;// 判断是否需要身份认证if (mailSenderInfo.isValidate()) {// 如果需要身份认证则创建一个密码验证器authenticator new Authenticator() {Overridepublic PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(mailSenderInfo.getMailServerUser(), mailSenderInfo.getMailServerPassword());}};}// 根据邮件会话属性和密码验证器构造一个发送邮件的sessionsendMailSession Session.getDefaultInstance(properties, authenticator);// 若是设置为debug模式可以查看详细的发送日志sendMailSession.setDebug(mailSenderInfo.isDebugMode());return sendMailSession;}/*** 使用 JavaMail 以文本格式发送邮件** param mailSenderInfo 待发送的邮件信息*/public static void sendTextEmail(MailSenderInfo mailSenderInfo) throws MessagingException, UnsupportedEncodingException {// 1. 根据邮件会话属性和密码验证器构造一个发送邮件的sessionSession session getSession(mailSenderInfo);// 2. 根据session创建一个邮件对象Message mailMessage new MimeMessage(session);// 3. From: 发件人。其中 InternetAddress 的三个参数分别为: 邮箱、显示的昵称(只用于显示, 没有特别的要求)、昵称mailMessage.setFrom(new InternetAddress(mailSenderInfo.getMailServerUser(), mailSenderInfo.getNickName(), CHARSET));// 4. To: 收件人mailMessage.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(mailSenderInfo.getReceiver()));// 5. To: 抄送收件人if (StringUtils.isNotBlank(mailSenderInfo.getCcReceiver())) {mailMessage.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress(mailSenderInfo.getCcReceiver()));}// 6. To: 密送收件人if (StringUtils.isNotBlank(mailSenderInfo.getBccReceiver())) {mailMessage.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress(mailSenderInfo.getBccReceiver()));}// 7. 设置邮件消息的主题mailMessage.setSubject(mailSenderInfo.getSubject());// 8. 设置邮件消息的主要内容mailMessage.setContent(mailSenderInfo.getContent(), text/html;charsetUTF-8);// 9. 设置邮件消息发送的时间mailMessage.setSentDate(new Date());// 10. 保存前面的设置mailMessage.saveChanges();// 11. 发送使用传输对象的消息Transport.send(mailMessage);}public static void main(String[] args) throws Exception {MailSenderInfo mailConfigInfo new MailSenderInfo();mailConfigInfo.setMailServerHost(smtp.sina.com);mailConfigInfo.setMailServerUser(dllwhcrawlersina.com);mailConfigInfo.setMailServerPassword(4f38d72caa78ffec);mailConfigInfo.setReceiver(duleilewuhensina.com);mailConfigInfo.setValidate(true);mailConfigInfo.setSubject(TEST邮件主题);mailConfigInfo.setContent(TEST这是邮件正文。。。);mailConfigInfo.setFilePath(/Users/dllwh/Desktop/redis.sh);mailConfigInfo.setImagePath(/Users/dllwh/Downloads/禅.jpeg);} }有时处于业务需要我们需要群发邮件示例代码如下 package org.dllwh.utils.application.email.test;import org.apache.commons.lang3.*; import org.dllwh.utils.application.email.model.MailSenderInfo;import javax.activation.*; import javax.mail.*; import javax.mail.internet.*; import java.io.*; import java.util.*;public class SendEmailHelper {private final static String CHARSET UTF-8;/*** 根据参数配置创建用于连接邮件服务器的参数配置发送邮件时才需要用到*/private static Properties getProperties(MailSenderInfo mailSenderInfo) {Properties properties new Properties();// 默认的邮件传输协议properties.setProperty(mail.transport.protocol, mailSenderInfo.getTransportType());// 默认的存储邮件协议properties.setProperty(mail.store.protocol, mailSenderInfo.getStoreType());// 设置邮件服务器主机名properties.put(mail.host, mailSenderInfo.getMailServerHost());properties.put(mail.port, mailSenderInfo.getMailServerPort());properties.put(mail.user, mailSenderInfo.getMailServerUser());// 设置是否安全验证,默认为false,一般情况都设置为trueproperties.put(mail.smtp.auth, mailSenderInfo.isValidate());return properties;}/*** 获得会话 Session*/private static Session getSession(MailSenderInfo mailSenderInfo) {Properties properties getProperties(mailSenderInfo);// 基本邮件会话是Java Mail API的入口Session sendMailSession;Authenticator authenticator null;// 判断是否需要身份认证if (mailSenderInfo.isValidate()) {// 如果需要身份认证则创建一个密码验证器authenticator new Authenticator() {Overridepublic PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(mailSenderInfo.getMailServerUser(), mailSenderInfo.getMailServerPassword());}};}// 根据邮件会话属性和密码验证器构造一个发送邮件的sessionsendMailSession Session.getDefaultInstance(properties, authenticator);// 若是设置为debug模式可以查看详细的发送日志sendMailSession.setDebug(mailSenderInfo.isDebugMode());return sendMailSession;}/*** 使用 JavaMail 群发邮件** param mailSenderInfo 待发送的邮件信息*/public void sendTextEmails(MailSenderInfo mailSenderInfo) throws MessagingException, UnsupportedEncodingException {// 1. 创建一封邮件获取一个SessionSession session getSession(mailSenderInfo);// 2. 创建邮件对象Message mailMessage new MimeMessage(session);// 3. From: 发件人。其中 InternetAddress 的三个参数分别为: 邮箱、显示的昵称(只用于显示, 没有特别的要求)、昵称的字符集编码mailMessage.setFrom(new InternetAddress(mailSenderInfo.getMailServerUser(), mailSenderInfo.getNickName(), CHARSET));// 4. To: 收件人String[] receivers mailSenderInfo.getReceivers();if (ArrayUtils.isNotEmpty(receivers)) {InternetAddress[] addresses new InternetAddress[receivers.length];for (int i 0; i receivers.length; i) {addresses[i] new InternetAddress(receivers[i]);}mailMessage.setRecipients(MimeMessage.RecipientType.TO, addresses);}// 5. To: 抄送收件人String[] ccReceivers mailSenderInfo.getCcReceivers();if (ArrayUtils.isNotEmpty(ccReceivers)) {InternetAddress[] addresses new InternetAddress[receivers.length];for (int i 0; i receivers.length; i) {addresses[i] new InternetAddress(receivers[i]);}mailMessage.setRecipients(MimeMessage.RecipientType.CC, addresses);}// 6. To: 密送收件人String[] bccReceivers mailSenderInfo.getBccReceivers();if (ArrayUtils.isNotEmpty(bccReceivers)) {InternetAddress[] addresses new InternetAddress[receivers.length];for (int i 0; i receivers.length; i) {addresses[i] new InternetAddress(receivers[i]);}mailMessage.setRecipients(MimeMessage.RecipientType.BCC, addresses);}// 7. 设置邮件的主题mailMessage.setSubject(mailSenderInfo.getSubject());// 8. 设置邮件的内容mailMessage.setContent(mailSenderInfo.getContent(), text/html;charsetUTF-8);// 9. 设置显示的发送时间mailMessage.setSentDate(new Date());// 10. 保存前面的设置mailMessage.saveChanges();// 11. 发送使用传输对象的消息Transport.send(mailMessage);}public static void main(String[] args) throws Exception {MailSenderInfo mailConfigInfo new MailSenderInfo();mailConfigInfo.setMailServerHost(smtp.sina.com);mailConfigInfo.setMailServerUser(dllwhcrawlersina.com);mailConfigInfo.setMailServerPassword(4f38d72caa78ffec);mailConfigInfo.setReceiver(duleilewuhensina.com);mailConfigInfo.setValidate(true);mailConfigInfo.setSubject(TEST邮件主题);mailConfigInfo.setContent(TEST这是邮件正文。。。);mailConfigInfo.setFilePath(/Users/dllwh/Desktop/redis.sh);mailConfigInfo.setImagePath(/Users/dllwh/Downloads/禅.jpeg);} }3.2.2 发送附件的邮件 一封复杂的邮件内容可以看做是由很多节点或者可以说是片段、部分、零件组成文本、图片、附件等都可以看成是邮件内容中的一个节点。这些节点之间又可以相互关联组合成一个节点最终组合成一个大节点就是邮件的正文内容。 import org.apache.commons.lang3.*; import javax.activation.*; import javax.mail.*; import javax.mail.internet.*; import java.io.*; import java.util.*;public class SendEmailHelper {private final static String CHARSET UTF-8;/*** 根据参数配置创建用于连接邮件服务器的参数配置发送邮件时才需要用到*/private static Properties getProperties(MailSenderInfo mailSenderInfo) {Properties properties new Properties();// 默认的邮件传输协议properties.setProperty(mail.transport.protocol, mailSenderInfo.getTransportType());// 默认的存储邮件协议properties.setProperty(mail.store.protocol, mailSenderInfo.getStoreType());// 设置邮件服务器主机名properties.put(mail.host, mailSenderInfo.getMailServerHost());properties.put(mail.port, mailSenderInfo.getMailServerPort());properties.put(mail.user, mailSenderInfo.getMailServerUser());// 设置是否安全验证,默认为false,一般情况都设置为trueproperties.put(mail.smtp.auth, mailSenderInfo.isValidate());return properties;}/*** 获得会话 Session*/private static Session getSession(MailSenderInfo mailSenderInfo) {Properties properties getProperties(mailSenderInfo);// 基本邮件会话是Java Mail API的入口Session sendMailSession;Authenticator authenticator null;// 判断是否需要身份认证if (mailSenderInfo.isValidate()) {// 如果需要身份认证则创建一个密码验证器authenticator new Authenticator() {Overridepublic PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(mailSenderInfo.getMailServerUser(), mailSenderInfo.getMailServerPassword());}};}// 根据邮件会话属性和密码验证器构造一个发送邮件的sessionsendMailSession Session.getDefaultInstance(properties, authenticator);// 若是设置为debug模式可以查看详细的发送日志sendMailSession.setDebug(mailSenderInfo.isDebugMode());return sendMailSession;}/*** 使用 JavaMail 发送带附件的邮件** param mailSenderInfo 待发送的邮件信息*/public static void sendAttachEmail(MailSenderInfo mailSenderInfo) throws MessagingException, UnsupportedEncodingException {// 1. 创建一封邮件获取一个SessionSession session getSession(mailSenderInfo);// 2. 创建邮件对象MimeMessage message new MimeMessage(session);// 3. From: 发件人。其中 InternetAddress 的三个参数分别为: 邮箱、显示的昵称(只用于显示, 没有特别的要求)、昵称的字符集编码message.setFrom(new InternetAddress(mailSenderInfo.getMailServerUser(), mailSenderInfo.getNickName(), CHARSET));// 4. To: 收件人String[] receivers mailSenderInfo.getReceivers();if (ArrayUtils.isNotEmpty(receivers)) {InternetAddress[] addresses new InternetAddress[receivers.length];for (int i 0; i receivers.length; i) {addresses[i] new InternetAddress(receivers[i]);}message.setRecipients(MimeMessage.RecipientType.TO, addresses);}// 5. To: 抄送收件人String[] ccReceivers mailSenderInfo.getCcReceivers();if (ArrayUtils.isNotEmpty(ccReceivers)) {InternetAddress[] addresses new InternetAddress[receivers.length];for (int i 0; i receivers.length; i) {addresses[i] new InternetAddress(receivers[i]);}message.setRecipients(MimeMessage.RecipientType.CC, addresses);}// 6. To: 密送收件人String[] bccReceivers mailSenderInfo.getBccReceivers();if (ArrayUtils.isNotEmpty(bccReceivers)) {InternetAddress[] addresses new InternetAddress[receivers.length];for (int i 0; i receivers.length; i) {addresses[i] new InternetAddress(receivers[i]);}message.setRecipients(MimeMessage.RecipientType.BCC, addresses);}// 7. 设置邮件的主题message.setSubject(mailSenderInfo.getSubject(), CHARSET);// 8. 创建一个MimeMultipart的对象BodyPart messageBodyPart new MimeBodyPart();messageBodyPart.setText(mailSenderInfo.getContent());messageBodyPart new MimeBodyPart();DataSource source new FileDataSource(mailSenderInfo.getFilePath());// 设置dhFile附件处理messageBodyPart.setDataHandler(new DataHandler(source));// 设置中文附件名称messageBodyPart.setFileName(mailSenderInfo.getFilePath());// 9. 设置邮件的内容Multipart multipart new MimeMultipart();// 把附件资源混合到 Multipart 多资源邮件模块里multipart.addBodyPart(messageBodyPart);message.setContent(multipart);// 10. 设置显示的发送时间message.setSentDate(new Date());// 11. 保存前面的设置message.saveChanges();// 12. 发送使用传输对象的消息Transport.send(message);}public static void main(String[] args) throws Exception {MailSenderInfo mailConfigInfo new MailSenderInfo();mailConfigInfo.setMailServerHost(smtp.sina.com);mailConfigInfo.setMailServerUser(dllwhcrawlersina.com);mailConfigInfo.setMailServerPassword(4f38d72caa78ffec);mailConfigInfo.setReceiver(duleilewuhensina.com);mailConfigInfo.setValidate(true);mailConfigInfo.setSubject(TEST邮件主题);mailConfigInfo.setContent(TEST这是邮件正文。。。);mailConfigInfo.setFilePath(/Users/dllwh/Desktop/redis.sh);mailConfigInfo.setImagePath(/Users/dllwh/Downloads/禅.jpeg);} }3.2.3 发送HTML的邮件 发送HTML格式电子邮件跟发送简单的电子邮件非常相似除非在使用setContent()方法来设置内容的第二个参数为“text/html指定的HTML内容。 package org.dllwh.utils.application.email.test;import org.apache.commons.lang3.*; import org.dllwh.utils.application.email.model.MailSenderInfo;import javax.activation.*; import javax.mail.*; import javax.mail.internet.*; import java.io.*; import java.util.*;public class SendEmailHelper {private final static String CHARSET UTF-8;/*** 根据参数配置创建用于连接邮件服务器的参数配置发送邮件时才需要用到*/private static Properties getProperties(MailSenderInfo mailSenderInfo) {Properties properties new Properties();// 默认的邮件传输协议properties.setProperty(mail.transport.protocol, mailSenderInfo.getTransportType());// 默认的存储邮件协议properties.setProperty(mail.store.protocol, mailSenderInfo.getStoreType());// 设置邮件服务器主机名properties.put(mail.host, mailSenderInfo.getMailServerHost());properties.put(mail.port, mailSenderInfo.getMailServerPort());properties.put(mail.user, mailSenderInfo.getMailServerUser());// 设置是否安全验证,默认为false,一般情况都设置为trueproperties.put(mail.smtp.auth, mailSenderInfo.isValidate());return properties;}/*** 获得会话 Session*/private static Session getSession(MailSenderInfo mailSenderInfo) {Properties properties getProperties(mailSenderInfo);// 基本邮件会话是Java Mail API的入口Session sendMailSession;Authenticator authenticator null;// 判断是否需要身份认证if (mailSenderInfo.isValidate()) {// 如果需要身份认证则创建一个密码验证器authenticator new Authenticator() {Overridepublic PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(mailSenderInfo.getMailServerUser(), mailSenderInfo.getMailServerPassword());}};}// 根据邮件会话属性和密码验证器构造一个发送邮件的sessionsendMailSession Session.getDefaultInstance(properties, authenticator);// 若是设置为debug模式可以查看详细的发送日志sendMailSession.setDebug(mailSenderInfo.isDebugMode());return sendMailSession;}/*** 使用 JavaMail 以HTML格式发送邮件** param mailSenderInfo 待发送的邮件信息*/public static void sendHtmlMail(MailSenderInfo mailSenderInfo) throws UnsupportedEncodingException, MessagingException {// 1. 根据邮件会话属性和密码验证器构造一个发送邮件的sessionSession session getSession(mailSenderInfo);// 2. 根据session创建一个邮件消息Message mailMessage new MimeMessage(session);// 3. From: 发件人。其中 InternetAddress 的三个参数分别为: 邮箱、显示的昵称(只用于显示, 没有特别的要求)、昵称的字符集编码mailMessage.setFrom(new InternetAddress(mailSenderInfo.getMailServerUser(), mailSenderInfo.getNickName(), CHARSET));// 4. To: 收件人mailMessage.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(mailSenderInfo.getReceiver()));// 5. To: 抄送收件人if (StringUtils.isNotBlank(mailSenderInfo.getCcReceiver())) {mailMessage.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress(mailSenderInfo.getCcReceiver()));}// 6. To: 密送收件人if (StringUtils.isNotBlank(mailSenderInfo.getBccReceiver())) {mailMessage.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress(mailSenderInfo.getBccReceiver()));}// 7. 设置邮件的主题mailMessage.setSubject(mailSenderInfo.getSubject());// 8. 设置邮件的内容mailMessage.setContent(mailSenderInfo.getContent(), text/html;charsetUTF-8);// 9. 设置显示的发送时间mailMessage.setSentDate(new Date());// 10. 保存前面的设置mailMessage.saveChanges();// 11. 发送使用传输对象的消息Transport.send(mailMessage);}public static void main(String[] args) throws Exception {MailSenderInfo mailConfigInfo new MailSenderInfo();mailConfigInfo.setMailServerHost(smtp.sina.com);mailConfigInfo.setMailServerUser(dllwhcrawlersina.com);mailConfigInfo.setMailServerPassword(4f38d72caa78ffec);mailConfigInfo.setReceiver(duleilewuhensina.com);mailConfigInfo.setValidate(true);mailConfigInfo.setSubject(TEST邮件主题);mailConfigInfo.setContent(TEST这是邮件正文。。。);mailConfigInfo.setFilePath(/Users/dllwh/Desktop/redis.sh);mailConfigInfo.setImagePath(/Users/dllwh/Downloads/禅.jpeg);} }3.2.4 发送内嵌图像中的邮件 要发送包含一个内嵌图像的电子邮件需要创建一个 DataHandler 类的来添加图像 messageBodyPart new MimeBodyPart(); DataSource fds new FileDataSource(图像位置或者访问地址); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader(Content-ID, image); multipart.addBodyPart(messageBodyPart); message.setContent(multipart);示例代码如下 package org.dllwh.utils.application.email.test;import org.apache.commons.lang3.*; import org.dllwh.utils.application.email.model.MailSenderInfo;import javax.activation.*; import javax.mail.*; import javax.mail.internet.*; import java.io.*; import java.util.*;public class SendEmailHelper {private final static String CHARSET UTF-8;/*** 根据参数配置创建用于连接邮件服务器的参数配置发送邮件时才需要用到*/private static Properties getProperties(MailSenderInfo mailSenderInfo) {Properties properties new Properties();// 默认的邮件传输协议properties.setProperty(mail.transport.protocol, mailSenderInfo.getTransportType());// 默认的存储邮件协议properties.setProperty(mail.store.protocol, mailSenderInfo.getStoreType());// 设置邮件服务器主机名properties.put(mail.host, mailSenderInfo.getMailServerHost());properties.put(mail.port, mailSenderInfo.getMailServerPort());properties.put(mail.user, mailSenderInfo.getMailServerUser());// 设置是否安全验证,默认为false,一般情况都设置为trueproperties.put(mail.smtp.auth, mailSenderInfo.isValidate());return properties;}/*** 获得会话 Session*/private static Session getSession(MailSenderInfo mailSenderInfo) {Properties properties getProperties(mailSenderInfo);// 基本邮件会话是Java Mail API的入口Session sendMailSession;Authenticator authenticator null;// 判断是否需要身份认证if (mailSenderInfo.isValidate()) {// 如果需要身份认证则创建一个密码验证器authenticator new Authenticator() {Overridepublic PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(mailSenderInfo.getMailServerUser(), mailSenderInfo.getMailServerPassword());}};}// 根据邮件会话属性和密码验证器构造一个发送邮件的sessionsendMailSession Session.getDefaultInstance(properties, authenticator);// 若是设置为debug模式可以查看详细的发送日志sendMailSession.setDebug(mailSenderInfo.isDebugMode());return sendMailSession;}/*** 使用 JavaMail 发送内嵌图像中的邮件** param mailSenderInfo 待发送的邮件信息*/public static void sendImageEmail(MailSenderInfo mailSenderInfo) throws UnsupportedEncodingException, MessagingException {// 1. 创建一封邮件获取一个SessionSession session getSession(mailSenderInfo);// 2. 创建邮件对象MimeMessage message new MimeMessage(session);// 3. From: 发件人。其中 InternetAddress 的三个参数分别为: 邮箱、显示的昵称(只用于显示, 没有特别的要求)、昵称的字符集编码message.setFrom(new InternetAddress(mailSenderInfo.getMailServerUser(), mailSenderInfo.getNickName(), CHARSET));// 4. To: 收件人message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(mailSenderInfo.getReceiver()));// 5. To: 抄送收件人if (StringUtils.isNotBlank(mailSenderInfo.getCcReceiver())) {message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress(mailSenderInfo.getCcReceiver()));}// 6. To: 密送收件人if (StringUtils.isNotBlank(mailSenderInfo.getBccReceiver())) {message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress(mailSenderInfo.getBccReceiver()));}// 7. 设置邮件的主题message.setSubject(mailSenderInfo.getSubject(), CHARSET);MimeMultipart multipart new MimeMultipart(related);// 8. 创建一个MimeMultipart的对象BodyPart messageBodyPart new MimeBodyPart();String htmlText H1Hello/H1img src\cid:image\;messageBodyPart.setContent(htmlText, text/html);multipart.addBodyPart(messageBodyPart);// 9. 设置邮件的内容messageBodyPart new MimeBodyPart();DataSource fds new FileDataSource(mailSenderInfo.getImagePath());// //设置dhImg图片处理messageBodyPart.setDataHandler(new DataHandler(fds));messageBodyPart.setHeader(Content-ID, image);multipart.addBodyPart(messageBodyPart);message.setContent(multipart);// 10. 设置显示的发送时间message.setSentDate(new Date());// 11. 保存前面的设置message.saveChanges();// 12. 发送使用传输对象的消息Transport.send(message);}public static void main(String[] args) throws Exception {MailSenderInfo mailConfigInfo new MailSenderInfo();mailConfigInfo.setMailServerHost(smtp.sina.com);mailConfigInfo.setMailServerUser(dllwhcrawlersina.com);mailConfigInfo.setMailServerPassword(4f38d72caa78ffec);mailConfigInfo.setReceiver(duleilewuhensina.com);mailConfigInfo.setValidate(true);mailConfigInfo.setSubject(TEST邮件主题);mailConfigInfo.setContent(TEST这是邮件正文。。。);mailConfigInfo.setFilePath(/Users/dllwh/Desktop/redis.sh);mailConfigInfo.setImagePath(/Users/dllwh/Downloads/禅.jpeg);} }3.3 收取邮件 为读邮件先要获取一个会话获取并连接一个用于邮箱的适宜的存储store打开适宜的文件夹然后获取相关的消息。同样切记完成后关闭连接。 package org.dllwh.utils.application.email.test;import org.apache.commons.lang3.*; import org.dllwh.utils.application.email.model.*;import javax.mail.*; import javax.mail.internet.*; import java.io.*; import java.text.SimpleDateFormat; import java.util.*;public class ReceiveEmailHelper {/*** 根据参数配置创建会话对象用于连接邮件服务器的参数配置发送邮件时才需要用到*/private static Properties getProperties(BaseMailConfig mailConfigInfo) {Properties properties new Properties();// 默认的邮件传输协议properties.setProperty(mail.transport.protocol, mailConfigInfo.getTransportType());// 默认的存储邮件协议properties.setProperty(mail.store.protocol, mailConfigInfo.getStoreType());// 设置邮件服务器主机名properties.put(mail.host, mailConfigInfo.getMailServerHost());properties.put(mail.port, mailConfigInfo.getMailServerPort());properties.put(mail.user, mailConfigInfo.getMailServerUser());// 设置是否安全验证,默认为false,一般情况都设置为trueproperties.put(mail.smtp.auth, mailConfigInfo.isValidate());return properties;}/*** 获得会话 Session*/private static Session getSession(BaseMailConfig mailConfigInfo) {Properties properties getProperties(mailConfigInfo);// 基本邮件会话是Java Mail API的入口Session sendMailSession;Authenticator authenticator null;// 判断是否需要身份认证if (mailConfigInfo.isValidate()) {// 如果需要身份认证则创建一个密码验证器authenticator new Authenticator() {Overridepublic PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(mailConfigInfo.getMailServerUser(), mailConfigInfo.getMailServerPassword());}};}// 根据邮件会话属性和密码验证器构造一个发送邮件的sessionsendMailSession Session.getDefaultInstance(properties, authenticator);// 若是设置为debug模式可以查看详细的发送日志sendMailSession.setDebug(mailConfigInfo.isDebugMode());return sendMailSession;}/*** 获取邮箱的基本邮件信息** param folder 收件箱对象* return 返回邮箱基本信息*/private static MapString, Integer emailInfo(Folder folder) throws MessagingException {MapString, Integer emailInfo new HashMap();// 未读邮件数。由于POP3协议无法获知邮件的状态,所以getUnreadMessageCount得到的是收件箱的邮件总数emailInfo.put(unreadMessageCount, folder.getUnreadMessageCount());// 删除邮件数。由于POP3协议无法获知邮件的状态,所以下面(删除、新邮件)得到的结果始终都是为0emailInfo.put(deletedMessageCount, folder.getDeletedMessageCount());// 新邮件emailInfo.put(newMessageCount, folder.getNewMessageCount());// 获得收件箱中的邮件总数emailInfo.put(messageCount, folder.getMessageCount());return emailInfo;}/**** 获得邮件主题*/private static String getSubject(MimeMessage msg) throws UnsupportedEncodingException, MessagingException {return decodeText(msg.getSubject());}/**** 获得邮件发件人*/private static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException {Address[] froms msg.getFrom();if (froms.length 1) {throw new MessagingException(没有发件人!);}InternetAddress address (InternetAddress) froms[0];String person address.getPersonal();person (person ! null) ? decodeText(person) : ;return person address.getAddress() ;}/**** 根据收件人类型获取邮件收件人、抄送和密送地址。如果收件人类型为空则获得所有的收件人* type可选值* pMessage.RecipientType.TO 收件人/p* pMessage.RecipientType.CC 抄送/p* pMessage.RecipientType.BCC 密送/p* param msg 邮件内容* param type 收件人类型* return 收件人1 邮件地址1, 收件人2 邮件地址2, ...*/private static String getReceiveAddress(Message msg, Message.RecipientType type) throws MessagingException {StringBuilder recipientAddress new StringBuilder();Address[] address;if (type null) {address msg.getAllRecipients();} else {address msg.getRecipients(type);}if (address null || address.length 1) {if (type null) {throw new MessagingException(没有收件人!);} else if (cc.equalsIgnoreCase(type.toString())) {throw new MessagingException(没有抄送人!);} else if (bcc.equalsIgnoreCase(type.toString())) {throw new MessagingException(没有密送人!);}}for (Address add : Objects.requireNonNull(address)) {InternetAddress internetAddress (InternetAddress) add;recipientAddress.append(internetAddress.toUnicodeString()).append(,);}//删除最后一个逗号recipientAddress.deleteCharAt(recipientAddress.length() - 1);return recipientAddress.toString();}/**** 获得邮件发送时间* param msg 邮件内容* return 默认返回yyyy年mm月dd日 星期X HH:mm*/private static String getSentDate(Message msg, String pattern) throws MessagingException {Date receivedDate msg.getSentDate();if (receivedDate null) {return ;}pattern StringUtils.isNotBlank(pattern) ? yyyy年MM月dd日 E HH:mm : pattern;return new SimpleDateFormat(pattern).format(receivedDate);}/**** 获得邮件接收时间* param msg 邮件内容* return 默认返回yyyy年mm月dd日 星期X HH:mm*/private static String getReceivedDate(Message msg, String pattern) throws MessagingException {Date receivedDate msg.getReceivedDate();if (receivedDate null) {return ;}pattern StringUtils.isNotBlank(pattern) ? yyyy年MM月dd日 E HH:mm : pattern;return new SimpleDateFormat(pattern).format(receivedDate);}/**** 判断邮件是否已读 www.2cto.com* param msg 邮件内容* return 如果邮件已读返回true, 否则返回false*/private static boolean isSeen(Message msg) throws MessagingException {return msg.getFlags().contains(Flags.Flag.SEEN);}/**** 判断邮件是否需要阅读回执* param msg 邮件内容* return 需要回执返回true, 否则返回false*/private static boolean isReplySign(Message msg) throws MessagingException {return ArrayUtils.isNotEmpty(msg.getHeader(Disposition-Notification-To));}/**** 获得邮件的优先级* param msg 邮件内容* return 1(High):紧急 3:普通(Normal) 5:低(Low)*/private static String getPriority(Message msg) throws MessagingException {String priority 普通;String[] headers msg.getHeader(X-Priority);if (headers ! null) {String headerPriority headers[0];if (headerPriority.contains(1) || headerPriority.contains(High)) {priority 紧急;} else if (headerPriority.contains(5) || headerPriority.contains(Low)) {priority 低;} else {priority 普通;}}return priority;}/**** 获得邮件文本内容* param part 邮件体* param content 存储邮件文本内容的字符串*/private static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {//如果是文本类型的附件通过getContent方法可以取到文本内容但这不是我们需要的结果所以在这里要做判断boolean isContainTextAttach part.getContentType().indexOf(name) 0;if (part.isMimeType(text/*) !isContainTextAttach) {content.append(part.getContent().toString());} else if (part.isMimeType(message/rfc822)) {getMailTextContent((Part) part.getContent(), content);} else if (part.isMimeType(multipart/*)) {Multipart multipart (Multipart) part.getContent();int partCount multipart.getCount();for (int i 0; i partCount; i) {BodyPart bodyPart multipart.getBodyPart(i);getMailTextContent(bodyPart, content);}}}/**** 文本解码* param encodeText 解码MimeUtility.encodeText(String text)方法编码后的文本* return 解码后的文本*/private static String decodeText(String encodeText) throws UnsupportedEncodingException {if (encodeText null || .equals(encodeText)) {return ;} else {return MimeUtility.decodeText(encodeText);}}/**** 判断邮件中是否包含附件 Part为Message接口,邮件中存在附件返回true不存在返回false*/private static boolean isContainAttachment(Part part) throws MessagingException, IOException {boolean flag false;if (part.isMimeType(multipart/*)) {MimeMultipart multipart (MimeMultipart) part.getContent();int partCount multipart.getCount();for (int i 0; i partCount; i) {BodyPart bodyPart multipart.getBodyPart(i);String disposition bodyPart.getDisposition();if (disposition ! null (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE))) {flag true;} else if (bodyPart.isMimeType(multipart/*)) {flag isContainAttachment(bodyPart);} else {String contentType bodyPart.getContentType();if (contentType.contains(application)) {flag true;}if (contentType.contains(name)) {flag true;}}if (flag) {break;}}} else if (part.isMimeType(message/rfc822)) {flag isContainAttachment((Part) part.getContent());}return flag;}/*** 使用 JavaMail 接收邮件*/public static void recipientMail(MailReceiveInfo mailReceiveInfo) throws MessagingException, IOException {// 1. 创建一封邮件获取一个SessionSession session getSession(mailReceiveInfo);// 2. 获取Store对象Store emailStore session.getStore(mailReceiveInfo.getStoreType());// POP3服务器登录认证user我们在properties中已经指定默认emailStore.connect(mailReceiveInfo.getMailServerUser(), mailReceiveInfo.getMailServerPassword());// 3. 获取收件箱内容电子邮件收件箱 folder邮件夹Folder emailFolder emailStore.getFolder(INBOX);// 4. 设置对邮件帐户的访问权限。 Folder.READ_ONLY (只读或者1)、Folder.READ_WRITE(只写或者2)emailFolder.open(Folder.READ_ONLY);// 获取邮箱基本信息System.out.println(emailInfo(emailFolder));// 5. 获取收件箱中的所有邮件Message[] messages emailFolder.getMessages();// 解析所有邮件for (Message message : messages) {System.out.println(------------------解析第 message.getMessageNumber() 封邮件-------------------- );System.out.println(主题: MimeUtility.decodeText(message.getSubject()));System.out.println(发件人: InternetAddress.toString(message.getFrom()));System.out.println(收件人 getReceiveAddress(message, Message.RecipientType.TO));System.out.println(邮件正文: message.getContent().toString());System.out.println(接收时间 getReceivedDate(message, yyyy-MM-dd HH:mm:ss));System.out.println(发送时间 getSentDate(message, yyyy-MM-dd HH:mm:ss));System.out.println(是否已读 isSeen(message));System.out.println(是否需要回执 isReplySign(message));System.out.println(邮件大小 message.getSize() * 1024 kb);System.out.println(邮件优先级 getPriority(message));System.out.println(是否包含附件 isContainAttachment(message));//用来存储正文的对象StringBuffer content new StringBuffer();getMailTextContent(message, content);System.out.println(邮件正文 content);System.out.println(-----------第 message.getMessageNumber() 封邮件解析结束------------);System.out.println();}// 6. 关闭邮件夹对象emailFolder.close(false);// 7. 关闭连接对象emailStore.close();}public static void main(String[] args) throws MessagingException, IOException {MailReceiveInfo mailConfigInfo new MailReceiveInfo();mailConfigInfo.setMailServerHost(imap.sina.com);mailConfigInfo.setMailServerUser(dllwhcrawlersina.com);mailConfigInfo.setMailServerPassword(4f38d72caa78ffec);mailConfigInfo.setValidate(true);ReceiveEmailHelper.recipientMail(mailConfigInfo);} }3.4 删除邮件 我们将使用JavaMail API来删除电子邮件。删除信息涉及与该消息相关联的标志工作。有不同的标志为不同的状态一些系统定义和一些用户定义的。预定义的标志在内部类中定义的标志。标志如下所列 标志说明Flags.Flag.ANSWERED邮件回复标记标识邮件是否已回复Flags.Flag.DELETED邮件删除标记标识邮件是否需要删除Flags.Flag.DRAFT草稿邮件标记标识邮件是否为草稿Flags.Flag.FLAGGED表示邮件是否为回收站中的邮件Flags.Flag.RECENT新邮件标记表示邮件是否为新邮件Flags.Flag.SEEN邮件阅读标记标识邮件是否已被阅读Flags.Flag.USER底层系统是否支持用户自定义标记应用程序只能检索这个属性而不能设置。 3.5 邮件文件夹管理 到目前为止我们在上面章节中主要使用了 INBOX 文件夹这是大多数邮件所在的默认文件夹。一些系统可能将其称为 INBOX而另一些系统可能会用其他名称来称呼它。但是我们始终可以使用名称 INBOX 从 JavaMail API 访问它。JavaMail API 将文件夹表示为抽象 Folder 类的实例 public abstract class Folder extends Object此类声明用于从服务器请求命名文件夹、从文件夹中删除邮件、在文件夹中搜索特定邮件、列出文件夹中的邮件等的方法。 3.5.1 打开文件夹 我们不能直接创建文件夹因为 Folder 类中唯一的构造函数是 protected。我们可以通过Session、Store、Folder类获取文件夹都有一个类似的 getFolder() 方法具有类似的签名 public abstract Folder getFolder(String name) throws MessagingException;以下是有助于获取 Folder 对象的以下方法 方法描述boolean exists()检查文件夹是否真的存在在获取 Folder 对象之前使用void open(int mode)以Folder.READ_ONLY或Folder.READ_WRITE模式打开文件夹boolean isOpen()如果文件夹打开返回 true否则返回 falsevoid close(boolean expunge)关闭文件夹。如果 expunge 为 true 则会从服务器上的实际文件中删除该文件夹中的所有已删除邮件。否则它们只是标记为 已删除但邮件仍然可以取消删除. 3.5.2 基本文件夹信息 以下是 Folder 类中的一些方法它们返回有关文件夹的基本信息 方法描述String getName()返回文件夹的名称String getFullName()从根目录返回完整的层次结构名称URLName getURLName()返回表示此文件夹的URLNameFolder getParent()返回包含此文件夹的文件夹的名称即父文件夹int getType()返回一个int指示文件夹是否可以包含消息和/或其他文件夹int getMode()返回Folder.READ_ONLY、Folder.READ_WRITE、-1Store getStore()返回从中检索此文件夹的 Store 对象char getSeparator()返回分隔此文件夹的路径名与直接子文件夹的名称的分隔符 3.5.3 管理文件夹 以下是一些有助于管理文件夹以及文件夹中的消息的方法 方法描述create(int type)在此文件夹的Store中创建一个新文件夹成功返回 true否则返回 falsedelete(boolean recurse)仅当文件夹关闭时才会删除。如果recurse是true则删除子文件夹renameTo(Folder f)更改文件夹的名称必须关闭文件夹才能重命名否则抛出异常appendMessages(Message[] messages)数组中的消息放置在此文件夹的末尾copyMessages(Message[] msgs,Folder folder)将此文件夹中的消息复制到作为参数给出的指定文件夹中Message[] expunge()从文件夹中物理删除已删除的邮件 3.5.4 列出文件夹的内容 以下几种方法可以列出文件夹包含的文件夹 方法描述Folder[] list()返回一个数组列出该文件夹包含的文件夹Folder[] listSubscribed()返回一个数组列出该文件夹包含的所有订阅文件夹.Folder[] list(String pattern)Folder[] listSubscribed(String pattern) 3.5.5 检查邮件 方法描述int getMessageCount()获取邮件总数boolean hasNewMessages()int getNewMessageCount()int getUnreadMessageCount()未读邮件数int getDeletedMessageCount()删除邮件数 3.5.6 从文件夹获取消息 Folder 类提供了以下几种从打开的文件夹中检索消息的方法 方法描述Messageget Message(int msgnum)这将返回文件夹中的第n条消息。文件夹中的第一条消息是数字 1Message[] getMessages()返回一组Message对象表示此文件夹中的所有消息Message[] getMessages(int startint end)返回文件夹中的Message对象数组从 start 开始以 end 结束Message[] getMessages(int[] msgnums) 3.5.7 修改文件夹标记 当需要更改文件夹中整个邮件集的标记时标志修改非常有用。以下是 Folder 类中提供的方法 方法描述void setFlags(Message[] msgsFlags flagboolean value)在数组中指定的消息上设置指定的标志void setFlags(intstartintendFlags flagboolean value)设置从开始到结束编号的消息上的指定标志包括起点和终点void setFlags(int[] msgnumsFlags flagboolean value)设置消息号在数组中的消息的指定标志Flags getPermanentFlags()返回此文件夹支持所有邮件的标志 四、附录 4.1 邮箱配置 针对不同的邮箱有不同的配置所以我们介绍几种我们常用的邮箱配置可以直接拿来配置。 邮箱类型POP3服务器SMTP服务器IMAP服务器端口新浪pop.sina.comsmtp.sina.comimap.sina.com25QQpop.qq.comsmtp.qq.comimap.qq.com465网易163pop.163.comsmtp.163.comimap.163.com465谷歌邮箱smtp.gmail.com587outlooksmtp-mail.outlook.com587 4.2 SMTP 服务器 SMTP 协议提供程序支持以下属性这些属性可以在 JavaMail Session 对象中设置属性 属性类说明mail.smtp.userStringSMTP 的默认用户名mail.smtp.hostString要连接的 SMTP 服务器mail.smtp.portint要连接的 SMTP 服务器端口默认为 25mail.smtp.connectiontimeoutint以毫秒为单位的套接字连接超时值默认为无限超时mail.smtp.timeoutint以毫秒为单位的套接字 I/O 超时值默认为无限超时mail.smtp.authboolean如果为 true则尝试使用 AUTH 命令对用户进行身份验证默认为假mail.smtp.auth.login.disableboolean如果为 true则阻止使用 AUTH LOGIN 命令默认为假mail.smtp.auth.plain.disableboolean如果为 true则阻止使用 AUTH PLAIN 命令默认为假mail.smtp.auth.digest-md5.disableboolean如果为 true则阻止使用 AUTH DIGEST-MD5 命令默认为假mail.smtp.auth.ntlm.disableboolean如果为 true则阻止使用 AUTH NTLM 命令默认为假mail.smtp.auth.ntlm.domainStringNTLM 身份验证域mail.smtp.auth.ntlm.flagsintNTLM 协议特定标志mail.smtp.dsn.retStringMAIL 命令的 RET 选项FULL 或 HDRSmail.smtp.sasl.authorizationidString在 SASL 身份验证中使用的授权 ID如果未设置则使用身份验证 IDmail.smtp.sasl.realmString用于 DIGEST-MD5 身份验证的领域mail.smtp.quitwaitboolean如果设置为 false则发送 QUIT 命令并立即关闭连接如果设置为 true默认值则导致传输等待对 QUIT 命令的响应mail.smtp.socketFactory.portint指定使用指定套接字工厂时要连接的端口如果未设置将使用默认端口mail.smtp.ssl.enableboolean如果设置为 true则默认使用 SSL 连接并使用 SSL 端口“smtp”协议mail.smtp.ssl.checkserveridentityboolean如果设置为 true则检查 RFC 2595 指定的服务器标识。默认为 falsemail.smtp.ssl.trustString如果设置并且未指定套接字工厂则启用 MailSSLSocketFactorymail.smtp.socks.hoststring指定将用于连接到邮件服务器的 SOCKS5 代理服务器的主机名mail.smtp.mailextensionString附加到 MAIL 命令的扩展字符串一般来说应用程序不需要直接使用这个包中的类。相反应该使用 javax.mail 包以及子包定义的 API。例如应用程序永远不应该直接构造 SMTPTransport 的实例相反应该使用 Session 方法 getTransport 来获取适当的 Transport 对象。 4.2 IMAP 服务器 IMAP 支持在线和离线操作模式使用 IMAP 的电子邮件客户端通常会将消息留在服务器上直到用户明确删除它们。IMAP 协议提供程序支持以下属性这些属性可以在 JavaMail Session 对象中设置。 属性类型描述mail.imap.userStringIMAP 的默认用户名。mail.imap.hostString要连接的 IMAP 服务器。mail.imap.portint要连接的 IMAP 服务器端口。默认为 143mail.imap.partialfetchboolean控制是否应使用 IMAP 部分提取功能。默认为真mail.imap.fetchsizeint部分提取大小以字节为单位。默认为 16Kmail.imap.connectiontimeoutint以毫秒为单位的套接字连接超时值。默认为无限超时mail.imap.timeoutint以毫秒为单位的套接字 I/O 超时值。默认为无限超时mail.imap.statuscachetimeoutint响应缓存的超时值以毫秒为单位。默认值为 1000零禁用mail.imap.appendbuffersizeint附加到 IMAP 文件夹时要在内存中缓冲的消息的最大大小mail.imap.connectionpoolsizeint连接池中可用连接的最大数量。默认值为 1mail.imap.connectionpooltimeoutint连接池连接的超时值以毫秒为单位默认值为 45000mail.imap.separatestoreconnectionboolean用于指示是否对存储命令使用专用存储连接的标志mail.imap.auth.plain.disableboolean如果为 true则阻止使用 AUTHENTICATE PLAIN 命令mail.imap.auth.ntlm.disableboolean如果为 true则阻止使用 AUTHENTICATE NTLM 命令mail.imap.sasl.mechanismsString要尝试使用的 SASL 机制名称的空格或逗号分隔列表。mail.imap.sasl.authorizationidString在 SASL 身份验证中使用的授权 ID。如果未设置则使用身份验证 ID用户名mail.imap.sasl.realmString与需要领域的 SASL 身份验证机制一起使用的领域mail.imap.auth.ntlm.domainStringNTLM 身份验证域。mail.imap.auth.ntlm.flagsintNTLM 协议特定标志。mail.imap.ssl.enableboolean如果设置为 true则默认使用 SSL 连接并使用 SSL 端口mail.imap.ssl.checkserveridentityboolean如果设置为 true请检查 RFC 2595 指定的服务器标识mail.imap.ssl.trustString如果设置并且未指定套接字工厂则启用 MailSSLSocketFactorymail.imap.socks.hoststring指定将用于连接到邮件服务器的 SOCKS5 代理服务器的主机名mail.imap.minidletimeint此属性以毫秒为单位设置延迟。如果未设置则默认为 10 毫秒一般来说应用程序不需要直接使用这个包中的类。相反他们应该使用 javax.mail 包及其子包定义的 API。应用程序不应直接构造 IMAPStore 或 IMAPFolder 的实例。相反应该使用 Session 方法 getStore 来获取适当的 Store 对象并从中获取 Folder 对象。 4.3 POP3 服务器 POP3 协议提供程序支持以下属性这些属性可以在 JavaMail Session 对象中设置。 Name类型描述mail.pop3.userStringPOP3 的默认用户名mail.pop3.hostString要连接的 POP3 服务器mail.pop3.portint要连接的 POP3 服务器端口默认为 110mail.pop3.connectiontimeoutint以毫秒为单位的套接字连接超时值。默认为无限超时mail.pop3.timeoutint以毫秒为单位的套接字 I/O 超时值。默认为无限超时mail.pop3.rsetbeforequitboolean关闭文件夹时发送 POP3 RSET 命令然后发送 QUIT 命令mail.pop3.ssl.checkserveridentityboolean如果设置为 true请检查 RFC 2595 指定的服务器标识mail.pop3.socks.portstring指定 SOCKS5 代理服务器的端口号。mail.pop3.disabletopboolean如果设置为 true则 POP3 TOP 命令将不会用于获取邮件头通常应用程序不应直接使用此包中的类。相反他们应该使用javax.mail包及其子包定义的 API 。应用程序不应直接构造POP3Store或POP3Folder 的实例。相反应该使用 Session 方法 getStore 来获取适当的 Store 对象并从中获取 Folder 对象。
http://www.hkea.cn/news/14321077/

相关文章:

  • 北京公司网站设计大良制作网站
  • 官方网站建设ppt免费制作ppt
  • 惠州网站建设制作企业网站开发 外文文献
  • 网站怎么做发送邮件的超链接seo顾问合同
  • 威海营销型网站建设简述网站建设的方法
  • 深圳住房和建设管理局官方网站网页设计手机版app下载
  • 网站概述怎么写百度app安装
  • 保定网站开发公司来宾网站建设
  • 龙岩建设局升降机网站免费发布推广的平台
  • 外贸公司网站模板免费wordpress托管站点
  • 以网站和什么为重点建设平台简述网页设计的开发流程
  • 郓城网站制作wordpress 链接新窗口
  • 简述网站开发平台及常用开发工具软文推广套餐
  • 赣州市建设工程造价管理网站俄罗斯乌克兰最新局势
  • 乐平网站设计免费的个人主页网站
  • 织梦修改网站背景颜色杭州app定制
  • 重庆网站推广运营公司国外有哪些设计网站
  • 丹麦做网站公司有哪些网站页脚的制作
  • 大学网站群建设方案智能建造平台
  • 设计网站公司有哪些南通做网站厉害的
  • 福州网站建设熊掌号贸易公司名称大全简单大气
  • 住房和城乡建设部网站三定网站不要了该如何处理
  • 中国智慧团建网站做火锅加盟哪个网站好
  • 网站素材设计框架工信部官网查询系统查询手机
  • 大良营销网站建设资讯招标建设网站
  • 溧水城市建设招标网站wordpress搭建自动发卡
  • 怎么打造自己的网站三维制图培训班在哪里
  • 深圳英文网站开发电子商务网站建设的论文
  • 如何制作公司网站南昌网站建设公司有哪些
  • 如何给公司网站做优化静态网站开发实验报告