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 = "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 blocke.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包: