1. 新增maven依賴項:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId>
<version>${spring-boot-version}</version> </dependency>
2. 新增配置項 mail.properties
spring.mail.host=smtp.qq.com
spring.mail.username=123@qq.com
spring.mail.password=授權碼
spring.mail.port=465
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.default-encoding=UTF-8
3. 啟動類掃描配置
@PropertySource(value = {"mail.properties"})
4. 傳送郵件程式碼
import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import javax.mail.internet.MimeMessage; @Slf4j @Servicepublic class MailService { @Autowired(required = false) private JavaMailSender mailSender; public boolean sendEmail(MailInfoBO mailInfo) { try { // 建立一個郵件訊息 MimeMessage message = mailSender.createMimeMessage(); // 建立 MimeMessageHelper MimeMessageHelper helper = new MimeMessageHelper(message, false); // 發件人郵箱和名稱 helper.setFrom("123@qq.com", "測試"); // 收件人郵箱 helper.setTo(mailInfo.getToEmail()); // 郵件標題 helper.setSubject(mailInfo.getSubject()); // 郵件正文,第二個參數列示是否是HTML正文 helper.setText(mailInfo.getContent(), true); mailSender.send(message); return true; } catch (Exception e) { log.error("MailService error", e); } return false; } }