...
package com.e6soft;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
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.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.search.BodyTerm;
import javax.mail.search.SearchTerm;
import javax.mail.Address;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import org.quartz.impl.jdbcjobstore.DBSemaphore;
import com.e6soft.base.service.JService;
import com.sun.mail.imap.IMAPMessage;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;
public class MainTest extends JService{
static String HOST = "smtp.163.com"; // smtp伺服器
static String FROM = "****@163.com"; // 發件人位址
//static String TO = "******@qq.com"; // 收件人位址
//static String AFFIX = "E:\\安裝手冊-6.3.5.doc"; // 附件位址
//static String AFFIXNAME = "安裝手冊-6.3.5.doc"; // 附件名稱
static String USER = "******"; // 使用者名
static String PWD = "**********"; // 163的授權碼
//static String SUBJECT = "您願望單中的 2 件物品正在促銷!"; // 郵件标題
//static String[] TOS = TO.split(",");
public static void main(String[] args) {
MainTest mainTest=new MainTest();
//mainTest.send("[email protected]","Your registration is complete!","注冊驗證您好 [email protected]!歡迎注冊碼雲,請将驗證碼填寫到注冊頁面。驗證碼:******","");
//(以上是) 發送的郵箱,标題,内容,
//mainTest.send("請盡快配合申請工作");
mainTest.getEmailList();
}
/* 發件人 -> MUA -> MTA -> MTA -> 若幹個MTA -> MDA <- MUA <- 收件人
本質上就是:
編寫MUA把郵件發到MTA;
編寫MUA從MDA上收郵件。
發郵件時,MUA和MTA使用的協定就是SMTP:Simple Mail Transfer Protocol,後面的MTA到另一個MTA也是用SMTP協定。
收郵件時,MUA和MDA使用的協定有兩種:POP:Post Office Protocol
在MyEclipse中,會自動給web項目導入javax.mail包中的類,但是不全(其實是隻有接口,而沒有接口的實作類),是以隻靠MyEclipse中的類是不能運作java mail項目的,但是如果這時你再去自行導入mail.jar時,就會出現沖突。
java mail中主要類:javax.mail.Session、javax.mail.internet.MimeMessage、javax.mail.Transport。
Session:表示會話,即用戶端與郵件伺服器之間的會話!想獲得會話需要給出賬戶和密碼,當然還要給出伺服器名稱。在郵件服務中的Session對象,就相當于連接配接資料庫時的Connection對象。
MimeMessage:表示郵件類,它是Message的子類。它包含郵件的主題(标題)、内容,收件人位址、發件人位址,還可以設定抄送和暗送,甚至還可以設定附件。
Transport:用來發送郵件。它是發送器!
*/
/* 以下是參考 // 接收
public static void s() throws IOException{
System.out.print("請輸入使用者名:");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String userName = in.readLine();
System.out.print("請輸入密碼:");
String password = in.readLine();
BASE64Encoder encoder = new BASE64Encoder();
System.out.println("編碼後的使用者名為:" + encoder.encode(userName.getBytes()));
System.out.println("編碼後的密碼為:" + encoder.encode(password.getBytes()));
BASE64Decoder decoder = new BASE64Decoder();
//郵件主題的Base64編碼
String emailSubject = "=?GBK?B?08q8/rLiytQ=?=";
//郵件文本内容的Base64編碼
String emailPlainContent = "vPK1pbXE08q8/reiy82y4srUo6E=";
//帶html标簽和郵件内容的Base64編碼
String emailHtmlContent = "PFA+vPK1pbXE08q8/reiy82y4srUo6E8L1A+";
//将使用Base64編碼過後的文本内容再使用Base64來解碼
emailSubject = new String(decoder.decodeBuffer(emailSubject),"GBK");
emailPlainContent = new String(decoder.decodeBuffer(emailPlainContent),"GBK");
emailHtmlContent = new String(decoder.decodeBuffer(emailHtmlContent),"GBK");
System.out.println("郵件标題:"+emailSubject);
System.out.println("郵件内容:"+emailPlainContent);
System.out.println("帶html标簽的郵件内容:"+emailHtmlContent);
}
// 接收
public static void ss() throws Exception{
//收件人位址
String recipientAddress = "[email protected]";
//收件人賬戶名
String recipientAccount = "xxx";
//收件人賬戶密碼
String recipientPassword = "xxx";
//1、連接配接郵件伺服器的參數配置
Properties props = new Properties();
//設定傳輸協定
props.setProperty("mail.store.protocol", "pop3");
//設定收件人的POP3伺服器
props.setProperty("mail.pop3.host", "pop3.163.com");
//2、建立定義整個應用程式所需的環境資訊的 Session 對象
Session session = Session.getInstance(props);
//設定調試資訊在控制台列印出來
//session.setDebug(true);
Store store = session.getStore("pop3");
//連接配接收件人POP3伺服器
store.connect("pop3.163.com", recipientAccount, recipientPassword);
//獲得使用者的郵件賬戶,注意通過pop3協定擷取某個郵件夾的名稱隻能為inbox
Folder folder = store.getFolder("inbox");
//設定對郵件賬戶的通路權限
folder.open(Folder.READ_WRITE);
//得到郵件賬戶的所有郵件資訊
Message [] messages = folder.getMessages();
for(int i = 0 ; i < messages.length ; i++){
//獲得郵件主題
String subject = messages[i].getSubject();
//獲得郵件發件人
Address[] from = messages[i].getFrom();
//擷取郵件内容(包含郵件内容的html代碼)
String content = (String) messages[i].getContent();
}
//關閉郵件夾對象
folder.close(false);
//關閉連接配接對象
store.close();
}
*/
/**
* 發送郵件
* sjrdz 收件人位址
* bt 标題
* context 内容
* @param host
* @param user
* @param pwd
*/
public static void send(String sjrdz,String bt,String context,String fjId) {
MainTest MainTest=new MainTest();
String []TOS=sjrdz.split(",");
Properties props = new Properties(); // Session 對象利用了java.util.Properties對象獲得了郵件伺服器、使用者名、密碼資訊 和整個應用程式都要使用到的 共享資訊
props.put("mail.smtp.host", HOST);//設定發送郵件的郵件伺服器的屬性(這裡使用網易的smtp伺服器)
props.put("mail.smtp.auth", "true"); //需要經過授權,也就是有戶名和密碼的校驗,這樣才能通過驗證(一定要有這一條)
Session session = Session.getDefaultInstance(props);//用props對象建構一個session
session.setDebug(true);
MimeMessage message = new MimeMessage(session);//用session為參數定義消息對象
try {
message.setFrom(new InternetAddress(FROM));// 加載發件人位址
InternetAddress[] sendTo = new InternetAddress[TOS.length]; // 加載收件人位址
for (int i = 0; i < TOS.length; i++) {
sendTo[i] = new InternetAddress(TOS[i]);
}
message.addRecipients(Message.RecipientType.TO,sendTo);
message.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(FROM));//設定在發送給收信人之前給自己(發送方)抄送一份,不然會被當成垃圾郵件,報554錯
message.setSubject(bt);//加載标題
Multipart multipart = new MimeMultipart();//向multipart對象中添加郵件的各個部分内容,包括文本内容和附件
BodyPart contentPart = new MimeBodyPart();//設定郵件的文本内容
contentPart.setText(context);
multipart.addBodyPart(contentPart);
if(!fjId.isEmpty()){//添加附件
String sqlString="select t.file_extend,t.file_info_id,t.file_filename,t.file_url from T_P_FILE_INFO t where t.file_index=\'"+fjId+"\' ";
List<Map<String, Object>> list=MainTest.dBSelect(sqlString);
for(int i=0;i<list.size();i++){
BodyPart messageBodyPart = new MimeBodyPart();
String AFFIX=System.getProperty("catalina.home")+"/webapps/webdav/"+list.get(i).get("file_info_id")+"."+list.get(i).get("file_extend");
String AFFIXNAME=list.get(i).get("file_filename").toString();
DataSource source = new FileDataSource(AFFIX);
messageBodyPart.setDataHandler(new DataHandler(source));//添加附件的内容
sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();//添加附件的标題
messageBodyPart.setFileName("=?GBK?B?"+ enc.encode(AFFIXNAME.getBytes()) + "?=");
multipart.addBodyPart(messageBodyPart);
}
}
message.setContent(multipart);//将multipart對象放到message中
message.saveChanges(); //儲存郵件
Transport transport = session.getTransport("smtp");//發送郵件
transport.connect(HOST, USER, PWD);//連接配接伺服器的郵箱
transport.sendMessage(message, message.getAllRecipients());//把郵件發送出去
transport.close();//關閉連接配接
} catch (Exception e) {
e.printStackTrace();
}
}
//擷取郵件清單
public void getEmailList(){
Properties props = new Properties(); //1、連接配接郵件伺服器的參數配置
props.put("mail.store.protocol", "imap"); //設定傳輸協定
props.put("mail.imap.host", "imap.163.com"); //設定收件人的POP3伺服器
//props.put("mail.imap.port", "143");
props.put("mail.imap.auth.plain.disable","true");
Session session = Session.getDefaultInstance(props); //2、建立定義整個應用程式所需的環境資訊的 Session 對象
Store store;
try {
store = session.getStore("imap"); //連接配接收件人POP3伺服器
store.connect("imap.163.com",USER, PWD);
Folder folder = store.getFolder("INBOX"); //獲得使用者的郵件賬戶,注意通過pop3協定擷取某個郵件夾的名稱隻能為inbox
folder.open(Folder.READ_WRITE); //設定對郵件賬戶的通路權限
//SearchTerm search= new BodyTerm("test");
//Message[] messages = folder.search(search); //得到郵件賬戶的所有郵件資訊
Message[] messages = folder.getMessages();
for (int i = 0 ; i < messages.length; i++){
Message msg = messages[i];
InternetAddress address = (InternetAddress) msg.getFrom()[0];
System.out.println(" [ #" + i + " ] ");
System.out.println( "Subject : " + msg.getSubject()); // 回複的标題
//Subject : 回複:Your registration is complete!
System.out.println("From : " + address.getPersonal() + "<" + address.getAddress() + ">"); // 回複人的名稱和郵箱
//From : " Follow your heart "<[email protected]>
System.out.println("ContentType : " + msg.getContentType()); //内容類型
//ContentType : multipart/alternative;
// boundary="----=_NextPart_5CA330D9_0A968A68_5C0E2915"
//Message表示一個郵件,msg.getContent()傳回一個Multipart對象。一個Multipart對象包含一個或多個BodyPart對象,來組成郵件的正文部分(包括附件)。
System.out.println("Content Detail : " + msg.getContent().toString()); // 内容細節
//Content Detail : javax.mail.internet.MimeMultipart@12bc6874
System.out.println("時間 : " + msg.getSentDate()); // 日期和時間
if(msg.isMimeType("multipart/*")){
Multipart mp = (Multipart)msg.getContent();
int bodynum = mp.getCount();
for(int j=0; j<bodynum; j++){
if(mp.getBodyPart(j).isMimeType("text/html")){
String content = (String)mp.getBodyPart(j).getContent();
System.out.print("郵件内容:"+content);
}
}
}else{
System.out.println("不支援的郵件類型!");
}
}
folder.close(false);
store.close();
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 解析綜合資料
* @param part
* @throws Exception
*/
private static void getAllMultipart(Part part) throws Exception{
String contentType = part.getContentType();
int index = contentType.indexOf("name");
boolean conName = false;
if(index!=-1){
conName=true;
}
//判斷part類型
if(part.isMimeType("text/plain") && ! conName) {
System.out.println((String) part.getContent());
}else if (part.isMimeType("text/html") && ! conName) {
System.out.println((String) part.getContent());
}else if (part.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) part.getContent();
int counts = multipart.getCount();
for (int i = 0; i < counts; i++) {
//遞歸擷取資料
getAllMultipart(multipart.getBodyPart(i));
//附件可能是截圖或上傳的(圖檔或其他資料)
if (multipart.getBodyPart(i).getDisposition() != null) {
//附件為截圖
if (multipart.getBodyPart(i).isMimeType("image/*")) {
InputStream is = multipart.getBodyPart(i)
.getInputStream();
String name = multipart.getBodyPart(i).getFileName();
String fileName;
//截圖圖檔
if(name.startsWith("=?")){
fileName = name.substring(name.lastIndexOf(".") - 1,name.lastIndexOf("?="));
}else{
//上傳圖檔
fileName = name;
}
FileOutputStream fos = new FileOutputStream("D:\\"
+ fileName);
int len = 0;
byte[] bys = new byte[1024];
while ((len = is.read(bys)) != -1) {
fos.write(bys,0,len);
}
fos.close();
} else {
//其他附件
InputStream is = multipart.getBodyPart(i)
.getInputStream();
String name = multipart.getBodyPart(i).getFileName();
FileOutputStream fos = new FileOutputStream("D:\\"
+ name);
int len = 0;
byte[] bys = new byte[1024];
while ((len = is.read(bys)) != -1) {
fos.write(bys,0,len);
}
fos.close();
}
}
}
}else if (part.isMimeType("message/rfc822")) {
getAllMultipart((Part) part.getContent());
}
}
/**
* 解析附件内容
* @param part
* @throws Exception
*/
private static void getAttachmentMultipart(Part part) throws Exception{
if(part.isMimeType("multipart/*")){
Multipart multipart = (Multipart) part.getContent();
int count = multipart.getCount();
for (int i = 0; i < count; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if(bodyPart.getDisposition()!=null){
InputStream is = bodyPart.getInputStream();
FileOutputStream fos=new FileOutputStream("路徑+檔案名");
int len=0;
byte[] bys=new byte[1024];
while((len=is.read(bys))!=-1){
fos.write(bys, 0, len);
}
fos.close();
}
}
}
}
/**
* 解析圖檔内容
* @param part
* @throws Exception
*/
private static void getPicMultipart(Part part) throws Exception{
if(part.isMimeType("multipart/*")){
Multipart multipart = (Multipart) part.getContent();
int count = multipart.getCount();
for (int i = 0; i < count; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if(bodyPart.isMimeType("image/*")){
InputStream is = bodyPart.getInputStream();
FileOutputStream fos=new FileOutputStream("路徑+檔案名");
int len=0;
byte[] bys=new byte[1024];
while((len=is.read(bys))!=-1){
fos.write(bys, 0, len);
}
fos.close();
}
}
}
}
/**
* 解析文本内容
* @param part
* @throws Exception
*/
private static void getTextMultipart(Part part) throws Exception{
if(part.isMimeType("text/html")){
String content = (String) part.getContent();
System.out.println(content);
}else if(part.isMimeType("text/plain")){
String content = (String) part.getContent();
System.out.println(content);
}
}
}