Sending Email Using Java

Here is the code to send email using Java. Here we are going to use gmail gateway to send emails.
Please follow these steps before you use this code:
1. Login your google account
2. In google search, search “Application-specific password”
3. Enter a label for your reference and select “generate password”
4. Copy that password and paste it in code at “//password here” line.

Tested in NetBeans 8.0

 

//Sending email using Java
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class mails {
    public static void main(String[] args) {
     final String SSL = "javax.net.ssl.SSLSocketFactory";
  
     Properties props = System.getProperties();
     props.setProperty("mail.smtp.host", "smtp.gmail.com");
     props.setProperty("mail.smtp.socketFactory.class", SSL);
     props.setProperty("mail.smtp.socketFactory.fallback", "false");
     props.setProperty("mail.smtp.port", "465");
     props.setProperty("mail.smtp.socketFactory.port", "465");
     props.put("mail.smtp.auth", "true");
     props.put("mail.debug", "true");
     props.put("mail.store.protocol", "pop3");
     props.put("mail.transport.protocol", "smtp");
     final String username = "your email here";//your email address(gmail)
     final String password = "password here"; //Password Generated using above steps
     try{
     Session session = Session.getDefaultInstance(props, 
                          new Authenticator(){
                             protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(username, password);
                             }});

 
     Message msg = new MimeMessage(session);

 
     msg.setFrom(new InternetAddress("your email address"));
     msg.setRecipients(Message.RecipientType.TO, 
                      InternetAddress.parse("Receivers email address",false));
     msg.setSubject("Good day!");
     msg.setText("This email is generated using Java Code");
     msg.setSentDate(new Date());
     Transport.send(msg);
     
  }
catch (Exception e)
  { 
      e.printStacktrace();
}
}
}

 

By Sri

One thought on “Sending Email Using Java”

Leave a Reply

Your email address will not be published. Required fields are marked *