2017-04-23 206 views
1

我想發送郵件使用Gmail郵件服務器和春季郵件發件人,它不會拋出任何例外,但我的郵件不發送我沒有收到它。JAVA春季郵件通過Gmail發送

這裏的服務怎麼樣子:

@Service 
public class MailSenderService { 

    @Autowired 
    public MailSender mailSender; 

    public void prepareAndSend(String recipient, String message) { 
     try { 

      SimpleMailMessage mail = new SimpleMailMessage(); 
      String from = "[email protected]"; 
      String to = "[email protected]"; 
      String subject = "Test subject"; 
      mail.setFrom(from); 
      mail.setTo(recipient); 
      mail.setSubject(subject); 
      mail.setText(message); 
      mailSender.send(mail); 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 
    } 
} 

AppProperties

spring.mail.host = smtp.gmail.com 
spring.mail.username = ********@gmail.com 
spring.mail.password = ******** 
spring.mail.properties.mail.smtp.auth = true 
spring.mail.properties.mail.smtp.socketFactory.port = 465 
spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory 
spring.mail.properties.mail.smtp.socketFactory.fallback = false 
spring.mail.properties.mail.smtp.ssl.enable = true 

及POM依賴

<dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-mail</artifactId> 
</dependency> 

我部署在8080端口上我的應用程序並調用這兩個參數此服務,沒有發現任何異常,但在我的testRecipient1收件箱中,我沒有找到任何新郵件我有沒有錯過?

+0

您是否將發件人的電子郵件帳戶,以[允許安全性較低的應用這裏提到(HTTP:// stackoverflow.com/a/32457468/205233)? – Filburt

+0

你檢查了這個[Spring Boot - 無法連接到SMTP主機:smtp.gmail.com,端口:25,響應:421](http://stackoverflow.com/questions/28064904/spring-boot-could-not -connect到SMTP主機-SMTP-的Gmail-COM端口-25響應)。可能會有所幫助。 –

+0

那麼,除了你應該使用記錄器的錯誤,而不是使用printStackTrace()方法,你做了一些調試?如果你沒有,你怎麼能說一切順利? – JeanValjean

回答

0

如果您沒有在您的web應用程序中使用SSL證書,而是嘗試使用我的代碼,那麼它在春季啓動,文本郵件和HTML Mail中都可以很好地工作。

@Autowired 
private JavaMailSender mailSender; 

@RequestMapping(value="/ShareVecancy",method=RequestMethod.GET) 
public ModelAndView sendEmailToReference(HttpServletRequest request,HttpSession session){ 

    try { 

      MimeMessage mail = mailSender.createMimeMessage(); 
      MimeMessageHelper messageHelper = new MimeMessageHelper(mail, true); 
      messageHelper.setTo("[email protected]"); 
      messageHelper.setSubject("Testing mail"); 
      messageHelper.setText("HTML Text or Any text You want to send ", true); 
      mailSender.send(mail); 

     } catch (MailException e) { 
      e.printStackTrace(); 
     } 


} 

屬性文件:::

spring.mail.host=smtp.gmail.com 
spring.mail.port=587 
[email protected] 
spring.mail.password=******* 
spring.mail.protocol=smtp 
spring.mail.properties.mail.smtp.starttls.enable=true 
spring.mail.default-encoding=UTF-8 

依賴::

<dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-mail</artifactId> 
    </dependency>