1.引入相关pom
<!--邮件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.配置文件
spring.mail.host=smtp.qq.com
spring.mail.username=邮箱地址
spring.mail.password=授权码
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
3.发送邮件类
@Component
public class SendMailUtils {
@Value("${spring.mail.username}")
private String fromEmail;
@Autowired
private JavaMailSender javaMailSender;
/**
* 发送简单纯文字邮件
* @param to
* @param subject
* @param content
* @return
*/
public boolean sendNomalMail(String to, String subject, String content) {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setTo(to);
simpleMailMessage.setFrom(fromEmail);
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(content);
try {
javaMailSender.send(simpleMailMessage);//执行发送
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 发送纯单个或多个带附件邮件
* @param to
* @param subject
* @param content
* @param filepath
* @return
*/
public boolean sendAttachmentMail(List<CityEmail> to, String subject, String content, List filepath) {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
/*helper.setTo(to);*/
helper.setSubject(subject);
helper.setText(content);
helper.setFrom(fromEmail);
//发送给多人 这里是我的实体类 可以改为对应的邮箱集合
for (CityEmail cityEmail : to){
mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(cityEmail.getEmail(), false));
}
//读取附件文件(传入文件路径)遍历文件数组,实现多个附件的添加
if(filepath.size()>0){
for (Object string : filepath) {
FileSystemResource file = new FileSystemResource(string.toString());
String fileName = file.getFilename();
helper.addAttachment(fileName, file);
}
try {
javaMailSender.send(mimeMessage);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}else {
return false;
}
} catch (MessagingException e) {
e.printStackTrace();
//捕获到创建MimeMessageHelper的异常
}
return true;
}
}
具体的功能 直接调用邮件类的方法传入参数即可