Search code examples
javasmtpjakarta-mail

SMTP exception in sending the email through java code


I am trying to send the email using java but my code is throwing the exception Exception herejavax.mail.MessagingException: Can't send command to SMTP host;

I am using the following code

 import java.util.Properties;
 import javax.mail.*;
 import javax.mail.internet.*;

 public class SendEmail {

     public static void main(String args[]) {

       final String username ="[email protected]"; 
       final String password = "password here";

       final String xtomail="email here";
       final String cc="email here";
       final String bcc="email here";

       final String xsub="heavy discount for static websites";
       final String xbody="we are great leader in software industry";

       Properties props = new Properties();

       try{    
           props.put("mail.smtp.auth", "true");
           props.put("mail.smtp.starttls.enable", "true");
           props.put("mail.smtp.host", "smtp.gmail.com");
           props.put("mail.smtp.port", "587");

       } catch(Exception ex) {
           System.out.println("exception here"+ex); 
       }

       Session session = Session.getInstance(props,
                                             new javax.mail.Authenticator() {
           protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
               return new javax.mail.PasswordAuthentication(username, password);
       }});

       try {

           Message message = new MimeMessage(session);
           message.setFrom(new InternetAddress(username));
           message.setRecipients(Message.RecipientType.TO,
                                 InternetAddress.parse(xtomail));
           message.addRecipients(Message.RecipientType.CC,InternetAddress.parse(cc));
           message.addRecipients(Message.RecipientType.BCC,InternetAddress.parse(bcc));
           message.setSubject(xsub);
           message.setText(xbody);

           Transport.send(message);
           System.out.println("email send");             
       }
       catch (Exception e) {
           System.out.println("Exception here"+e);
       }                    
    }
}        

Solution

  • What does the debug output show?

    Is your Gmail account enabled for less secure apps?