java 批量或单个发送邮件
/**
* 发件人使用发邮件的电子信箱服务器
* smtp.mxhichina.com代表是阿里的服务器
*/
private static String SMTP_HOST = "smtp.mxhichina.com";
private static String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
//发件人账号
private static String userName = "";
//发件人密码
private static String password = "";
//发件人昵称
private static String nick = "";
//发件人备注
private static String mailFrom = "";
/**
*@描述 发送邮件方法
*@参数 [environment, mailTo, content, model]
*@返回值 void
*@创建人 licf
*@创建时间 2017/11/9
*@修改人和其它信息
*/
public static void send(String mailTo, String content, String subject) {
try {
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST);
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
//鉴权验证
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, new Authenticator(){
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}});
Message msg = new MimeMessage(session);
InternetAddress fromAddress = null;
//设置自定义发件人昵称
if(null != nick && !"".equals(nick)){
try {
nick= MimeUtility.encodeText(nick);
fromAddress = new InternetAddress(nick+" <" + mailFrom + ">");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
fromAddress = new InternetAddress(mailFrom);
}
// 设置发件人地址信息
msg.setFrom(fromAddress);
// 设置收件人地址信息
String[] to = mailTo.split(",");
for(int i = 0; i < to.length;i++) {
InternetAddress toAddress = new InternetAddress(to[i]);
msg.addRecipient(Message.RecipientType.TO,toAddress);
}
//设置邮件主题
msg.setSubject(subject);
// 邮件内容
msg.setText(content);
//发送时间
msg.setSentDate(new Date());
Transport.send(msg);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
send("xxx@xxx.com","11121212111","测试单个发送邮件");
send("xxx@xxx.com,xxx@126.com,xxx@163.com","12121211","测试批量发送邮件");
}