package webservice;
import java.util.Properties;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
public class EmailUtils12 {
private static JavaMailSenderImpl javaMailSender;
private static String userName = "XXXXXXXX";
static {
javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost("smtp.163.com");// 链接服务器
javaMailSender.setUsername(userName);// 账号
javaMailSender.setPassword("XXXXX");// 密码
javaMailSender.setDefaultEncoding("UTF-8");
Properties properties = new Properties();
// 设置通过ssl协议使用465端口发送、使用默认端口(25)时下面三行不需要
properties.setProperty("mail.smtp.auth", "true");// 开启认证
properties.setProperty("mail.smtp.socketFactory.port", "465");// 设置ssl端口
properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
javaMailSender.setJavaMailProperties(properties);
}
public static void sendEmail(final String title, final String content, final String toMail) {
new Thread(new Runnable() {// 开启线程异步发送 防止发送请求时间过长
@Override
public void run() {
try {
if (!toMail.equals("")) {
String[] toAddress = toMail.split(",");
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");
helper.setFrom(userName);
helper.setTo(toAddress);
helper.setSubject(title);
helper.setText(content, true); // 内容
javaMailSender.send(message); // 发送邮件
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public static void main(String[] args) {
sendEmail("邮件标题", "邮件<b>内容</b><br/>------", "收件人邮箱");
}
}