1.導入jar
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.1.6.RELEASE</version>
</dependency>
2.SpringBoot配置
spring.mail.host=smtp.qq.com
spring.mail.username=發送郵箱
spring.mail.password=cutkvuqshjgobbcj
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
3.編碼
public class MailUtil {
@Autowired
JavaMailSenderImpl mailSender;
public void sendEmail(HashMap map) throws Exception{
//建立一個複雜的消息郵件
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
helper.setSubject((String) map.get("subject"));//郵件主題
helper.setText((String) map.get("text"),true);//使用html,郵件內容
helper.setTo((String) map.get("to"));//收件地址
helper.setFrom((String) map.get("from"));//發件人
String filePath = (String) map.get("file");//附件路徑 if(!StringUtils.isEmpty(filePath)){ FileSystemResource fileSystemResource = new FileSystemResource(filePath); helper.addAttachment((String) map.get("newName"), fileSystemResource); } mailSender.send(mimeMessage); }}