import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class TestEmail {
//用于加载引入模板
private static Configuration configuration =null;
public static void main(String[] args) throws Exception {
configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
//加载资源路径 及加载类
configuration.setClassForTemplateLoading(TestEmail.class,"/test");
//ftl需要的测试数据
Map map = new HashMap();
map.put("userName", "张三");
String html="";
//加载ftl
Template template = configuration.getTemplate("test.ftl");
html = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
JavaMailSenderImpl send = new JavaMailSenderImpl();
Properties prop = new Properties();
prop.setProperty("mail.transport.protocol", "smtp"); // 设置邮件发送协议
prop.setProperty("mail.host", "smtp.qq.com"); // 邮件服务器地址
prop.setProperty("mail.smtps.ssl.enable", "true"); // 邮件ssl验证
prop.setProperty("mail.smtp.auth", "true"); // 邮件服务身份验证
prop.setProperty("mail.smtp.port", "25"); // 端口
prop.setProperty("mail.debug", "true");//打印debug日志
send.setUsername("XXXXXXX@qq.com"); // 设置用户名
send.setPassword("XXXXXX"); // 设置密码
send.setJavaMailProperties(prop);
MimeMessage msg = send.createMimeMessage();
// 指定HTML编码,参数true表示为multipart
MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");
helper.setFrom("XXXXXX@qq.com"); // 发送者邮箱
helper.setTo("XXXXXXX@qq.com"); // 接收者邮箱
helper.setSubject("测试");//
helper.setText(html, true); // 邮件内容,参数true表示是html代码
send.send(msg); // 发送邮件
}
}
//需要的jar:
// compile group: 'org.freemarker', name: 'freemarker', version: '2.3.23'
// compile group: 'org.springframework.boot', name: 'spring-boot-starter-freemarker', version: '2.1.3.RELEASE'
// compile group: 'javax.mail', name: 'javax.mail-api', version: '1.5.6'