<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.1</version>
</dependency>
@Data
public class EmailVo {
private String receiveMail;
private String subject;
private String content;
}
@Configuration
public class EmailConfig {
@Value("${mail.user}")
private String mailUser;
@Value("${mail.password}")
private String mailPassword;
@Bean
public Properties props() {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.qq.com");
props.put("mail.smtp.port", "587");
props.put("mail.user", mailUser);
props.put("mail.password", mailPassword);
return props;
}
@Bean
public Authenticator authenticator(Properties props) {
return new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
}
}
@RestController
public class SendEmailController {
@Autowired
private Properties props;
@Autowired
private Authenticator authenticator;
@PostMapping("/email/send")
public R sendEmail(@RequestBody EmailTo emailTo) throws MessagingException {
Session mailSession = Session.getInstance(props, authenticator);
MimeMessage message = new MimeMessage(mailSession);
InternetAddress form = new InternetAddress(props.getProperty("mail.user"));
message.setFrom(form);
InternetAddress to = new InternetAddress(emailTo.getReceiveMail());
message.setRecipient(Message.RecipientType.TO, to);
message.setSubject(emailTo.getSubject());
message.setContent(emailTo.getContent(), "text/html;charset=UTF-8");
Transport.send(message);
return R.ok();
}
}