要先下载javax.mail.jar包
csdn免费下载地址:http://download.csdn.net/detail/tolcf/7736937,也可以去官网下载
package com.cn;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class sentEmail {
// 邮箱服务器
private static String host = "smtp.exmail.qq.com";
// 发件人的邮箱用户名
private static String usernames = "****@******";
// 发件人的邮箱密码
private static String passwords = "*******";
//邮件主题
private static String mail_subject = "此处为发送邮件的主题";
//发送邮件时显示的发件人名称
private static String personalName = "此处为发件人名称";
/**
* 群发邮件
* @param sendmessage 发送邮件的内容
* @param emails 收件人
* @return true 成功 false 失败
*/
public static boolean send(String sendmessage, String emails) {
if(emails.isEmpty()){
return true;
}
String email[] = emails.split(";");//收件人字符串,以;隔开
try {
Properties props = new Properties(); // 获取系统环境
Authenticator auth = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {// 进行邮件服务器用户认证
return new PasswordAuthentication(usernames, passwords);
}
};
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "25");
Session session = Session.getDefaultInstance(props, auth);// 设置session,和邮件服务器进行通讯。
MimeMessage message = new MimeMessage(session);
message.setSubject(mail_subject); // 设置邮件主题
message.setContent(sendmessage, "text/html;charset=gbk"); // 设置邮件格式
message.setSentDate(new Date()); // 设置邮件发送日期
Address address = new InternetAddress(usernames, personalName);
message.setFrom(address); // 设置邮件发送者的地址
int len = email.length;
//群发邮件的代码
InternetAddress toAddress[]=new InternetAddress[len];
for (int i = 0; i < email.length; i++) {
if(!email[i].isEmpty()){
toAddress[i]=new InternetAddress(email[i]);
}
}
message.addRecipients(Message.RecipientType.TO, toAddress);
//发单个邮箱的代码
/**
* InternetAddress toAddress=new InternetAddress();
toAddress=new InternetAddress("****@126.com");
message.addRecipient(Message.RecipientType.TO, toAddress);
*/
Transport.send(message); // 发送邮件
return true;
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
}