4

I am new in spring MVC i have got an issue while send email through spring . no exception will occur but mail not send.

my applicationContext.xml

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">  
        <property name="host" value="smtp.gmail.com" />  

        <property name="username" value="uname" />  
        <property name="password" value="pass" />  
        <property name="javaMailProperties">  
            <props>  
               <prop key="mail.smtp.auth">true</prop>  
              <prop key="mail.smtp.socketFactory.port">465</prop>  
              <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>  
              <prop key="mail.smtp.port">465</prop>  
            </props>  
        </property>  
    </bean> 

my controller class

@Controller
public class WebController {

//    System.out.println("suceees");
    @Autowired
     private JavaMailSender mailSender;  

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {

        return "index";

    }

    @RequestMapping(value = "/redirect", method = RequestMethod.GET)
    public String redirect() {

         sendMail();
        return "redirect:finalPage";
    }

    @RequestMapping(value = "/finalPage", method = RequestMethod.GET)
    public String finalPage() {


        return "final";
    }

    public void sendMail() {

        try {
            MimeMessage message = mailSender.createMimeMessage();

            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom("sender");
            helper.setTo("receiver");
            helper.setSubject("hi");
            helper.setText("welcome");

            // attach the file
            FileSystemResource file = new FileSystemResource(new File("/home/ajmal/Pictures/messi.jpg"));
            helper.addAttachment("messi.jpg", file);//image will be sent by this name

            mailSender.send(message);
 } catch (MailException | MessagingException ex) {

            System.err.println("error");

        }

    }
}

thanks in advance .. no exception will occur. but mail not send ?

Subodh Joshi
  • 12,717
  • 29
  • 108
  • 202
Ajmal Muhammad
  • 685
  • 7
  • 25

1 Answers1

7

We had into the same problem sometime back, with Spring Boot 1.2.5. Looks like with the latest version of Java Mail, now another property is needed - spring.mail.properties.mail.smtp.ssl.enable to be set as true. See this post for details.

Also, when I tested my application, I saw that merely giving the regular gmail password didn't anymore work. I needed a 2-step verified account, and had to use an application password.

Community
  • 1
  • 1
Sanjay
  • 8,755
  • 7
  • 46
  • 62