Demo2.java:

package com.cz.email;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
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;

import org.apache.log4j.Logger;

public class Demo2 {
	private static final String MAIL_USER = "mylearn";   //郵件服務器登錄用戶名 
    
    private static final String MAIL_PASSWORD = "mylearn";   //郵件服務器登錄密碼 
   
    private static final String MAIL_FROM_SMTP = "mylearn@sina.com";  //發送郵件地址
    
	public void sendmail(String[] mailArray,String subject,String content){
		Properties props = new Properties();
		//設置服務器驗證
		props.setProperty("mail.smtp.auth", "true");
		//設置傳輸協議
		props.setProperty("mail.transport.protocol", "smtp");
		//選擇服務類型
		props.setProperty("mail.host", "smtp.sina.com");
		//通過認證創建一個session實例
		Session session = Session.getInstance(props,
				new Authenticator()
				{
					protected PasswordAuthentication getPasswordAuthentication()
					{
						return new PasswordAuthentication(MAIL_USER,MAIL_PASSWORD);
					}
				}
		);
		//顯示郵件發送過程中的交互信息
		session.setDebug(true);
		
		Message msg = new MimeMessage(session);
		Transport transport=null;
		try {
			//郵件發送人
			msg.setFrom(new InternetAddress(MAIL_FROM_SMTP));
			//郵件主題
			msg.setSubject(subject);			
			//郵件內容
			msg.setText(content);
			int len=mailArray.length;  
		    InternetAddress address[]=new InternetAddress[len];  
			for (int i = 0; i < mailArray.length; i++) {
				address[i]=new InternetAddress(mailArray[i]); 
			}
			//郵件接收方
			msg.addRecipients(Message.RecipientType.TO, address);
			transport.send(msg);			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(transport!=null){
					transport.close();
				}				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}		
	}
	public static void main(String[] args) throws Exception{
		Demo2 demo2=new Demo2();
		String[] mailArray ={"chenzheng@163.com","chenzheng@sina.com"};
		String subject="冬天來啦!";
		String content="Hello world啊!";
		demo2.sendmail(mailArray,subject,content);
	}


}

 上傳需要的mail.jar包:

創作者介紹
創作者 shadow 的頭像
shadow

資訊園

shadow 發表在 痞客邦 留言(0) 人氣()