Spring Mail
Spring Mail
Spring Mail
2020/04/14 (新增連結)
基本概念
基本概念
Spring Mail是基於JavaMail,可以利用JavaMail透過SMTP送出email,也可以利用pop3或imap去mail server讀取email。我們最常使用的就是利用SMTP送出email,以下就只提供SMTP這部份的範例。
設定
設定
pom.xml需要:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
application.properties (以gmail為例)
spring.mail.host = smtp.gmail.com
spring.mail.username = xxxx@gmail.com
spring.mail.password = xxxx
send.from.email= xxxx@gmail.com
spring.mail.properties.mail.smtp.auth = true;
spring.mail.properties.mail.smtp.starttls.enable = true
spring.mail.properties.mail.smtp.ssl.enable = true
spring.mail.properties.mail.socketFactory.port=587
spring.mail.properties.mail.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.socketFactory.fallback=false
spring.mail.smtp.port= 587
- 使用gmail時,記得要「啟用安全性較低的應用程式存取權 」 https://www.google.com/settings/security/lesssecureapps
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.demo.service.MailService;
@Controller
public class MailController {
@Autowired
private MailService mailService;
@GetMapping("/")
@ResponseBody
public String hello(){
mailService.prepareAndSend("053792@fju.edu.tw","Sample mail subject");
return "Mail sent";
}
}
MailService.java
package com.example.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;
@Service
public class MailService {
private JavaMailSender mailSender;
@Autowired
public MailService(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void prepareAndSend(String recipient, String message) {
MimeMessagePreparator messagePreparator = mimeMessage -> {
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
messageHelper.setFrom("jitsung.wu@gmail.com");
messageHelper.setTo(recipient);
messageHelper.setSubject(message);
messageHelper.setText(message);
};
try {
mailSender.send(messagePreparator);
//System.out.println("sent");
} catch (MailException e) {
//System.out.println(e);
// runtime exception; compiler will not force you to handle it
}
}
}
參考資料
參考資料