使用Java Mail實現簡單的郵件發送

package com.van.common.tools.email.service;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;


public class SendMailDemo {
    
    
    public Session getSession(){
        
            Properties pros = new Properties();
        
            //資源文件郵箱服務器信息
            pros.setProperty("mail.transport.protocol", "smtp");
            pros.setProperty("mail.smtp.auth", "true");
            pros.setProperty("mail.host","smtp.qq.com");
            pros.setProperty("mail.smtp.port","25");
            
            //驗證信息
            Session session = Session.getInstance(pros,new Authenticator(){
                
                        protected PasswordAuthentication getPasswordAuthentication()
                        {
                            return new PasswordAuthentication("18365918","你的密碼");
                        }
                    });
            //打印Dbug信息
            session.setDebug(true);
            return session;
    }
    

   
    public boolean sendMail(){    
        
        
        Session session=getSession();
        boolean result = false;
        //內容編碼
        String mailtype = "text/html;charset=GBK";
        try{
           
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("[email protected]"));//發送郵箱
            
            InternetAddress[] tos = new InternetAddress[1];//收件箱
            tos[0] = new InternetAddress("[email protected]");
           
            msg.setRecipients(RecipientType.TO, tos);
            msg.setSubject("這是一個測試郵件。");
            msg.setContent("這是測試郵件的內容", mailtype);
            Transport.send(msg);
            result = true;
        } catch (Exception e){   
           e.printStackTrace();
        }
        
        return result;
    }
    
    
    public static void main(String [] args){
        
        new SendMailDemo().sendMail();
    }

}


郵件發送需要使用到Java Mail包,請自行下載,附上下載地址:http://www.oracle.com/technetwork/java/javamail/index-138643.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章