利用spring发送邮件
1、打开邮箱的POP3/SMTP服务,以sina邮箱为例
2、在porm.xml中加入如下依赖,修改properties
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
#MailProperties
spring.mail.host=smtp.sina.com
spring.mail.port=465
spring.mail.username=###
spring.mail.password=###
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.ssl.enable=true
3、MailClient代码
@Component
public class MailClient {
private static final Logger logger = LoggerFactory.getLogger(MailClient.class);
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
public void sendMail(String to,String subject,String content){
try {
MimeMessage message=mailSender.createMimeMessage();
MimeMessageHelper helper=new MimeMessageHelper(message);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content,true);
mailSender.send(helper.getMimeMessage());
} catch (MessagingException e) {
logger.error("发送邮件失败:"+e.getMessage());
}
}
}
4、发送邮件
private MailClient mailClient;
mailClient.sendMail("xxx@qq.com","TESTMYHERO","HIHIHIHI");
5、HTML邮件
public void testHtmlMail(){
Context context=new Context();
context.setVariable("username","sunday");
String content=templateEngine.process("/mail/demo",context);
System.out.println(content);
mailClient.sendMail("xxx@qq.com","HTMLTEST",content);
}
demo.html
<p>欢迎你,<span style="color:red" th:text="${username}"></span></p>