Arjun K P
Arjun K P

Reputation: 2111

unable to send java mail via SSL in Servlet

I am writing a simple java program to send mail to a particular Email ID using java mail using SSL

Following is my code

        public static String sendMail(String to)
        {
             String status_message = null;

             try 
             {
                   Properties props = new Properties();
                   props.put("mail.smtp.host", "smtp.gmail.com");
                   props.put("mail.smtp.socketFactory.port", "465");
                   props.put("mail.smtp.socketFactory.class",
                        "javax.net.ssl.SSLSocketFactory");
                   props.put("mail.smtp.auth", "true");
                   props.put("mail.smtp.port", "465");

                   Session session = Session.getDefaultInstance(props,
                   new javax.mail.Authenticator() 
                   {
                       @Override
                       protected PasswordAuthentication getPasswordAuthentication() 
                       {
                             return new PasswordAuthentication("[email protected]","password");//change accordingly
                       }
                  });

               //compose message
                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress("[email protected]"));//change accordingly
                message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
                message.setSubject("Email Subject");
                message.setText("Text Content included in inside Email"); 

                //send message
                Transport.send(message);

                status_message = "success";
    } 
    catch (MessagingException ex) 
    {
                status_message = ex.getMessage();
    } 


}

When i ran this code inside a pariticular main Thread. It worked successfully.

But this same didn't worked when i included it inside a function called within a servlet

When i read the status_message value. It's showing smtp.

Can anyone help me find out what the issue is. Am i missing anything ? I want to send mail through a jsp servlet.

Upvotes: 0

Views: 570

Answers (1)

Bill Shannon
Bill Shannon

Reputation: 29971

You've made several of the common JavaMail mistakes. Correct them and see if that solves your problem.

Upvotes: 1

Related Questions