概述:以前用QQ郵箱作了發郵件,但是到接收郵件時卻不行了,這個問題還沒解決,後面就用163郵箱來作就能夠html
1.到163郵箱的設置去打開SMTP和imap服務,SMTP是發送郵件,IMAP是接收郵件數據庫
2.發送郵件:服務器
public static String send(String toEmail , String _content,String subject) throws MessagingException {session
Properties props = new Properties();app
props.put("mail.smtp.host", "smtp.163.com");// 指定SMTP服務器ide
props.put("mail.smtp.auth", "true");// 指定是否須要SMTP驗證post
String from = "*****@163.com";this
String to = toEmail;//接收的Emailspa
String content = _content;//郵件內容code
String host = "smtp.163.com";
String user = "*****@163.com";
String password = "*****";
Session mailSession = Session.getDefaultInstance(props);
Message message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));// 發件人
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));// 收件人
message.setSubject(subject);// 郵件主題
message.setContent(content,"text/html;charset=utf-8");// 郵件內容
message.saveChanges();
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, user, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
return from;
}
3.接收郵件
public class ReceiveEmail {
private MimeMessage msg = null;
private String saveAttchPath = "";
private StringBuffer bodytext = new StringBuffer();
private String dateformate = "yy-MM-dd HH:mm:ss";
public ReceiveEmail(MimeMessage msg){
this.msg = msg;
}
public void setMsg(MimeMessage msg) {
this.msg = msg;
}
/**
* 獲取發送郵件者信息
* @return
* @throws MessagingException
*/
public String getFrom() throws MessagingException{
InternetAddress[] address = (InternetAddress[]) msg.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;
}
/**
* 獲取郵件收件人,抄送,密送的地址和信息。根據所傳遞的參數不一樣 "to"-->收件人,"cc"-->抄送人地址,"bcc"-->密送地址
* @param type
* @return
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public String getMailAddress(String type) throws MessagingException, UnsupportedEncodingException{
String mailaddr = "";
String addrType = type.toUpperCase();
InternetAddress[] address = null;
if(addrType.equals("TO")||addrType.equals("CC")||addrType.equals("BCC")){
if(addrType.equals("TO")){
address = (InternetAddress[]) msg.getRecipients(Message.RecipientType.TO);
}
if(addrType.equals("CC")){
address = (InternetAddress[]) msg.getRecipients(Message.RecipientType.CC);
}
if(addrType.equals("BCC")){
address = (InternetAddress[]) msg.getRecipients(Message.RecipientType.BCC);
}
if(address != null){
for(int i=0;i<address.length;i++){
String mail = address[i].getAddress();
if(mail == null){
mail = "";
}else{
mail = MimeUtility.decodeText(mail);
}
String personal = address[i].getPersonal();
if(personal == null){
personal = "";
}else{
personal = MimeUtility.decodeText(personal);
}
String compositeto = personal +"<"+mail+">";
mailaddr += ","+compositeto;
}
mailaddr = mailaddr.substring(1);
}
}else{
throw new RuntimeException("Error email Type!");
}
return mailaddr;
}
/**
* 獲取郵件主題
* @return
* @throws UnsupportedEncodingException
* @throws MessagingException
*/
public String getSubject() throws UnsupportedEncodingException, MessagingException{
String subject = "";
subject = MimeUtility.decodeText(msg.getSubject());
if(subject == null){
subject = "";
}
return subject;
}
/**
* 獲取郵件發送日期
* @return
* @throws MessagingException
*/
public Date getSendDate() throws MessagingException{
Date sendDate = msg.getSentDate();
// SimpleDateFormat smd = new SimpleDateFormat(dateformate);
return sendDate;
}
/**
* 獲取郵件正文內容
* @return
*/
public String getBodyText(){
return bodytext.toString();
}
/**
* 解析郵件,將獲得的郵件內容保存到一個stringBuffer對象中,解析郵件 主要根據MimeType的不一樣執行不一樣的操做,一步一步的解析
* @param part
* @throws MessagingException
* @throws IOException
*/
public void getMailContent(Part part) throws MessagingException, IOException{
String contentType = part.getContentType();
int nameindex = contentType.indexOf("name");
boolean conname = false;
if(nameindex != -1){
conname = true;
}
System.out.println("CONTENTTYPE:"+contentType);
if(part.isMimeType("text/plain")&&!conname){
bodytext.append((String)part.getContent());
}else if(part.isMimeType("text/html")&&!conname){
bodytext.append((String)part.getContent());
}else if(part.isMimeType("multipart/*")){
Multipart multipart = (Multipart) part.getContent();
int count = multipart.getCount();
for(int i=0;i<count;i++){
getMailContent(multipart.getBodyPart(i));
}
}else if(part.isMimeType("message/rfc822")){
getMailContent((Part) part.getContent());
}
}
/**
* 判斷郵件是否須要回執,如需回執返回true,不然返回false
* @return
* @throws MessagingException
*/
public boolean getReplySign() throws MessagingException{
boolean replySign = false;
String needreply[] = msg.getHeader("Disposition-Notification-TO");
if(needreply != null){
replySign = true;
}
return replySign;
}
/**
* 獲取此郵件的message-id
* @return
* @throws MessagingException
*/
public String getMessageId() throws MessagingException{
return msg.getMessageID();
}
/**
* 判斷此郵件是否已讀,若是未讀則返回false,已讀返回true
* @return
* @throws MessagingException
*/
public boolean isNew() throws MessagingException{
boolean isnew = false;
Flags flags = ((Message)msg).getFlags();
Flags.Flag[] flag = flags.getSystemFlags();
System.out.println("flags's length:"+flag.length);
for(int i=0;i<flag.length;i++){
if(flag[i]==Flags.Flag.SEEN){
isnew = true;
System.out.println("seen message .......");
break;
}else{
}
}
return isnew;
}
/**
* 判斷是是否包含附件
* @param part
* @return
* @throws MessagingException
* @throws IOException
*/
public boolean isContainAttch(Part part) throws MessagingException, IOException{
boolean flag = false;
String contentType = part.getContentType();
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);
String dispostion = bodypart.getDisposition();
if((dispostion != null)&&(dispostion.equals(Part.ATTACHMENT)||dispostion.equals(Part.INLINE))){
flag = true;
}else if(bodypart.isMimeType("multipart/*")){
flag = isContainAttch(bodypart);
}else{
String conType = bodypart.getContentType();
if(conType.toLowerCase().indexOf("appliaction")!=-1){
flag = true;
}
if(conType.toLowerCase().indexOf("name")!=-1){
flag = true;
}
}
}
}else if(part.isMimeType("message/rfc822")){
flag = isContainAttch((Part) part.getContent());
}
return flag;
}
/**
* 保存附件
* @param part
* @throws MessagingException
* @throws IOException
*/
public void saveAttchMent(Part part) throws MessagingException, IOException{
String filename = "";
if(part.isMimeType("multipart/*")){
Multipart mp = (Multipart) part.getContent();
for(int i=0;i<mp.getCount();i++){
BodyPart mpart = mp.getBodyPart(i);
String dispostion = mpart.getDisposition();
if((dispostion != null)&&(dispostion.equals(Part.ATTACHMENT)||dispostion.equals(Part.INLINE))){
filename = mpart.getFileName();
if(filename.toLowerCase().indexOf("gb2312")!=-1){
filename = MimeUtility.decodeText(filename);
}
saveFile(filename,mpart.getInputStream());
}else if(mpart.isMimeType("multipart/*")){
saveAttchMent(mpart);
}else{
filename = mpart.getFileName();
if(filename != null&&(filename.toLowerCase().indexOf("gb2312")!=-1)){
filename = MimeUtility.decodeText(filename);
}
saveFile(filename,mpart.getInputStream());
}
}
}else if(part.isMimeType("message/rfc822")){
saveAttchMent((Part) part.getContent());
}
}
/**
* 得到保存附件的地址
* @return
*/
public String getSaveAttchPath() {
return saveAttchPath;
}
/**
* 設置保存附件地址
* @param saveAttchPath
*/
public void setSaveAttchPath(String saveAttchPath) {
this.saveAttchPath = saveAttchPath;
}
/**
* 設置日期格式
* @param dateformate
*/
public void setDateformate(String dateformate) {
this.dateformate = dateformate;
}
/**
* 保存文件內容
* @param filename
* @param inputStream
* @throws IOException
*/
private void saveFile(String filename, InputStream inputStream) throws IOException {
String osname = System.getProperty("os.name");
String storedir = getSaveAttchPath();
String sepatror = "";
if(osname == null){
osname = "";
}
if(osname.toLowerCase().indexOf("win")!=-1){
sepatror = "//";
if(storedir==null||"".equals(storedir)){
storedir = "d://temp";
}
}else{
sepatror = "/";
storedir = "/temp";
}
File storefile = new File(storedir+sepatror+filename);
System.out.println("storefile's path:"+storefile.toString());
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(storefile));
bis = new BufferedInputStream(inputStream);
int c;
while((c= bis.read())!=-1){
bos.write(c);
bos.flush();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
bos.close();
bis.close();
}
}
//獲取單個對象
public BsmEmailInfoVO recive(Part part,int i) throws MessagingException, IOException{
BsmEmailInfoVO bsmEmailInfoVO = new BsmEmailInfoVO();
bsmEmailInfoVO.setEmailTitle(getSubject());
bsmEmailInfoVO.setSendEmail(getFrom());
bsmEmailInfoVO.setSendTime(getSendDate());
bsmEmailInfoVO.setReceiveEmail(getMailAddress("TO"));
bsmEmailInfoVO.setCopyEmail(getMailAddress("CC"));
bsmEmailInfoVO.setBccEmail(getMailAddress("BCC"));
boolean isNew = isNew();
if(isNew==true){
bsmEmailInfoVO.setReadStatus(EmailReadStatusEnum.HAVEREAD.getCode());
}else{
bsmEmailInfoVO.setReadStatus(EmailReadStatusEnum.NEWEMAIL.getCode());
}
boolean flag = isContainAttch(part);
System.out.println("Message" + i + " replySign:" + getReplySign()); //是否回執就先無論了
getMailContent(part);
bsmEmailInfoVO.setEmailContent(getBodyText());
bsmEmailInfoVO.setEmailType(EmailTypeEnum.RECEIVETYPE.getCode());
setSaveAttchPath("c://temp//" + i);
if(flag){
saveAttchMent(part);
}
return bsmEmailInfoVO;
}
//獲取郵件
public static List<BsmEmailInfoVO> receiveEmail()throws MessagingException, IOException{
List<BsmEmailInfoVO> result = new ArrayList<BsmEmailInfoVO>();
Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.163.com");//指定服務器
props.setProperty("mail.smtp.auth", "true");//指定須要驗證
Session session = Session.getDefaultInstance(props);
Store store = session.getStore("imap");
store.connect("imap.163.com", "帳號", "密碼");
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);//對於郵件可讀也可寫
Message msgs[] = folder.getMessages();
int count = msgs.length;
ReceiveEmail rm = null;
for(int i=0;i<count;i++){
rm = new ReceiveEmail((MimeMessage) msgs[i]);
BsmEmailInfoVO bsmEmailInfoVO = new BsmEmailInfoVO();
bsmEmailInfoVO = rm.recive(msgs[i],i);
//未讀的郵件才保存到數據庫
if(bsmEmailInfoVO.getReadStatus()==EmailReadStatusEnum.NEWEMAIL.getCode()){
msgs[i].setFlag(Flags.Flag.SEEN,true);//將未讀的郵件標記爲已讀
// msgs[i].saveChanges(); 這是致命的,不須要這保存
result.add(bsmEmailInfoVO);
}
}
folder.close(false);
store.close();
return result;
}
public static void main(String[] args) throws MessagingException, IOException {
Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.163.com");
props.setProperty("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
Store store = session.getStore("imap");
store.connect("imap.163.com", "***", "***");
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
Message msgs[] = folder.getMessages();
int count = msgs.length;
System.out.println("Message Count:"+count);
ReceiveEmail rm = null;
for(int i=0;i<count;i++){
rm = new ReceiveEmail((MimeMessage) msgs[i]);
rm.recive(msgs[i],i);;
}
folder.close(false);
store.close();
}
}