javamail 收发邮件

来源:互联网 发布:什么软件适合iphonex 编辑:程序博客网 时间:2024/05/29 09:08

1、发送邮件类

package com.nfa.yy_receive;
import javax.mail.*;
public class MyAuthenticator extends Authenticator{
String userName=null;
String password=null;

public MyAuthenticator(){
}
public MyAuthenticator(String username, String password) {
this.userName = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
}

package com.nfa.yy_receive;

import java.util.Properties;

public class MailSenderInfo {
// 发送邮件的服务器的IP和端口
private String mailServerHost;
private String mailServerPort = "25";
// 邮件发送者的地址
private String fromAddress;
// 邮件接收者的地址
private String[] toAddress;
// 登陆邮件发送服务器的用户名和密码
private String userName;
private String password;
// 是否需要身份验证
private boolean validate = false;
// 邮件主题
private String subject;
// 邮件的文本内容
private String content;
// 邮件附件的文件名
private String[] attachFileNames;

public Properties getProperties(){
Properties p = new Properties();
p.put("mail.smtp.host", this.mailServerHost);
p.put("mail.smtp.port", this.mailServerPort);
p.put("mail.smtp.auth", validate ? "true" : "false");
return p;
}
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 boolean isValidate() {
return validate;
}
public void setValidate(boolean validate) {
this.validate = validate;
}
public String[] getAttachFileNames() {
return attachFileNames;
}
public void setAttachFileNames(String[] fileNames) {
this.attachFileNames = fileNames;
}
public String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
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 String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String textContent) {
this.content = textContent;
}
public String[] getToAddress() {
return toAddress;
}
public void setToAddress(String[] toAddress) {
this.toAddress = toAddress;
}
}


package com.nfa.yy_receive;

import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.nfa.yy_send.MailSenderInfo;


public class SimpleMailSender {

public boolean sendTextMail(MailSenderInfo mailInfo) {
// 判断是否需要身份认证
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
if (mailInfo.isValidate()) {
// 如果需要身份认证,则创建一个密码验证器
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
try {
// 根据session创建一个邮件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 创建邮件发送者地址
Address from = new InternetAddress(mailInfo.getFromAddress());
// 设置邮件消息的发送者
mailMessage.setFrom(from);
// 创建邮件的接收者地址,并设置到邮件消息中
// Address to = new InternetAddress(mailInfo.getToAddress());
//mailMessage.setRecipient(Message.RecipientType.TO,to);
//创建邮件的接收地址(数组)
String[] to=mailInfo.getToAddress();
InternetAddress[] sendTo = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++)
{
System.out.println("发送到:" + to[i]);
sendTo[i] = new InternetAddress(to[i]);
}
mailMessage.setRecipients(javax.mail.internet.MimeMessage.RecipientType.TO, sendTo);
// 设置邮件消息的主题
mailMessage.setSubject(mailInfo.getSubject());
// 设置邮件消息发送的时间
mailMessage.setSentDate(new Date());
// 设置邮件消息的主要内容
String mailContent = mailInfo.getContent();
mailMessage.setText(mailContent);
// 发送邮件
Transport.send(mailMessage);
return true;
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}


public static boolean sendHtmlMail(MailSenderInfo mailInfo){
// 判断是否需要身份认证
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
//如果需要身份认证,则创建一个密码验证器
if (mailInfo.isValidate()) {
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
try {
// 根据session创建一个邮件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 创建邮件发送者地址
Address from = new InternetAddress(mailInfo.getFromAddress());
// 设置邮件消息的发送者
mailMessage.setFrom(from);

//创建邮件的接收地址(数组)
String[] to=mailInfo.getToAddress();
InternetAddress[] sendTo = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++)
{
System.out.println("发送到:" + to[i]);
sendTo[i] = new InternetAddress(to[i]);
}
mailMessage.setRecipients(javax.mail.internet.MimeMessage.RecipientType.TO, sendTo);
// 设置邮件消息的主题
mailMessage.setSubject(mailInfo.getSubject());
// 设置邮件消息发送的时间
mailMessage.setSentDate(new Date());
// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = new MimeMultipart();
// 创建一个包含HTML内容的MimeBodyPart
BodyPart html = new MimeBodyPart();
// 设置HTML内容 建立第一部分: 文本正文
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
// 将MiniMultipart对象设置为邮件内容 建立第二部分:附件
mailMessage.setContent(mainPart);
if(mailInfo.getAttachFileNames().length>0){
for(int i=0;i<mailInfo.getAttachFileNames().length;i++){
if (!mailInfo.getAttachFileNames()[i].equals("")) {
// 建立第二部分:附件
html = new MimeBodyPart();
// 获得附件
DataSource source = new FileDataSource(mailInfo.getAttachFileNames()[i]);
//设置附件的数据处理器
html.setDataHandler(new DataHandler(source));
// 设置附件文件名
html.setFileName(mailInfo.getAttachFileNames()[i]);
// 加入第二部分
mainPart.addBodyPart(html);
}
}
}
// 发送邮件
Transport.send(mailMessage);
return true;
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}
}

2、接收邮件类

package com.nfa.yy_receive;

public class MailReceiveBean {
private String mailFromPerson;//发件人

private String mailFrom;//发件人地址

private String mailTOAdder;//邮件收件人

private String mailCCAdder;//邮件抄送人

private String mailBCCAdder;//邮件密送人

private String mailSubject;//主题

private String sentDate;//发送日期

private String bodyText;//邮件正文

private Integer replySign;//回执 1、要求回执 2、不用回执

private Integer urgent;//优先级 1、紧急 3、普通 5、缓慢

private String messageId;//邮件id

private String mailUid;//uid

private Integer isRead;// 1 已读 2未读

private String attachMent;//附件




public String getMailFromPerson() {
return mailFromPerson;
}

public void setMailFromPerson(String mailFromPerson) {
this.mailFromPerson = mailFromPerson;
}

public String getMailFrom() {
return mailFrom;
}

public void setMailFrom(String mailFrom) {
this.mailFrom = mailFrom;
}

public String getMailTOAdder() {
return mailTOAdder;
}

public void setMailTOAdder(String mailTOAdder) {
this.mailTOAdder = mailTOAdder;
}

public String getMailCCAdder() {
return mailCCAdder;
}

public void setMailCCAdder(String mailCCAdder) {
this.mailCCAdder = mailCCAdder;
}

public String getMailBCCAdder() {
return mailBCCAdder;
}

public void setMailBCCAdder(String mailBCCAdder) {
this.mailBCCAdder = mailBCCAdder;
}

public String getMailSubject() {
return mailSubject;
}

public void setMailSubject(String mailSubject) {
this.mailSubject = mailSubject;
}

public String getSentDate() {
return sentDate;
}

public void setSentDate(String sentDate) {
this.sentDate = sentDate;
}

public String getBodyText() {
return bodyText;
}

public void setBodyText(String bodyText) {
this.bodyText = bodyText;
}

public Integer getReplySign() {
return replySign;
}

public void setReplySign(Integer replySign) {
this.replySign = replySign;
}

public Integer getUrgent() {
return urgent;
}

public void setUrgent(Integer urgent) {
this.urgent = urgent;
}

public String getMessageId() {
return messageId;
}

public void setMessageId(String messageId) {
this.messageId = messageId;
}

public String getMailUid() {
return mailUid;
}

public void setMailUid(String mailUid) {
this.mailUid = mailUid;
}

public Integer getIsRead() {
return isRead;
}

public void setIsRead(Integer isRead) {
this.isRead = isRead;
}

public String getAttachMent() {
return attachMent;
}

public void setAttachMent(String attachMent) {
this.attachMent = attachMent;
}

public MailReceiveBean() {
super();
// TODO Auto-generated constructor stub
}

public MailReceiveBean(String mailFromPerson, String mailFrom,
String mailTOAdder, String mailCCAdder, String mailBCCAdder,
String mailSubject, String sentDate, String bodyText,
Integer replySign, Integer urgent, String messageId,
String mailUid, Integer isRead, String attachMent) {
super();
this.mailFromPerson = mailFromPerson;
this.mailFrom = mailFrom;
this.mailTOAdder = mailTOAdder;
this.mailCCAdder = mailCCAdder;
this.mailBCCAdder = mailBCCAdder;
this.mailSubject = mailSubject;
this.sentDate = sentDate;
this.bodyText = bodyText;
this.replySign = replySign;
this.urgent = urgent;
this.messageId = messageId;
this.mailUid = mailUid;
this.isRead = isRead;
this.attachMent = attachMent;
}

public String toString() {
return "MailReceiveBean [attachMent=" + attachMent + ", bodyText="
+ bodyText + ", isRead=" + isRead + ", mailBCCAdder="
+ mailBCCAdder + ", mailCCAdder=" + mailCCAdder + ", mailFrom="
+ mailFrom + ", mailFromPerson=" + mailFromPerson
+ ", mailSubject=" + mailSubject + ", mailTOAdder="
+ mailTOAdder + ", mailUid=" + mailUid + ", messageId="
+ messageId + ", replySign=" + replySign + ", sentDate="
+ sentDate + ", urgent=" + urgent + "]";
}
}


package com.nfa.yy_receive;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
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.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import com.nfa.yy_receive.Base64;
import com.nfa.yy_receive.FileTool;
import com.nfa.yy_receive.MailReceiveBean;

public class MailParse {

private String dateformat = "yyyy-MM-dd HH:mm:ss";

private MimeMessage mimeMessage = null;

private StringBuffer bodyText = new StringBuffer();// 存放邮件正文

private StringBuffer fileresult = new StringBuffer();// 附件

private String saveFilePath = "";

public MailParse(MimeMessage mimeMessage, String saveFilePath) {
super();
this.mimeMessage = mimeMessage;
this.saveFilePath = saveFilePath;

FileTool.checkDirAndCreate(saveFilePath);
}

/**
* 解析邮件
*
* @param mimeMessage
* @return
*/
public MailReceiveBean getMailReceive() {
MailReceiveBean mb = null;
try {
mb = new MailReceiveBean();

mb.setMailFromPerson(getMailPerson());
mb.setMailFrom(getMailFrom());
mb.setMailTOAdder(getMailAddressByType(Message.RecipientType.TO));
mb.setMailCCAdder(getMailAddressByType(Message.RecipientType.CC));
mb.setMailBCCAdder(getMailAddressByType(Message.RecipientType.BCC));
mb.setMailSubject(getSubject());
mb.setSentDate(getSentDate());
mb.setBodyText(getBodyText());
mb.setReplySign(getReplySign());
mb.setMessageId(getMessageId());
mb.setIsRead(getMailIsRead());
mb.setUrgent(getXPriority());
mb.setAttachMent(getAttachMent());
} catch (Exception e) {
//log.error("解析邮件异常" + e.getMessage());
e.printStackTrace();
}

return mb;
}
/**
* 邮件优先级
*
* @return
* @throws Exception
*/
private Integer getXPriority() throws Exception {
Integer xpri = Integer.valueOf(0);
String pris[] = mimeMessage.getHeader("X-Priority");
if (pris != null && pris.length > 0) {
String tmp = pris[0];
xpri = Integer.valueOf(0);
if ("1".equals(tmp)) {
xpri = Integer.valueOf(1);
} else if ("3".equals(tmp)) {
xpri = Integer.valueOf(3);
} else if ("5".equals(tmp)) {
xpri = Integer.valueOf(5);
}else{
xpri = Integer.valueOf(0);
}
}
return xpri;
}
/**
* 是否已读(pop3 不支持flags状态,imap可以)
*
* @return
* @throws Exception
*/
private Integer getMailIsRead() throws Exception {
Integer isread = Integer.valueOf(1);
Flags flag= mimeMessage.getFlags();
flag.getSystemFlags();
return isread;
}


/**
* 获得此邮件的Message-ID
*/
private String getMessageId() throws Exception {
return mimeMessage.getMessageID();
}

/**
* 是否需要回执
* 1、2
* @return
* @throws Exception
*/
private Integer getReplySign() throws Exception {
Integer replysign = Integer.valueOf(0);
String needreply[] = mimeMessage.getHeader("Disposition-Notification-To");
if (needreply != null) {
replysign = Integer.valueOf(1);
}
return replysign;
}

/**
* 收件人名称
* @return
* @throws Exception
*/
private String getMailPerson() throws Exception{
InternetAddress[] address = (InternetAddress[]) mimeMessage.getFrom();
String personal = address[0].getPersonal();
String pname="";
if (personal != null){
String[] asd=mimeMessage.getHeader("From");
if (asd!=null) {
String tmp = asd[0];
if(tmp.indexOf("=?x-unknown?")>=0){
tmp = tmp.replaceAll("x-unknown","UTF-8"); // 将编码方式的信息由x-unkown改为UTF-8
}
if (tmp.indexOf("=?")>=0) {
pname = MimeUtility.decodeText(personal);
}else{
pname = new String(personal.getBytes("ISO-8859-1"),"UTF-8");
}

if (pname.indexOf("=?")>=0) {
pname = MimeUtility.decodeWord(pname);
}
}
}

return pname;
}

/**
* 发件人地址
*
* @param mimeMessage
* @return
* @throws Exception
*/
private String getMailFrom() throws Exception {
InternetAddress[] address = (InternetAddress[]) mimeMessage.getFrom();
String from = address[0].getAddress();
String fromaddr="";
if (from != null){
fromaddr = MimeUtility.decodeText(from);
}
return fromaddr;
}

/**
* 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同 "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址
*/
private String getMailAddressByType(RecipientType type) throws Exception {
String mailaddr = "";
InternetAddress[] address = null;
address = (InternetAddress[]) mimeMessage.getRecipients(type);
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;
}
if (mailaddr.length()>0) {
mailaddr = mailaddr.substring(1);
}
}
return mailaddr;
}

/**
* 获得邮件主题
*/
private String getSubject() throws Exception {
String subject = mimeMessage.getSubject();
String tmp="";
if (subject != null) {
String[] asd=mimeMessage.getHeader("Subject");
if (asd!=null) {
String sub = asd[0];
if(sub.indexOf("=?x-unknown?")>=0){
sub = sub.replaceAll("x-unknown","UTF-8"); // 将编码方式的信息由x-unkown改为UTF-8
}
if (sub.indexOf("=?")>=0) {
tmp = MimeUtility.decodeText(subject);
}else{
tmp = new String(subject.getBytes("ISO-8859-1"),"UTF-8");
}

if (tmp.indexOf("=?")>=0) {
tmp = MimeUtility.decodeWord(tmp);
}
}
}
return tmp;
}

/**
* 获得邮件发送日期
*/
private String getSentDate() throws Exception {
Date sentdate = mimeMessage.getSentDate();
if (sentdate==null) {
sentdate = new Date();
}
SimpleDateFormat format = new SimpleDateFormat(dateformat);
return format.format(sentdate);
}

/**
* 获得邮件正文内容
*/
private String getBodyText() throws Exception {
getMailContent((Part) mimeMessage);
return bodyText.toString();
}

/**
* 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中,解析邮件 主要是根据MimeType类型的不同执行不同的操作,一步一步的解析
*/
private void getMailContent(Part part) throws Exception {
String contenttype = part.getContentType();
int nameindex = contenttype.indexOf("name");
String txt="";
boolean conname = false;
if (nameindex != -1)
conname = true;
if (part.isMimeType("text/plain") && !conname) {
txt = part.getContent().toString();
} else if (part.isMimeType("text/html") && !conname) {
txt = part.getContent().toString();
} else if (part.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) part.getContent();
int counts = multipart.getCount();
for (int i = 0; i < counts; i++) {
getMailContent(multipart.getBodyPart(i));
}
} else if (part.isMimeType("message/rfc822")) {
getMailContent((Part) part.getContent());
}

if (txt.indexOf("=?")>=0) {
txt = MimeUtility.decodeText(txt);
if (txt.indexOf("=?")>=0) {
txt = MimeUtility.decodeWord(txt);
}
}
bodyText.append(txt);
}

/**
* 判断此邮件是否包含附件
*/
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 mpart = mp.getBodyPart(i);
String disposition = mpart.getDisposition();
if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE))))
attachflag = true;
else if (mpart.isMimeType("multipart/*")) {
attachflag = isContainAttach((Part) mpart);
} else {
String contype = mpart.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 saveAttachMent(Part part){
String fileName = "";
try {
if (part.isMimeType("multipart/*")) {
Multipart mp = (Multipart) part.getContent();
for (int i = 0; i < mp.getCount(); i++) {
BodyPart mpart = mp.getBodyPart(i);
String disposition = mpart.getDisposition();
if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE)))) {
fileName = mpart.getFileName();
if(fileName.contains("\\"))
{
fileName = fileName.substring(fileName.lastIndexOf("\\")+1);

}
if(fileName.split("").length>=2)
{
fileName.substring(fileName.lastIndexOf("/")+1);
}
if(fileName != null){
if (fileName.indexOf("=?")>=0) {
fileName = MimeUtility.decodeText(fileName);
}else{
fileName = new String(fileName.getBytes("ISO-8859-1"),"GB2312");
if(fileName.contains("\\"))
{
fileName.substring(fileName.lastIndexOf("\\"),fileName.length());
}
}
saveFile(fileName, mpart.getInputStream());
}
} else if (mpart.isMimeType("multipart/*")) {
saveAttachMent(mpart);
} else {
fileName = mpart.getFileName();
if (fileName != null){
if(fileName.indexOf("=?")>=0) {
fileName = MimeUtility.decodeText(fileName);
}else{
fileName = new String(fileName.getBytes("ISO-8859-1"),"GB2312");

}
saveFile(fileName, mpart.getInputStream());
}
}
}
} else if (part.isMimeType("message/rfc822")) {
saveAttachMent((Part) part.getContent());
}
} catch (Exception e) {
e.printStackTrace();
}
}

// 返回一个当前时间的字符串表示
private String getDateStr() {
String pattern = "yyyyMMddHHmmssSSS";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String dateStr = sdf.format(new java.util.Date());

return dateStr;
}


// 分离完整文件名的文件名和后缀,并在中间加入字符串后返回
private String addInNameExt(String fullName, String add) {
String name = "";// 文件名
String ext = ""; // 后缀
char point = '.';
int index = fullName.lastIndexOf(point);

if (index != -1) {// 如果有后缀
name = fullName.substring(0, index);
ext = fullName.substring(index + 1);
} else {
name = fullName;
}

return name.trim() + "_" + add + point + ext;
}

/**
* 【真正的保存附件到指定目录里】
*/
private void saveFile(String fileName, InputStream in) throws Exception {
if (fileName.indexOf("=?")>=0) {
fileName = MimeUtility.decodeWord(fileName);
}

String newfile = addInNameExt(fileName.replaceAll(",", ""), getDateStr());//文件重命名存放

String fullPath = saveFilePath + newfile;

File storefile = new File(fullPath);
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(storefile));
bis = new BufferedInputStream(in);
int c;
while ((c = bis.read()) != -1) {
bos.write(c);
bos.flush();
}
fileresult.append(fileName+"|"+Base64.getBase64FromString(fullPath)+",");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(bos!=null){
bos.close();
}
if(bis!=null){
bis.close();
}
}
}
/**
* 邮件附件
* @return
* @throws Exception
*/
private String getAttachMent() throws Exception{
saveAttachMent((Part)mimeMessage);
String tmp = fileresult.toString();
if (tmp.length()>0) {
if (tmp.charAt(tmp.length() - 1) == ',') {
tmp = tmp.substring(0, tmp.length() - 1);
}
}
return tmp;
}
}


package com.nfa.yy_receive;
import java.io.File;
public class FileTool {
/**
* 创建目录
* @param dir
*/
public static boolean checkDirAndCreate(String dir) {
boolean bl = false;
File file = new File(dir);
if (!file.exists()){
file.mkdirs();
bl = true;
}
return bl;
}

}

package com.nfa.yy_receive;

public class Base64Encode {
private static char[] codec_table = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };

public Base64Encode() {

}

public String encode(byte[] a) {
int totalBits = a.length * 8;
int nn = totalBits % 6;
int curPos = 0;// process bits
StringBuffer toReturn = new StringBuffer();
while (curPos < totalBits) {
int bytePos = curPos / 8;
switch (curPos % 8) {
case 0:
toReturn.append(codec_table[(a[bytePos] & 0xfc) >> 2]);
break;
case 2:

toReturn.append(codec_table[(a[bytePos] & 0x3f)]);
break;
case 4:
if (bytePos == a.length - 1) {
toReturn.append(codec_table[((a[bytePos] & 0x0f) << 2) & 0x3f]);
} else {
int pos = (((a[bytePos] & 0x0f) << 2) | ((a[bytePos + 1] & 0xc0) >> 6)) & 0x3f;
toReturn.append(codec_table[pos]);
}
break;
case 6:
if (bytePos == a.length - 1) {
toReturn.append(codec_table[((a[bytePos] & 0x03) << 4) & 0x3f]);
} else {
int pos = (((a[bytePos] & 0x03) << 4) | ((a[bytePos + 1] & 0xf0) >> 4)) & 0x3f;
toReturn.append(codec_table[pos]);
}
break;
default:
// never hanppen
break;
}
curPos += 6;
}
if (nn == 2) {
toReturn.append("==");
} else if (nn == 4) {
toReturn.append("=");
}
return toReturn.toString();

}

}


/**
* @author
* @version 1.0
*
* Copyright
*/
package com.nfa.yy_receive;

import sun.misc.BASE64Decoder;

public class Base64 {

/*
public static String getBase64FromString(String s) {
if (s == null) {
return null;
}
String tmp = (new sun.misc.BASE64Encoder()).encode(s.getBytes());
tmp = tmp.replaceAll("\\+", "@1").replaceAll("\\-", "@2").replaceAll("\\=", "@3");

return tmp;
}*/

/**
* Base64将字符串进行加密
*/
public static String getBase64FromString(String s) {
if (s == null) {
return null;
}
String tmp = (new Base64Encode()).encode(s.getBytes());
tmp = tmp.replaceAll("\\+", "@1").replaceAll("\\-", "@2").replaceAll("\\=", "@3");

return tmp;
}

/**
* Base64对字符串进行解密
* @param s
* @return
*/
public static String getStringFromBase64(String s) {
if (s == null) {
return null;
}
s = s.replaceAll("@1", "\\+").replaceAll("@2", "\\-").replaceAll("@3", "\\=");
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] b = decoder.decodeBuffer(s);
String tmp = new String(b);
return tmp;
} catch (Exception e) {
return null;
}
}

public static void main(String[] args) {
long t1 = System.currentTimeMillis();
String code = Base64.getBase64FromString("一起来dota");
System.out.println(code);
String p = Base64.getStringFromBase64(code);
System.out.println(p);
}
}


package com.nfa.yy_receive;

import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

import com.nfa.yy_send.MailSenderInfo;

public class MainTest {
public static void main(String[] args) throws Exception{

sendMail();
Thread.sleep(3000);
recevieMail();

}

public static void sendMail(){
//这个类主要是设置邮件
MailSenderInfo mailInfo = new MailSenderInfo();
mailInfo.setMailServerHost("smtp.qq.com"); //smtp服务
mailInfo.setMailServerPort("25"); //服务端口
mailInfo.setValidate(true); //是否需要验证
mailInfo.setUserName("
11111111@qq.com"); //用户名(和邮箱名一致)
mailInfo.setPassword("*");//您的邮箱密码
mailInfo.setFromAddress("
111111111@qq.com");//发送地址(和邮箱一致)
mailInfo.setToAddress(new String[]{"
000000000@qq.com","NFA_YY@163.COM"});//接收地址(接受者邮箱地址)
mailInfo.setRecipientCC(new String[]{"
000000000@qq.com","NFA_YY@163.COM"});//抄送人
mailInfo.setRecipientBBC(new String[]{"
000000000@qq.com","NFA_YY@163.COM"});//密送人
mailInfo.setAttachFileNames(new String[]{"F:\\mail\\3695.jpg"});//附件
mailInfo.setSubject("邮件主题"); //邮件主题
mailInfo.setContent("dsfdf");//邮件正文

SimpleMailSender sms = new SimpleMailSender();
//sms.sendTextMail(mailInfo);//发送文体格式
sms.sendHtmlMail(mailInfo);//发送html格式
}

public static void recevieMail() throws Exception{
String host="pop3.163.com";//QQ:imap.qq.com,网易:pop3.163.com
String username="NFA_YY@163.COM";//NFA_YY@163.COM
String password="*********";//邮箱密码
Properties props=new Properties();
Session session=Session.getDefaultInstance(props,new MyAuthenticator(username,password));
Store store=session.getStore("pop3");
store.connect(host,username,password);
Folder folder=store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
Message message[]=folder.getMessages();
MailParse mp = null;
for (int i = 0; i < message.length; i++)
{
mp = new MailParse((MimeMessage)message[i], "f:\\mail\\");
MailReceiveBean bean = mp.getMailReceive();
if(bean!=null)
{
System.out.println("发送人:"+bean.getMailFrom());
System.out.println("接收人:"+bean.getMailTOAdder());
System.out.println("主题:"+bean.getMailSubject());
System.out.println("邮件密送人:"+bean.getMailBCCAdder());
System.out.println("抄送人:"+bean.getMailCCAdder());
System.out.println("邮件ID"+bean.getMessageId());
System.out.println("正文:"+bean.getBodyText());
System.out.println("附件:"+bean.getAttachMent());
System.out.println("已读:"+bean.getIsRead());
System.out.println("回执:"+bean.getReplySign());
System.out.println("优先级:"+bean.getUrgent());
System.out.println("邮件只读:"+bean.getIsRead());
System.out.println("发送日期:"+bean.getSentDate());
}
}
folder.close(false);
store.close();
}
}

3、jar

mail.jar