前言
这篇文章主要介绍了SpringBoot实现发送邮件代码,希望帮助大家解决问题,感兴趣的朋友可以了解下
代码如下(示例):
package utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
/**
* @Description:
*/
@Component
public class MailUtils {
@Autowired
private JavaMailSenderImpl javaMailSender;
@Value("${spring.mail.username}")
private String from;
/**
* 发送文本邮件
* @param title
* @param content
* @param to
*/
public void sendTxtMail(String title,String content,String[] to) {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setTo(to);
simpleMailMessage.setFrom(from);
simpleMailMessage.setSubject(title);
simpleMailMessage.setText(content);
javaMailSender.send(simpleMailMessage);
}
/**
* 发送html邮件
* @param title
* @param content
* @param to
* @throws MessagingException
*/
public void sendHtmlMail(String title,String content,String[] to) {
try{
MimeMessage mimeMessage=javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper=new MimeMessageHelper(mimeMessage,true);
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setTo(to);
mimeMessageHelper.setSubject(title);
mimeMessageHelper.setText(content,true);
javaMailSender.send(mimeMessage);
}catch(MessagingException me){
me.printStackTrace();
}
}
}
本文详细可参考:
http://springboot.javaboy.org/2019/0717/springboot-mail
https://www.cnblogs.com/sun2020/p/13961554.html
总结
以上就是今天要讲的内容,本文仅仅简单介绍了springboot 发送邮件代码。