<!--邮件-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
</dependency>
设置一下配置
private static JavaMailSenderImpl getMailSender() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
//链接服务器
javaMailSender.setHost(ApolloConfManage.getBaseConfigString("email.serverAddress"));
//账号
javaMailSender.setUsername(getMailUserName());
//密码
javaMailSender.setPassword(ApolloConfManage.getBaseConfigString("email.password"));
javaMailSender.setDefaultEncoding("UTF-8");
Properties properties = new Properties();
//设置链接超时
properties.setProperty("mail.smtp.timeout", "1000");
//设置通过ssl协议使用465端口发送、使用默认端口(25)时下面三行不需要
//开启认证
properties.setProperty("mail.smtp.auth", "true");
//设置ssl端口
properties.setProperty("mail.smtp.socketFactory.port", "465");
properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
javaMailSender.setJavaMailProperties(properties);
return javaMailSender;
}
发复杂邮件方法(里面开启了多线程,群发的时候效率高点)
private static void send(final String title, final String body, final String[] toMail) {
final String mailUserName = getMailUserName();
final JavaMailSenderImpl javaMailSender = getMailSender();
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("send-mail-%d").build();
ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
singleThreadPool.execute(new Runnable() {
@Override
public void run() {
try {
//复杂邮件
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//邮件发送助手
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
//发送方
helper.setFrom(mailUserName);
//标题
helper.setSubject("环境:" + APPLICATION_ENV + title);
//正文
helper.setText(body, true);
//接受方
helper.setTo(toMail);
log.info("给收件人: {} 发送邮件,主题为: {}", Arrays.toString(toMail), title);
//发送邮件
javaMailSender.send(mimeMessage);
} catch (Exception e) {
log.error(e.getLocalizedMessage(), e);
}
}
});
singleThreadPool.shutdown();
}
简单邮件,上面获取邮件对象换一下
//简单邮件
SimpleMailMessage message = new SimpleMailMessage();
//邮件标题
message.setSubject("标题");
//邮件内容
message.setText("内容->邮件测试");
//发送者
message.setTo(" xxx");
//接收者
message.setFrom("xxx");
mailSender.send(message);
网友评论