关键技术:
- javax.mail.Store: 该类实现特定邮件协议(如POP3)上的读、写、监视、查找等操作。通过它的getFolder方法打开一个javax.mail.Folder。
- javax.mail.Folder: 该类用于描述邮件的分级组织,如收件箱、草稿箱。它的open 方法打开分级组织,close方法关闭分级组织,getMessages方法获得分级组织中的邮件,getNewMessageCount方法获得分级组 织中新邮件的数量,getUnreadMessageCount方法获得分级组织中未读邮件的数量
- 根据MimeMessage的getFrom和getRecipients方法获得邮件的发件人和收件人地址列表,得到的是 InternetAddress数组,根据InternetAddress的getAddress方法获得邮件地址,根据InternetAddress 的getPersonal方法获得邮件地址的个人信息。
- MimeMessage的getSubject、getSentDate、getMessageID方法获得邮件的主题、发送日期和邮件的ID(表示邮件)。
- 通过MimeMessage的getContent方法获得邮件的内容,如果邮件是MIME邮件,那么得到的是一个Multipart的 对象,如果是一共普通的文本邮件,那么得到的是BodyPart对象。Multipart可以包含多个BodyPart,而BodyPart本身又可以是 Multipart。BodyPart的MimeType类型为“multipart/*”时,表示它是一个Mutipart。
- 但一个BodyPart的disposition属性等于Part.ATTACHMENT或者Part.INLINE常量时,表示它带有附件。通过BodyPart的getInputStream方法可以获得附件的输入流。
package
book.email;
import java.io.File;
import java.util.Properties;
/**
* 收邮件的基本信息
*/
public class MailReceiverInfo {
// 邮件服务器的IP、端口和协议
private String mailServerHost;
private String mailServerPort = " 110 " ;
private String protocal = " pop3 " ;
// 登陆邮件服务器的用户名和密码
private String userName;
private String password;
// 保存邮件的路径
private String attachmentDir = " C:/temp/ " ;
private String emailDir = " C:/temp/ " ;
private String emailFileSuffix = " .eml " ;
// 是否需要身份验证
private boolean validate = true ;
/**
* 获得邮件会话属性
*/
public Properties getProperties(){
Properties p = new Properties();
p.put( " mail.pop3.host " , this .mailServerHost);
p.put( " mail.pop3.port " , this .mailServerPort);
p.put( " mail.pop3.auth " , validate ? " true " : " false " );
return p;
}
public String getProtocal() {
return protocal;
}
public void setProtocal(String protocal) {
this .protocal = protocal;
}
public String getAttachmentDir() {
return attachmentDir;
}
public void setAttachmentDir(String attachmentDir) {
if ( ! attachmentDir.endsWith(File.separator)){
attachmentDir = attachmentDir + File.separator;
}
this .attachmentDir = attachmentDir;
}
public String getEmailDir() {
return emailDir;
}
public void setEmailDir(String emailDir) {
if ( ! emailDir.endsWith(File.separator)){
emailDir = emailDir + File.separator;
}
this .emailDir = emailDir;
}
public String getEmailFileSuffix() {
return emailFileSuffix;
}
public void setEmailFileSuffix(String emailFileSuffix) {
if ( ! emailFileSuffix.startsWith( " . " )){
emailFileSuffix = " . " + emailFileSuffix;
}
this .emailFileSuffix = emailFileSuffix;
}
public String getMailServerHost() {
return mailServerHost;
}
public void setMailServerHost(String mailServerHost) {
this .mailServerHost = mailServerHost;
}
public String getMailServerPort() {
return mailServerPort;
}
public void setMailServerPort(String mailServerPort) {
this .mailServerPort = mailServerPort;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this .password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this .userName = userName;
}
public boolean isValidate() {
return validate;
}
public void setValidate( boolean validate) {
this .validate = validate;
}
}
import java.io.File;
import java.util.Properties;
/**
* 收邮件的基本信息
*/
public class MailReceiverInfo {
// 邮件服务器的IP、端口和协议
private String mailServerHost;
private String mailServerPort = " 110 " ;
private String protocal = " pop3 " ;
// 登陆邮件服务器的用户名和密码
private String userName;
private String password;
// 保存邮件的路径
private String attachmentDir = " C:/temp/ " ;
private String emailDir = " C:/temp/ " ;
private String emailFileSuffix = " .eml " ;
// 是否需要身份验证
private boolean validate = true ;
/**
* 获得邮件会话属性
*/
public Properties getProperties(){
Properties p = new Properties();
p.put( " mail.pop3.host " , this .mailServerHost);
p.put( " mail.pop3.port " , this .mailServerPort);
p.put( " mail.pop3.auth " , validate ? " true " : " false " );
return p;
}
public String getProtocal() {
return protocal;
}
public void setProtocal(String protocal) {
this .protocal = protocal;
}
public String getAttachmentDir() {
return attachmentDir;
}
public void setAttachmentDir(String attachmentDir) {
if ( ! attachmentDir.endsWith(File.separator)){
attachmentDir = attachmentDir + File.separator;
}
this .attachmentDir = attachmentDir;
}
public String getEmailDir() {
return emailDir;
}
public void setEmailDir(String emailDir) {
if ( ! emailDir.endsWith(File.separator)){
emailDir = emailDir + File.separator;
}
this .emailDir = emailDir;
}
public String getEmailFileSuffix() {
return emailFileSuffix;
}
public void setEmailFileSuffix(String emailFileSuffix) {
if ( ! emailFileSuffix.startsWith( " . " )){
emailFileSuffix = " . " + emailFileSuffix;
}
this .emailFileSuffix = emailFileSuffix;
}
public String getMailServerHost() {
return mailServerHost;
}
public void setMailServerHost(String mailServerHost) {
this .mailServerHost = mailServerHost;
}
public String getMailServerPort() {
return mailServerPort;
}
public void setMailServerPort(String mailServerPort) {
this .mailServerPort = mailServerPort;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this .password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this .userName = userName;
}
public boolean isValidate() {
return validate;
}
public void setValidate( boolean validate) {
this .validate = validate;
}
}
package
book.email;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.Date;
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.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
/**
* 邮件接收器,目前支持pop3协议。
* 能够接收文本、HTML和带有附件的邮件
*/
public class MailReceiver {
// 收邮件的参数配置
private MailReceiverInfo receiverInfo;
// 与邮件服务器连接后得到的邮箱
private Store store;
// 收件箱
private Folder folder;
// 收件箱中的邮件消息
private Message[] messages;
// 当前正在处理的邮件消息
private Message currentMessage;
private String currentEmailFileName;
public MailReceiver(MailReceiverInfo receiverInfo) {
this .receiverInfo = receiverInfo;
}
/**
* 收邮件
*/
public void receiveAllMail() throws Exception{
if ( this .receiverInfo == null ){
throw new Exception( " 必须提供接收邮件的参数! " );
}
// 连接到服务器
if ( this .connectToServer()) {
// 打开收件箱
if ( this .openInBoxFolder()) {
// 获取所有邮件
this .getAllMail();
this .closeConnection();
} else {
throw new Exception( " 打开收件箱失败! " );
}
} else {
throw new Exception( " 连接邮件服务器失败! " );
}
}
/**
* 登陆邮件服务器
*/
private boolean connectToServer() {
// 判断是否需要身份认证
MyAuthenticator authenticator = null ;
if ( this .receiverInfo.isValidate()) {
// 如果需要身份认证,则创建一个密码验证器
authenticator = new MyAuthenticator( this .receiverInfo.getUserName(),
this .receiverInfo.getPassword());
}
// 创建session
Session session = Session.getInstance( this .receiverInfo
.getProperties(), authenticator);
// 创建store,建立连接
try {
this .store = session.getStore( this .receiverInfo.getProtocal());
} catch (NoSuchProviderException e) {
System.out.println( " 连接服务器失败! " );
return false ;
}
System.out.println( " connecting " );
try {
this .store.connect();
} catch (MessagingException e) {
System.out.println( " 连接服务器失败! " );
return false ;
}
System.out.println( " 连接服务器成功 " );
return true ;
}
/**
* 打开收件箱
*/
private boolean openInBoxFolder() {
try {
this .folder = store.getFolder( " INBOX " );
// 只读
folder.open(Folder.READ_ONLY);
return true ;
} catch (MessagingException e) {
System.err.println( " 打开收件箱失败! " );
}
return false ;
}
/**
* 断开与邮件服务器的连接
*/
private boolean closeConnection() {
try {
if ( this .folder.isOpen()) {
this .folder.close( true );
}
this .store.close();
System.out.println( " 成功关闭与邮件服务器的连接! " );
return true ;
} catch (Exception e) {
System.out.println( " 关闭和邮件服务器之间连接时出错! " );
}
return false ;
}
/**
* 获取messages中的所有邮件
* @throws MessagingException
*/
private void getAllMail() throws MessagingException {
// 从邮件文件夹获取邮件信息
this .messages = this .folder.getMessages();
System.out.println( " 总的邮件数目: " + messages.length);
System.out.println( " 新邮件数目: " + this .getNewMessageCount());
System.out.println( " 未读邮件数目: " + this .getUnreadMessageCount());
// 将要下载的邮件的数量。
int mailArrayLength = this .getMessageCount();
System.out.println( " 一共有邮件 " + mailArrayLength + " 封 " );
int errorCounter = 0 ; // 邮件下载出错计数器
int successCounter = 0 ;
for ( int index = 0 ; index < mailArrayLength; index ++ ) {
try {
this .currentMessage = (messages[index]); // 设置当前message
System.out.println( " 正在获取第 " + index + " 封邮件 " );
this .showMailBasicInfo();
getMail(); // 获取当前message
System.out.println( " 成功获取第 " + index + " 封邮件 " );
successCounter ++ ;
} catch (Throwable e) {
errorCounter ++ ;
System.err.println( " 下载第 " + index + " 封邮件时出错 " );
}
}
System.out.println( " ------------------ " );
System.out.println( " 成功下载了 " + successCounter + " 封邮件 " );
System.out.println( " 失败下载了 " + errorCounter + " 封邮件 " );
System.out.println( " ------------------ " );
}
/**
* 显示邮件的基本信息
*/
private void showMailBasicInfo() throws Exception{
showMailBasicInfo( this .currentMessage);
}
private void showMailBasicInfo(Message message) throws Exception {
System.out.println( " -------- 邮件ID: " + this .getMessageId()
+ " --------- " );
System.out.println( " From: " + this .getFrom());
System.out.println( " To: " + this .getTOAddress());
System.out.println( " CC: " + this .getCCAddress());
System.out.println( " BCC: " + this .getBCCAddress());
System.out.println( " Subject: " + this .getSubject());
System.out.println( " 发送时间:: " + this .getSentDate());
System.out.println( " 是新邮件? " + this .isNew());
System.out.println( " 要求回执? " + this .getReplySign());
System.out.println( " 包含附件? " + this .isContainAttach());
System.out.println( " ------------------------------ " );
}
/**
* 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同
* "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址
*/
private String getTOAddress() throws Exception {
return getMailAddress( " TO " , this .currentMessage);
}
private String getCCAddress() throws Exception {
return getMailAddress( " CC " , this .currentMessage);
}
private String getBCCAddress() throws Exception {
return getMailAddress( " BCC " , this .currentMessage);
}
/**
* 获得邮件地址
* @param type 类型,如收件人、抄送人、密送人
* @param mimeMessage 邮件消息
* @return
* @throws Exception
*/
private String getMailAddress(String type, Message mimeMessage)
throws Exception {
String mailaddr = "" ;
String addtype = type.toUpperCase();
InternetAddress[] address = null ;
if (addtype.equals( " TO " ) || addtype.equals( " CC " )
|| addtype.equals( " BCC " )) {
if (addtype.equals( " TO " )) {
address = (InternetAddress[]) mimeMessage
.getRecipients(Message.RecipientType.TO);
} else if (addtype.equals( " CC " )) {
address = (InternetAddress[]) mimeMessage
.getRecipients(Message.RecipientType.CC);
} else {
address = (InternetAddress[]) mimeMessage
.getRecipients(Message.RecipientType.BCC);
}
if (address != null ) {
for ( int i = 0 ; i < address.length; i ++ ) {
// 先获取邮件地址
String email = address[i].getAddress();
if (email == null ){
email = "" ;
} else {
email = MimeUtility.decodeText(email);
}
// 再取得个人描述信息
String personal = address[i].getPersonal();
if (personal == null ){
personal = "" ;
} else {
personal = MimeUtility.decodeText(personal);
}
// 将个人描述信息与邮件地址连起来
String compositeto = personal + " < " + email + " > " ;
// 多个地址时,用逗号分开
mailaddr += " , " + compositeto;
}
mailaddr = mailaddr.substring( 1 );
}
} else {
throw new Exception( " 错误的地址类型!! " );
}
return mailaddr;
}
/**
* 获得发件人的地址和姓名
* @throws Exception
*/
private String getFrom() throws Exception {
return getFrom( this .currentMessage);
}
private String getFrom(Message mimeMessage) throws Exception {
InternetAddress[] address = (InternetAddress[]) mimeMessage.getFrom();
// 获得发件人的邮箱
String from = address[ 0 ].getAddress();
if (from == null ){
from = "" ;
}
// 获得发件人的描述信息
String personal = address[ 0 ].getPersonal();
if (personal == null ){
personal = "" ;
}
// 拼成发件人完整信息
String fromaddr = personal + " < " + from + " > " ;
return fromaddr;
}
/**
* 获取messages中message的数量
* @return
*/
private int getMessageCount() {
return this .messages.length;
}
/**
* 获得收件箱中新邮件的数量
* @return
* @throws MessagingException
*/
private int getNewMessageCount() throws MessagingException {
return this .folder.getNewMessageCount();
}
/**
* 获得收件箱中未读邮件的数量
* @return
* @throws MessagingException
*/
private int getUnreadMessageCount() throws MessagingException {
return this .folder.getUnreadMessageCount();
}
/**
* 获得邮件主题
*/
private String getSubject() throws MessagingException {
return getSubject( this .currentMessage);
}
private String getSubject(Message mimeMessage) throws MessagingException {
String subject = "" ;
try {
// 将邮件主题解码
subject = MimeUtility.decodeText(mimeMessage.getSubject());
if (subject == null ){
subject = "" ;
}
} catch (Exception exce) {
}
return subject;
}
/**
* 获得邮件发送日期
*/
private Date getSentDate() throws Exception {
return getSentDate( this .currentMessage);
}
private Date getSentDate(Message mimeMessage) throws Exception {
return mimeMessage.getSentDate();
}
/**
* 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"
*/
private boolean getReplySign() throws MessagingException {
return getReplySign( this .currentMessage);
}
private boolean getReplySign(Message mimeMessage) throws MessagingException {
boolean replysign = false ;
String needreply[] = mimeMessage
.getHeader( " Disposition-Notification-To " );
if (needreply != null ) {
replysign = true ;
}
return replysign;
}
/**
* 获得此邮件的Message-ID
*/
private String getMessageId() throws MessagingException {
return getMessageId( this .currentMessage);
}
private String getMessageId(Message mimeMessage) throws MessagingException {
return ((MimeMessage) mimeMessage).getMessageID();
}
/**
* 判断此邮件是否已读,如果未读返回返回false,反之返回true
*/
private boolean isNew() throws MessagingException {
return isNew( this .currentMessage);
}
private boolean isNew(Message mimeMessage) throws MessagingException {
boolean isnew = false ;
Flags flags = mimeMessage.getFlags();
Flags.Flag[] flag = flags.getSystemFlags();
for ( int i = 0 ; i < flag.length; i ++ ) {
if (flag[i] == Flags.Flag.SEEN) {
isnew = true ;
break ;
}
}
return isnew;
}
/**
* 判断此邮件是否包含附件
*/
private boolean isContainAttach() throws Exception {
return isContainAttach( this .currentMessage);
}
private boolean isContainAttach(Part part) throws Exception {
boolean attachflag = false ;
if (part.isMimeType( " multipart/* " )) {
// 如果邮件体包含多部分
Multipart mp = (Multipart) part.getContent();
// 遍历每部分
for ( int i = 0 ; i < mp.getCount(); i ++ ) {
// 获得每部分的主体
BodyPart bodyPart = mp.getBodyPart(i);
String disposition = bodyPart.getDisposition();
if ((disposition != null )
&& ((disposition.equals(Part.ATTACHMENT)) || (disposition
.equals(Part.INLINE)))){
attachflag = true ;
} else if (bodyPart.isMimeType( " multipart/* " )) {
attachflag = isContainAttach((Part) bodyPart);
} else {
String contype = bodyPart.getContentType();
if (contype.toLowerCase().indexOf( " application " ) != - 1 ){
attachflag = true ;
}
if (contype.toLowerCase().indexOf( " name " ) != - 1 ){
attachflag = true ;
}
}
}
} else if (part.isMimeType( " message/rfc822 " )) {
attachflag = isContainAttach((Part) part.getContent());
}
return attachflag;
}
/**
* 获得当前邮件
*/
private void getMail() throws Exception {
try {
this .saveMessageAsFile(currentMessage);
this .parseMessage(currentMessage);
} catch (IOException e) {
throw new IOException( " 保存邮件出错,检查保存路径 " );
} catch (MessagingException e) {
throw new MessagingException( " 邮件转换出错 " );
} catch (Exception e) {
e.printStackTrace();
throw new Exception( " 未知错误 " );
}
}
/**
* 保存邮件源文件
*/
private void saveMessageAsFile(Message message) {
try {
// 将邮件的ID中尖括号中的部分做为邮件的文件名
String oriFileName = getInfoBetweenBrackets( this .getMessageId(message)
.toString());
// 设置文件后缀名。若是附件则设法取得其文件后缀名作为将要保存文件的后缀名,
// 若是正文部分则用.htm做后缀名
String emlName = oriFileName;
String fileNameWidthExtension = this .receiverInfo.getEmailDir()
+ oriFileName + this .receiverInfo.getEmailFileSuffix();
File storeFile = new File(fileNameWidthExtension);
for ( int i = 0 ; storeFile.exists(); i ++ ) {
emlName = oriFileName + i;
fileNameWidthExtension = this .receiverInfo.getEmailDir()
+ emlName + this .receiverInfo.getEmailFileSuffix();
storeFile = new File(fileNameWidthExtension);
}
this .currentEmailFileName = emlName;
System.out.println( " 邮件消息的存储路径: " + fileNameWidthExtension);
// 将邮件消息的内容写入ByteArrayOutputStream流中
ByteArrayOutputStream baos = new ByteArrayOutputStream();
message.writeTo(baos);
// 读取邮件消息流中的数据
StringReader in = new StringReader(baos.toString());
// 存储到文件
saveFile(fileNameWidthExtension, in);
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 解析邮件
*/
private void parseMessage(Message message) throws IOException,
MessagingException {
Object content = message.getContent();
// 处理多部分邮件
if (content instanceof Multipart) {
handleMultipart((Multipart) content);
} else {
handlePart(message);
}
}
/*
* 解析Multipart
*/
private void handleMultipart(Multipart multipart) throws MessagingException,
IOException {
for ( int i = 0 , n = multipart.getCount(); i < n; i ++ ) {
handlePart(multipart.getBodyPart(i));
}
}
/*
* 解析指定part,从中提取文件
*/
private void handlePart(Part part) throws MessagingException, IOException {
String disposition = part.getDisposition();
String contentType = part.getContentType();
String fileNameWidthExtension = "" ;
// 获得邮件的内容输入流
InputStreamReader sbis = new InputStreamReader(part.getInputStream());
// 没有附件的情况
if (disposition == null ) {
if ((contentType.length() >= 10 )
&& (contentType.toLowerCase().substring( 0 , 10 )
.equals( " text/plain " ))) {
fileNameWidthExtension = this .receiverInfo.getAttachmentDir()
+ this .currentEmailFileName + " .txt " ;
} else if ((contentType.length() >= 9 ) // Check if html
&& (contentType.toLowerCase().substring( 0 , 9 )
.equals( " text/html " ))) {
fileNameWidthExtension = this .receiverInfo.getAttachmentDir()
+ this .currentEmailFileName + " .html " ;
} else if ((contentType.length() >= 9 ) // Check if html
&& (contentType.toLowerCase().substring( 0 , 9 )
.equals( " image/gif " ))) {
fileNameWidthExtension = this .receiverInfo.getAttachmentDir()
+ this .currentEmailFileName + " .gif " ;
} else if ((contentType.length() >= 11 )
&& contentType.toLowerCase().substring( 0 , 11 ).equals(
" multipart/* " )) {
// System.out.println("multipart body: " + contentType);
handleMultipart((Multipart) part.getContent());
} else { // Unknown type
// System.out.println("Other body: " + contentType);
fileNameWidthExtension = this .receiverInfo.getAttachmentDir()
+ this .currentEmailFileName + " .txt " ;
}
// 存储内容文件
System.out.println( " 保存邮件内容到: " + fileNameWidthExtension);
saveFile(fileNameWidthExtension, sbis);
return ;
}
// 各种有附件的情况
String name = "" ;
if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
name = getFileName(part);
// System.out.println("Attachment: " + name + " : "
// + contentType);
fileNameWidthExtension = this .receiverInfo.getAttachmentDir() + name;
} else if (disposition.equalsIgnoreCase(Part.INLINE)) {
name = getFileName(part);
// System.out.println("Inline: " + name + " : "
// + contentType);
fileNameWidthExtension = this .receiverInfo.getAttachmentDir() + name;
} else {
// System.out.println("Other: " + disposition);
}
// 存储各类附件
if ( ! fileNameWidthExtension.equals( "" )) {
System.out.println( " 保存邮件附件到: " + fileNameWidthExtension);
saveFile(fileNameWidthExtension, sbis);
}
}
private String getFileName(Part part) throws MessagingException,
UnsupportedEncodingException {
String fileName = part.getFileName();
fileName = MimeUtility.decodeText(fileName);
String name = fileName;
if (fileName != null ) {
int index = fileName.lastIndexOf( " / " );
if (index != - 1 ) {
name = fileName.substring(index + 1 );
}
}
return name;
}
/**
* 保存文件内容
* @param fileName 文件名
* @param input 输入流
* @throws IOException
*/
private void saveFile(String fileName, Reader input) throws IOException {
// 为了放置文件名重名,在重名的文件名后面天上数字
File file = new File(fileName);
// 先取得文件名的后缀
int lastDot = fileName.lastIndexOf( " . " );
String extension = fileName.substring(lastDot);
fileName = fileName.substring( 0 , lastDot);
for ( int i = 0 ; file.exists(); i ++ ) {
// 如果文件重名,则添加i
file = new File(fileName + i + extension);
}
// 从输入流中读取数据,写入文件输出流
FileWriter fos = new FileWriter(file);
BufferedWriter bos = new BufferedWriter(fos);
BufferedReader bis = new BufferedReader(input);
int aByte;
while ((aByte = bis.read()) != - 1 ) {
bos.write(aByte);
}
// 关闭流
bos.flush();
bos.close();
bis.close();
}
/**
* 获得尖括号之间的字符
* @param str
* @return
* @throws Exception
*/
private String getInfoBetweenBrackets(String str) throws Exception {
int i, j; // 用于标识字符串中的"<"和">"的位置
if (str == null ) {
str = " error " ;
return str;
}
i = str.lastIndexOf( " < " );
j = str.lastIndexOf( " > " );
if (i != - 1 && j != - 1 ){
str = str.substring(i + 1 , j);
}
return str;
}
public static void main(String[] args) throws Exception {
MailReceiverInfo receiverInfo = new MailReceiverInfo();
receiverInfo.setMailServerHost( " pop.163.com " );
receiverInfo.setMailServerPort( " 110 " );
receiverInfo.setValidate( true );
receiverInfo.setUserName( " *** " );
receiverInfo.setPassword( " *** " );
receiverInfo.setAttachmentDir( " C:/temp/mail/ " );
receiverInfo.setEmailDir( " C:/temp/mail/ " );
MailReceiver receiver = new MailReceiver(receiverInfo);
receiver.receiveAllMail();
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.Date;
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.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
/**
* 邮件接收器,目前支持pop3协议。
* 能够接收文本、HTML和带有附件的邮件
*/
public class MailReceiver {
// 收邮件的参数配置
private MailReceiverInfo receiverInfo;
// 与邮件服务器连接后得到的邮箱
private Store store;
// 收件箱
private Folder folder;
// 收件箱中的邮件消息
private Message[] messages;
// 当前正在处理的邮件消息
private Message currentMessage;
private String currentEmailFileName;
public MailReceiver(MailReceiverInfo receiverInfo) {
this .receiverInfo = receiverInfo;
}
/**
* 收邮件
*/
public void receiveAllMail() throws Exception{
if ( this .receiverInfo == null ){
throw new Exception( " 必须提供接收邮件的参数! " );
}
// 连接到服务器
if ( this .connectToServer()) {
// 打开收件箱
if ( this .openInBoxFolder()) {
// 获取所有邮件
this .getAllMail();
this .closeConnection();
} else {
throw new Exception( " 打开收件箱失败! " );
}
} else {
throw new Exception( " 连接邮件服务器失败! " );
}
}
/**
* 登陆邮件服务器
*/
private boolean connectToServer() {
// 判断是否需要身份认证
MyAuthenticator authenticator = null ;
if ( this .receiverInfo.isValidate()) {
// 如果需要身份认证,则创建一个密码验证器
authenticator = new MyAuthenticator( this .receiverInfo.getUserName(),
this .receiverInfo.getPassword());
}
// 创建session
Session session = Session.getInstance( this .receiverInfo
.getProperties(), authenticator);
// 创建store,建立连接
try {
this .store = session.getStore( this .receiverInfo.getProtocal());
} catch (NoSuchProviderException e) {
System.out.println( " 连接服务器失败! " );
return false ;
}
System.out.println( " connecting " );
try {
this .store.connect();
} catch (MessagingException e) {
System.out.println( " 连接服务器失败! " );
return false ;
}
System.out.println( " 连接服务器成功 " );
return true ;
}
/**
* 打开收件箱
*/
private boolean openInBoxFolder() {
try {
this .folder = store.getFolder( " INBOX " );
// 只读
folder.open(Folder.READ_ONLY);
return true ;
} catch (MessagingException e) {
System.err.println( " 打开收件箱失败! " );
}
return false ;
}
/**
* 断开与邮件服务器的连接
*/
private boolean closeConnection() {
try {
if ( this .folder.isOpen()) {
this .folder.close( true );
}
this .store.close();
System.out.println( " 成功关闭与邮件服务器的连接! " );
return true ;
} catch (Exception e) {
System.out.println( " 关闭和邮件服务器之间连接时出错! " );
}
return false ;
}
/**
* 获取messages中的所有邮件
* @throws MessagingException
*/
private void getAllMail() throws MessagingException {
// 从邮件文件夹获取邮件信息
this .messages = this .folder.getMessages();
System.out.println( " 总的邮件数目: " + messages.length);
System.out.println( " 新邮件数目: " + this .getNewMessageCount());
System.out.println( " 未读邮件数目: " + this .getUnreadMessageCount());
// 将要下载的邮件的数量。
int mailArrayLength = this .getMessageCount();
System.out.println( " 一共有邮件 " + mailArrayLength + " 封 " );
int errorCounter = 0 ; // 邮件下载出错计数器
int successCounter = 0 ;
for ( int index = 0 ; index < mailArrayLength; index ++ ) {
try {
this .currentMessage = (messages[index]); // 设置当前message
System.out.println( " 正在获取第 " + index + " 封邮件 " );
this .showMailBasicInfo();
getMail(); // 获取当前message
System.out.println( " 成功获取第 " + index + " 封邮件 " );
successCounter ++ ;
} catch (Throwable e) {
errorCounter ++ ;
System.err.println( " 下载第 " + index + " 封邮件时出错 " );
}
}
System.out.println( " ------------------ " );
System.out.println( " 成功下载了 " + successCounter + " 封邮件 " );
System.out.println( " 失败下载了 " + errorCounter + " 封邮件 " );
System.out.println( " ------------------ " );
}
/**
* 显示邮件的基本信息
*/
private void showMailBasicInfo() throws Exception{
showMailBasicInfo( this .currentMessage);
}
private void showMailBasicInfo(Message message) throws Exception {
System.out.println( " -------- 邮件ID: " + this .getMessageId()
+ " --------- " );
System.out.println( " From: " + this .getFrom());
System.out.println( " To: " + this .getTOAddress());
System.out.println( " CC: " + this .getCCAddress());
System.out.println( " BCC: " + this .getBCCAddress());
System.out.println( " Subject: " + this .getSubject());
System.out.println( " 发送时间:: " + this .getSentDate());
System.out.println( " 是新邮件? " + this .isNew());
System.out.println( " 要求回执? " + this .getReplySign());
System.out.println( " 包含附件? " + this .isContainAttach());
System.out.println( " ------------------------------ " );
}
/**
* 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同
* "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址
*/
private String getTOAddress() throws Exception {
return getMailAddress( " TO " , this .currentMessage);
}
private String getCCAddress() throws Exception {
return getMailAddress( " CC " , this .currentMessage);
}
private String getBCCAddress() throws Exception {
return getMailAddress( " BCC " , this .currentMessage);
}
/**
* 获得邮件地址
* @param type 类型,如收件人、抄送人、密送人
* @param mimeMessage 邮件消息
* @return
* @throws Exception
*/
private String getMailAddress(String type, Message mimeMessage)
throws Exception {
String mailaddr = "" ;
String addtype = type.toUpperCase();
InternetAddress[] address = null ;
if (addtype.equals( " TO " ) || addtype.equals( " CC " )
|| addtype.equals( " BCC " )) {
if (addtype.equals( " TO " )) {
address = (InternetAddress[]) mimeMessage
.getRecipients(Message.RecipientType.TO);
} else if (addtype.equals( " CC " )) {
address = (InternetAddress[]) mimeMessage
.getRecipients(Message.RecipientType.CC);
} else {
address = (InternetAddress[]) mimeMessage
.getRecipients(Message.RecipientType.BCC);
}
if (address != null ) {
for ( int i = 0 ; i < address.length; i ++ ) {
// 先获取邮件地址
String email = address[i].getAddress();
if (email == null ){
email = "" ;
} else {
email = MimeUtility.decodeText(email);
}
// 再取得个人描述信息
String personal = address[i].getPersonal();
if (personal == null ){
personal = "" ;
} else {
personal = MimeUtility.decodeText(personal);
}
// 将个人描述信息与邮件地址连起来
String compositeto = personal + " < " + email + " > " ;
// 多个地址时,用逗号分开
mailaddr += " , " + compositeto;
}
mailaddr = mailaddr.substring( 1 );
}
} else {
throw new Exception( " 错误的地址类型!! " );
}
return mailaddr;
}
/**
* 获得发件人的地址和姓名
* @throws Exception
*/
private String getFrom() throws Exception {
return getFrom( this .currentMessage);
}
private String getFrom(Message mimeMessage) throws Exception {
InternetAddress[] address = (InternetAddress[]) mimeMessage.getFrom();
// 获得发件人的邮箱
String from = address[ 0 ].getAddress();
if (from == null ){
from = "" ;
}
// 获得发件人的描述信息
String personal = address[ 0 ].getPersonal();
if (personal == null ){
personal = "" ;
}
// 拼成发件人完整信息
String fromaddr = personal + " < " + from + " > " ;
return fromaddr;
}
/**
* 获取messages中message的数量
* @return
*/
private int getMessageCount() {
return this .messages.length;
}
/**
* 获得收件箱中新邮件的数量
* @return
* @throws MessagingException
*/
private int getNewMessageCount() throws MessagingException {
return this .folder.getNewMessageCount();
}
/**
* 获得收件箱中未读邮件的数量
* @return
* @throws MessagingException
*/
private int getUnreadMessageCount() throws MessagingException {
return this .folder.getUnreadMessageCount();
}
/**
* 获得邮件主题
*/
private String getSubject() throws MessagingException {
return getSubject( this .currentMessage);
}
private String getSubject(Message mimeMessage) throws MessagingException {
String subject = "" ;
try {
// 将邮件主题解码
subject = MimeUtility.decodeText(mimeMessage.getSubject());
if (subject == null ){
subject = "" ;
}
} catch (Exception exce) {
}
return subject;
}
/**
* 获得邮件发送日期
*/
private Date getSentDate() throws Exception {
return getSentDate( this .currentMessage);
}
private Date getSentDate(Message mimeMessage) throws Exception {
return mimeMessage.getSentDate();
}
/**
* 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"
*/
private boolean getReplySign() throws MessagingException {
return getReplySign( this .currentMessage);
}
private boolean getReplySign(Message mimeMessage) throws MessagingException {
boolean replysign = false ;
String needreply[] = mimeMessage
.getHeader( " Disposition-Notification-To " );
if (needreply != null ) {
replysign = true ;
}
return replysign;
}
/**
* 获得此邮件的Message-ID
*/
private String getMessageId() throws MessagingException {
return getMessageId( this .currentMessage);
}
private String getMessageId(Message mimeMessage) throws MessagingException {
return ((MimeMessage) mimeMessage).getMessageID();
}
/**
* 判断此邮件是否已读,如果未读返回返回false,反之返回true
*/
private boolean isNew() throws MessagingException {
return isNew( this .currentMessage);
}
private boolean isNew(Message mimeMessage) throws MessagingException {
boolean isnew = false ;
Flags flags = mimeMessage.getFlags();
Flags.Flag[] flag = flags.getSystemFlags();
for ( int i = 0 ; i < flag.length; i ++ ) {
if (flag[i] == Flags.Flag.SEEN) {
isnew = true ;
break ;
}
}
return isnew;
}
/**
* 判断此邮件是否包含附件
*/
private boolean isContainAttach() throws Exception {
return isContainAttach( this .currentMessage);
}
private boolean isContainAttach(Part part) throws Exception {
boolean attachflag = false ;
if (part.isMimeType( " multipart/* " )) {
// 如果邮件体包含多部分
Multipart mp = (Multipart) part.getContent();
// 遍历每部分
for ( int i = 0 ; i < mp.getCount(); i ++ ) {
// 获得每部分的主体
BodyPart bodyPart = mp.getBodyPart(i);
String disposition = bodyPart.getDisposition();
if ((disposition != null )
&& ((disposition.equals(Part.ATTACHMENT)) || (disposition
.equals(Part.INLINE)))){
attachflag = true ;
} else if (bodyPart.isMimeType( " multipart/* " )) {
attachflag = isContainAttach((Part) bodyPart);
} else {
String contype = bodyPart.getContentType();
if (contype.toLowerCase().indexOf( " application " ) != - 1 ){
attachflag = true ;
}
if (contype.toLowerCase().indexOf( " name " ) != - 1 ){
attachflag = true ;
}
}
}
} else if (part.isMimeType( " message/rfc822 " )) {
attachflag = isContainAttach((Part) part.getContent());
}
return attachflag;
}
/**
* 获得当前邮件
*/
private void getMail() throws Exception {
try {
this .saveMessageAsFile(currentMessage);
this .parseMessage(currentMessage);
} catch (IOException e) {
throw new IOException( " 保存邮件出错,检查保存路径 " );
} catch (MessagingException e) {
throw new MessagingException( " 邮件转换出错 " );
} catch (Exception e) {
e.printStackTrace();
throw new Exception( " 未知错误 " );
}
}
/**
* 保存邮件源文件
*/
private void saveMessageAsFile(Message message) {
try {
// 将邮件的ID中尖括号中的部分做为邮件的文件名
String oriFileName = getInfoBetweenBrackets( this .getMessageId(message)
.toString());
// 设置文件后缀名。若是附件则设法取得其文件后缀名作为将要保存文件的后缀名,
// 若是正文部分则用.htm做后缀名
String emlName = oriFileName;
String fileNameWidthExtension = this .receiverInfo.getEmailDir()
+ oriFileName + this .receiverInfo.getEmailFileSuffix();
File storeFile = new File(fileNameWidthExtension);
for ( int i = 0 ; storeFile.exists(); i ++ ) {
emlName = oriFileName + i;
fileNameWidthExtension = this .receiverInfo.getEmailDir()
+ emlName + this .receiverInfo.getEmailFileSuffix();
storeFile = new File(fileNameWidthExtension);
}
this .currentEmailFileName = emlName;
System.out.println( " 邮件消息的存储路径: " + fileNameWidthExtension);
// 将邮件消息的内容写入ByteArrayOutputStream流中
ByteArrayOutputStream baos = new ByteArrayOutputStream();
message.writeTo(baos);
// 读取邮件消息流中的数据
StringReader in = new StringReader(baos.toString());
// 存储到文件
saveFile(fileNameWidthExtension, in);
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 解析邮件
*/
private void parseMessage(Message message) throws IOException,
MessagingException {
Object content = message.getContent();
// 处理多部分邮件
if (content instanceof Multipart) {
handleMultipart((Multipart) content);
} else {
handlePart(message);
}
}
/*
* 解析Multipart
*/
private void handleMultipart(Multipart multipart) throws MessagingException,
IOException {
for ( int i = 0 , n = multipart.getCount(); i < n; i ++ ) {
handlePart(multipart.getBodyPart(i));
}
}
/*
* 解析指定part,从中提取文件
*/
private void handlePart(Part part) throws MessagingException, IOException {
String disposition = part.getDisposition();
String contentType = part.getContentType();
String fileNameWidthExtension = "" ;
// 获得邮件的内容输入流
InputStreamReader sbis = new InputStreamReader(part.getInputStream());
// 没有附件的情况
if (disposition == null ) {
if ((contentType.length() >= 10 )
&& (contentType.toLowerCase().substring( 0 , 10 )
.equals( " text/plain " ))) {
fileNameWidthExtension = this .receiverInfo.getAttachmentDir()
+ this .currentEmailFileName + " .txt " ;
} else if ((contentType.length() >= 9 ) // Check if html
&& (contentType.toLowerCase().substring( 0 , 9 )
.equals( " text/html " ))) {
fileNameWidthExtension = this .receiverInfo.getAttachmentDir()
+ this .currentEmailFileName + " .html " ;
} else if ((contentType.length() >= 9 ) // Check if html
&& (contentType.toLowerCase().substring( 0 , 9 )
.equals( " image/gif " ))) {
fileNameWidthExtension = this .receiverInfo.getAttachmentDir()
+ this .currentEmailFileName + " .gif " ;
} else if ((contentType.length() >= 11 )
&& contentType.toLowerCase().substring( 0 , 11 ).equals(
" multipart/* " )) {
// System.out.println("multipart body: " + contentType);
handleMultipart((Multipart) part.getContent());
} else { // Unknown type
// System.out.println("Other body: " + contentType);
fileNameWidthExtension = this .receiverInfo.getAttachmentDir()
+ this .currentEmailFileName + " .txt " ;
}
// 存储内容文件
System.out.println( " 保存邮件内容到: " + fileNameWidthExtension);
saveFile(fileNameWidthExtension, sbis);
return ;
}
// 各种有附件的情况
String name = "" ;
if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
name = getFileName(part);
// System.out.println("Attachment: " + name + " : "
// + contentType);
fileNameWidthExtension = this .receiverInfo.getAttachmentDir() + name;
} else if (disposition.equalsIgnoreCase(Part.INLINE)) {
name = getFileName(part);
// System.out.println("Inline: " + name + " : "
// + contentType);
fileNameWidthExtension = this .receiverInfo.getAttachmentDir() + name;
} else {
// System.out.println("Other: " + disposition);
}
// 存储各类附件
if ( ! fileNameWidthExtension.equals( "" )) {
System.out.println( " 保存邮件附件到: " + fileNameWidthExtension);
saveFile(fileNameWidthExtension, sbis);
}
}
private String getFileName(Part part) throws MessagingException,
UnsupportedEncodingException {
String fileName = part.getFileName();
fileName = MimeUtility.decodeText(fileName);
String name = fileName;
if (fileName != null ) {
int index = fileName.lastIndexOf( " / " );
if (index != - 1 ) {
name = fileName.substring(index + 1 );
}
}
return name;
}
/**
* 保存文件内容
* @param fileName 文件名
* @param input 输入流
* @throws IOException
*/
private void saveFile(String fileName, Reader input) throws IOException {
// 为了放置文件名重名,在重名的文件名后面天上数字
File file = new File(fileName);
// 先取得文件名的后缀
int lastDot = fileName.lastIndexOf( " . " );
String extension = fileName.substring(lastDot);
fileName = fileName.substring( 0 , lastDot);
for ( int i = 0 ; file.exists(); i ++ ) {
// 如果文件重名,则添加i
file = new File(fileName + i + extension);
}
// 从输入流中读取数据,写入文件输出流
FileWriter fos = new FileWriter(file);
BufferedWriter bos = new BufferedWriter(fos);
BufferedReader bis = new BufferedReader(input);
int aByte;
while ((aByte = bis.read()) != - 1 ) {
bos.write(aByte);
}
// 关闭流
bos.flush();
bos.close();
bis.close();
}
/**
* 获得尖括号之间的字符
* @param str
* @return
* @throws Exception
*/
private String getInfoBetweenBrackets(String str) throws Exception {
int i, j; // 用于标识字符串中的"<"和">"的位置
if (str == null ) {
str = " error " ;
return str;
}
i = str.lastIndexOf( " < " );
j = str.lastIndexOf( " > " );
if (i != - 1 && j != - 1 ){
str = str.substring(i + 1 , j);
}
return str;
}
public static void main(String[] args) throws Exception {
MailReceiverInfo receiverInfo = new MailReceiverInfo();
receiverInfo.setMailServerHost( " pop.163.com " );
receiverInfo.setMailServerPort( " 110 " );
receiverInfo.setValidate( true );
receiverInfo.setUserName( " *** " );
receiverInfo.setPassword( " *** " );
receiverInfo.setAttachmentDir( " C:/temp/mail/ " );
receiverInfo.setEmailDir( " C:/temp/mail/ " );
MailReceiver receiver = new MailReceiver(receiverInfo);
receiver.receiveAllMail();
}
}
转自 : http://www.blogjava.net/kissyan4916/articles/279130.html
发表评论
-
[转:]jQuery焦点中国地图
2013-04-17 11:05 1670转自:http://xiaoyaosr.blog.51cto ... -
一个轻量级的网页遮罩层jQuery插件
2012-11-14 17:48 6365一个轻量级的网页遮罩层jQuery插件 分 ... -
通过Spring Mail Api发送邮件
2012-11-14 17:47 1435通过Spring Mail Api发送邮件 ... -
jquery.validate
2012-11-09 16:51 1063jquery.validate 需要JQuery ... -
Hibernate commit() 和flush() 的区别(转)
2012-09-28 09:46 2626Hibernate commit() 和flush( ... -
maven3.0.2下settings.xml配置下(转)
2012-09-25 19:14 5928maven3.0.2下settings.xml配置下 ... -
hibernate中Qurey类的setDate方法自动截掉时分秒——setDate和setTimeStamp(转)
2012-09-03 10:30 3062原帖地址:http://www.iteye.com/to ... -
Maven3.0.3的环境变量配置
2012-07-19 11:22 3019转自http://hi.baidu.com/douxinchu ... -
转:org.apache.catalina.core.JreMemoryLeakPreventionListener解决办法
2012-07-18 15:38 5515转自:http://blog.csdn.net/ang ... -
eclipse中的java文件图标j成空心
2012-07-06 10:06 13532eclipse中的java文件图标j成空心 ... -
jQuery - Ajax - readyState获取请求操作的当前状态
2012-06-29 14:46 0jQuery - Ajax - readyState获取请求 ... -
Dom加载判断,兼容所有浏览器
2012-06-29 14:35 9177Dom加载判断,兼容所有浏览器 Dom 加载完毕,兼容 ... -
document.readyState几种状态及示例
2012-06-29 14:33 1968document.readySta ... -
DOM Ready 详解
2012-06-29 14:03 3081转自:http://www.cnblogs.com/zhang ... -
转】js实现另存为的方法
2012-06-29 13:42 2911转】js实现另存为的方法 本文转自http://www ... -
js添加和去除千分号
2012-06-22 11:41 2117利用js的replace方法和正则表达式实现 1 ... -
Hibernate的游离态与持久态转换(转)
2012-06-18 10:30 5203本文转自:http://blog.csdn.net/sdban ... -
maven继承parent,relativePath warn信息的解决办法
2012-06-11 17:12 25979转自:http://blog.sina.com.cn/s/bl ... -
使用Maven管理Eclipse Java项目
2012-06-11 17:10 1065转自:http://www.blogjava.net/lost ... -
The parent project must have a packaging type of POM
2012-06-11 17:09 25249The parent project must ha ...
相关推荐
NULL 博文链接:https://zhaoshijie.iteye.com/blog/804788
总之,这个“java-mail 支持smtp pop3源码”压缩包是学习和实践Java邮件处理的一个宝贵资源,涵盖了从发送邮件到接收邮件的基本流程,以及SMTP和POP3协议的实现细节。通过学习和分析这些源代码,开发者能够提升处理...
4. **POP3接收邮件**:在POP3中,客户端首先会发送一个CAPA命令来查询服务器支持的特性,然后使用USER和PASS命令进行身份验证。接着,可以使用LIST命令查看邮件数量和大小, RETR命令下载邮件,或者DELE命令标记邮件...
这个应用可能使用了JavaMail API来实现POP3邮件接收功能,并且具备一个可视化窗口,让用户能够直观地查看和管理邮件。可视化界面设计通常会涉及到Swing或JavaFX这样的GUI库,用于创建按钮、文本框、列表视图等组件,...
它提供了全面的API,支持SMTP、POP3和IMAP等邮件协议,使得开发者能够方便地实现邮件的发送、接收以及管理。在这个“javamail包--自己用的”项目中,我们可以深入探讨JavaMail的核心概念和使用方法。 首先,要使用...
在接收邮件方面,JavaMail 提供了 `Store` 和 `Folder` 接口,用于连接邮件服务器并管理邮箱中的邮件。`Folder` 类可以打开、关闭和列举邮箱中的邮件,而 `Message` 对象可以通过 `Folder.getMessages()` 获取。`...
2. **Demo 应用**:可能包含演示如何使用 JavaMail API 的示例代码,这些示例可以帮助开发者快速理解和学习如何使用 JavaMail 发送和接收邮件。 3. **文档**:如 `API 文档`(通常为 HTML 或 PDF 格式)提供了详细类...
1. **连接邮件服务器**:JavaMail支持多种协议,如SMTP(简单邮件传输协议)、POP3(邮局协议)和IMAP(因特网消息访问协议),使得程序可以发送和接收邮件。 2. **创建和管理邮件**:开发者可以通过JavaMail创建...
JavaMail 是一个开源的 Java API,它为 Java 程序员提供了处理电子邮件的功能,包括发送、接收邮件以及访问邮件服务器。在JavaMail 1.4.7 版本中,我们可以找到对邮件协议(如 SMTP、POP3 和 IMAP)的全面支持,以及...
5. 如需接收邮件,使用 `Store` 连接邮件服务器,打开 `Folder` 并读取邮件。 在实际应用中,JavaMail 还可以与其他库结合使用,如 Apache Commons Net 提供了更底层的 SMTP 支持,或者使用 JSF、Spring 等框架集成...
这个示例展示了如何使用 JavaMail API 从服务器接收邮件。首先,通过 `Session` 类设置邮件服务器的连接参数,然后创建 `Store` 对象并连接到邮箱。接着,使用 `Folder` 类打开收件箱,最后遍历 `Folder` 中的 `...
SMTP服务器之间通过TCP/IP连接交换邮件,发送方的SMTP客户端将邮件文本发送到SMTP服务器,服务器再将其转发到接收方的SMTP服务器,最终由接收方的邮件客户端通过POP3或其他协议下载邮件。SMTP协议支持身份验证和加密...
JavaMail则是用于处理电子邮件的Java API,提供了丰富的功能,可以方便地进行邮件发送、接收及管理。本文将详细介绍这两个工具的结合——ant-javamail-1.6.jar.zip,以及如何在实际开发中运用它们。 首先,让我们...
2. **POP3(Post Office Protocol v3)和IMAP(Internet Message Access Protocol)支持**:除了发送邮件,JavaMail 还能处理接收邮件,支持POP3和IMAP这两种常见的邮件收取协议。 3. **多部分和MIME(Multipurpose...
对于接收邮件,可以通过Folder和Message对象进行操作。 总之,JavaMail库为Java开发者提供了强大的邮件处理能力,而`javamail-1.6`是这个库的一个稳定版本,具有丰富的功能和改进,是开发邮件应用的理想选择。
我们可以使用 Transport 对象来发送邮件, Transport 对象是 JavaMail 库中的一个核心对象,用于发送和接收电子邮件。我们可以使用 Transport 对象的 send 方法来发送邮件。 在发送邮件之前,我们需要设置邮件...
这个库支持多种邮件协议,如 SMTP(简单邮件传输协议)用于发送邮件,POP3(邮局协议)和 IMAP(因特网消息访问协议)用于接收邮件。在这个资源中,我们将探讨如何使用 JavaMail 实现邮件的发送、接收、查看邮件数量...
2. **POP3 和 IMAP 协议支持**:除了发送邮件,JavaMail 还支持 POP3(邮局协议)和 IMAP(因特网消息访问协议)用于接收邮件。用户可以使用 `Store` 对象连接邮件服务器,并通过 `Folder` 对象来管理收件箱,获取和...
4. **JavaMail API 实现POP3接收**: - 首先,需要导入JavaMail相关的库,如`javax.mail`和`javax.mail.internet`。 - 创建`Properties`对象并设置所需的邮件服务器属性,如`pop3.host`和`pop3.port`。 - 使用`...