javamail向多人发送邮件例子代码

注意:此代码需要添加mail.jar和activation.jar两个包,这两个包可以到sun的官网下载javamail和jaf这两个文件。


package com.lccert.crm.chemistry.util;

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class SendMail {   
	
	private static SendMail instance = null;

	private SendMail() {

	}

	public static SendMail getInstance() {
		if (instance == null) {
			instance = new SendMail();
		}
		return instance;
	}
	
    public void send() {
        try {
        	String to[]={"[email protected]","[email protected]"};
           Properties p = new Properties(); //Properties p = System.getProperties();   
            p.put("mail.smtp.auth", "true");   
            p.put("mail.transport.protocol", "smtp");   
            p.put("mail.smtp.host", "smtp.163.com");   
            p.put("mail.smtp.port", "25");   
            //建立会话   
            Session session = Session.getInstance(p);   
            Message msg = new MimeMessage(session); //建立信息   
    
            msg.setFrom(new InternetAddress("[email protected]")); //发件人   
            
            String toList = getMailList(to);
            InternetAddress[] iaToList = new InternetAddress().parse(toList);
            
            msg.setRecipients(Message.RecipientType.TO,iaToList); //收件人   
    
            msg.setSentDate(new Date()); // 发送日期   
            msg.setSubject("javamail测试邮件"); // 主题   
            msg.setText("注意,这是测试程序发的,请不要回复!"); //内容   
            // 邮件服务器进行验证   
            Transport tran = session.getTransport("smtp");   
            tran.connect("smtp.163.com", "tiwson", "9041160");   
            // bluebit_cn是用户名,xiaohao是密码   
            tran.sendMessage(msg, msg.getAllRecipients()); // 发送   
            System.out.println("邮件发送成功");   
    
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
    }   
    
    private String getMailList(String[] mailArray){
        
        StringBuffer toList = new StringBuffer();
    int length = mailArray.length;
        if(mailArray!=null && length <2){
             toList.append(mailArray[0]);
        }else{
             for(int i=0;i<length;i++){
                     toList.append(mailArray[i]);
                     if(i!=(length-1)){
                         toList.append(",");
                     }

             }
         }
     return toList.toString();

}


} 

你可能感兴趣的:(sun)