package com.boventech.learning.test;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
/**
* 邮件测试
* @author
*
*/
public class MailTest {
private static final Logger LOGGER = LoggerFactory.getLogger(MailTest.class);
private static final String HOST = "smtp.gmail.com";
private static final int PORT = 587;
private static final String USERNAME = "xxx";
private static final String PASSWORD = "xx";
/**
* @param args
*/
public static void main(String[] args) {
String to = "764503410@qq.com";
String title = "主题";
String content = "内容";
sendMail(to, title, content);
}
/**
* 发送邮件
* @param to
* @param title
* @param content
* @return
*/
public static boolean sendMail(String to,String title,String content){
final String _to = to;
final String _title = title;
final String _content = content;
new Thread(new Runnable() {
@Override
public void run() {
try {
sendHtmlMail(_to, _title, _content);
} catch (MessagingException e) {
String msg = String.format("Error when send mail", _to);
LOGGER.error(msg, e);
}
}
}).start();
return true;
}
/**
* 邮件配置
* @param to
* @param subject
* @param htmlContent
* @throws MessagingException
*/
private static void sendHtmlMail(String to, String subject, String htmlContent) throws MessagingException {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(HOST);
mailSender.setPort(PORT);
mailSender.setUsername(USERNAME);
mailSender.setPassword(PASSWORD);
Properties javaMailProperties = new Properties();
javaMailProperties.setProperty("mail.transport.protocol", "smtp");
javaMailProperties.setProperty("mail.smtp.auth", "true");
javaMailProperties.setProperty("mail.smtp.starttls.enable", "true");
javaMailProperties.setProperty("mail.debug", "false");
mailSender.setJavaMailProperties(javaMailProperties);
MimeMessage message = mailSender.createMimeMessage();
// use the true flag to indicate you need a multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setTo(to);
helper.setSubject(subject);
// use the true flag to indicate the text included is HTML
helper.setText(htmlContent, true);
mailSender.send(message);
}
}
java mail
最新推荐文章于 2023-06-24 17:57:09 发布