javamail实现邮件群发

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 = "[email protected]";  //发送邮件地址
    
	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 ={"[email protected]","[email protected]"};
		String subject="冬天来啦!";
		String content="Hello world啊!";
		demo2.sendmail(mailArray,subject,content);
	}


}

 上传需要的mail.jar包:

你可能感兴趣的:(javamail,邮件群发)