Java 发送多人邮件(非线程), 不带附件
/**
* 非线程发送邮件
*
* @param tto
* @param ttitle
* @param tcontent
* @param sourceMail
* @param smtp
* @param username
* @param password
*/
public Boolean send(String tto, String ttitle, String tcontent, String sourceMail, String smtp,
final String username, final String password,String sendUser) {
try {
Properties props = new Properties(); // 也可用Properties props =
// System.getProperties();
props.put("mail.smtp.host", smtp); // 存储发送邮件服务器的信息
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true"); // 同时通过验证
Session session = Session.getInstance(props); // 根据属性新建一个邮件会话
session.setDebug(true);
MimeMessage message = new MimeMessage(session); // 由邮件会话新建一个消息对象
// 设置邮件
InternetAddress from = new InternetAddress(sourceMail);
message.setFrom(from); // 设置发件人
/**
* 发送多人用分号隔开(";")
*/
String[] toarry = tto.split(";");
InternetAddress[] address = new InternetAddress[toarry.length];
for (int i = 0; i < toarry.length; i++) {
if (!("".equals(toarry[i].trim()))) {
address[i] = new InternetAddress(toarry[i]);
}
}
// InternetAddress to = new InternetAddress(tto);
message.setRecipients(Message.RecipientType.TO, address); // 设置收件人,并设置其接收类型为TO
message.setSubject(ttitle); // 设置主题
message.setSentDate(new Date()); // 设置发信时间
/**
* Multipart邮件
*/
Multipart mp = new MimeMultipart();
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(tcontent, "text/html;charset=utf-8");// 设置普通内容
mp.addBodyPart(mbp);
Transport transport = session.getTransport("smtp");
transport.connect(smtp, username, password); // 以smtp方式登录邮箱
transport.sendMessage(message, message.getAllRecipients()); // 发送邮件,其中第二个参数是所有
// 已设好的收件人地址
transport.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}