我想使用JavaMailSender
在Spring Boot中發送電子郵件。每當我跑我的項目,我得到這個錯誤:無法使用Gmail SMTP在Spring Boot中發送電子郵件
org.springframework.mail.MailSendException: Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 530-5.5.1 Authentication Required. Learn more at 530 5.5.1 https://support.google.com/mail/answer/14257 ps2sm10628859pab.10 - gsmtp
我不使用兩步驗證了我的帳號和密碼是正確的也是,我檢查了它。
這是我的application.properties文件:
spring.mail.host = smtp.gmail.com
sprint.mail.username = [email protected]
sprint.mail.password = *******
send.from.email= [email protected]
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
我MailService的類:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
@Component
public class MailService {
@Autowired
private JavaMailSender javaMailSender;
//public MailService(JavaMailSender javaMailSender){
// this.javaMailSender = javaMailSender;
//}
public void sendMail() throws MailException{
SimpleMailMessage mail = new SimpleMailMessage();
mail.setTo("[email protected]");
mail.setFrom("[email protected]");
mail.setSubject("Test");
mail.setText("test mail");
javaMailSender.send(mail);
}
}
這是我的控制器:
@Controller
@EnableAutoConfiguration
public class MailController {
@Autowired
private MailService mailService;
@RequestMapping("/api/sendmail")
@ResponseBody
private String sendMail() {
try{
mailService.sendMail();
return "mail sent";
}catch(MailException e){
e.printStackTrace();
}
return "thanks";
}
}
我幾乎所有的線程都與stackoverflow上的這個問題有關,但仍然無法弄清楚。請幫忙!
您是否配置Gmail帳戶接受IMAP/POP3請求? – WeMakeSoftware