How to Send Email in Java using javax.mail API

Hey Everyone! In this article, we will learn how we can send an email using the Gmail Smtp server as host.


To send an email using Java first download the javax.mail API from the link provided below
https://javaee.github.io/javamail/

How to add JavaMail API to Java Project

Then add the JavaMail API by following steps (I have used NetBeans for my code), the other IDE will also have the same kind of options.
1. Right-click on the java project application created (in my case EmailSender)
add JavaMail API to Java Project

2. Select Properties.
How to Send Email in Java

3. Select Libraries.
JavaMail API

4. Click on Add JAR/Folder and add your javax.mail jar file.
Add javax.mail Jar file

To send an email in java we will be using the Java Mail API.
The key and value pair can be specified by using the methods of the Properties class.
The Session class represents a mail session.
The PasswordAuthentication class is a repository for the username and password provided by the user.
In the messageContent() method the message contents such as CC, subject and attachments are provided.
Let’s have a look at the program.

You can learn: How to validate Email Address in Java

Java program to send an Email

package emailsender;
 
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;



public class EmailSender{
       
    public static void main(String args[]) throws Exception{
        sendEmail();
       
        
    }
    
    
    
    public static void sendEmail() throws Exception{
        
        
        
        final String emailId = "[email protected]"; //sender's email address
        final String reciever="[email protected]"; //reciever's email address
        final String password = "*******";      //provide your password here
        
        
        System.out.println("Sending Email from "+emailId+" to "+reciever);
        
        Properties pr = new Properties();
        
        pr.put("mail.smtp.auth","true");    //for username and password authentication
        pr.put("mail.smtp.starttls.enable","true");
        pr.put("mail.smtp.host","smtp.gmail.com");  //here host is gmail.com 
        pr.put("mail.smtp.port","587");             //port no.
        
        Session gs = Session.getInstance(pr, new Authenticator(){
            @Override
            protected PasswordAuthentication getPasswordAuthentication(){
                return new PasswordAuthentication(emailId,password);  //pass your email id and password here
         
            }
        });
        
        Message ms = messageContent(gs,emailId,reciever);

         
            System.out.println("Message sent! ");
        
    }
    
       private static Message messageContent(Session gs, String emailId, String reciever) throws Exception {
           try{
           
           Message msg = new MimeMessage(gs);
           msg.setFrom(new InternetAddress(emailId));
           msg.setRecipient(Message.RecipientType.TO,new InternetAddress(reciever));
           msg.setSubject("Codespeedy.com tutorial"); //to set the subject (not mandatory)
           msg.setText("Visit Codespeedy.com to read articles on various programming languages such as Java,php,python etc.");
           Transport.send(msg);
           return msg;
           }catch(MessagingException e)
           {
               System.out.println(e);
           }
           
           return null;
            
       }
}
Output

Sending Email from [email protected] to [email protected]
Message sent!

 

Using the Properties class object set the host and the port number accordingly.
Here we have used the Gmail SMTP server as our host with 587 as the port number.

If you want to send an attachment along with your email consider the following program.

Send email with attachments in Java

The below Java program is for sending an email with attachments.

package emailsender;
 
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;



public class EmailSender{
       
    public static void main(String args[]) throws Exception{
        sendEmail();
       
        
    }
    
    
    
    public static void sendEmail() throws Exception{
        
        
        
        final String emailId = "[email protected]"; //sender's email address
        final String reciever="[email protected]"; //reciever's email address
        final String password = "*****";      //provide your password here
        
        
        System.out.println("Sending Email from "+emailId+" to "+reciever);
        
        Properties pr = new Properties();
         String host = "smtp.gmail.com";
        pr.put("mail.smtp.auth","true");    //for username and password authentication
        pr.put("mail.smtp.starttls.enable","true");
        pr.put("mail.smtp.host",host);  //here host is gmail.com 
        pr.put("mail.smtp.port","587");             //port no.
        
        Session gs = Session.getInstance(pr, new Authenticator(){
            @Override
            protected PasswordAuthentication getPasswordAuthentication(){
                return new PasswordAuthentication(emailId,password);  //pass your email id and password here
         
            }
        });
        
        Message ms = messageContent(gs,emailId,reciever);

         
            System.out.println("Message with attachment sent! ");
        
    }
    
       private static Message messageContent(Session gs, String emailId, String reciever) throws Exception {
           try{
           
           Message msg = new MimeMessage(gs);
           msg.setFrom(new InternetAddress(emailId));
           msg.setRecipient(Message.RecipientType.TO,new InternetAddress(reciever));
           msg.setSubject("Codespeedy.com tutorial"); //to set the subject (not mandatory)
           msg.setText("Visit Codespeedy.com to read articles on various programming languages such as Java,php,python etc.");
          
          
         BodyPart messageBodyPart = new MimeBodyPart();
         messageBodyPart.setText("Codespeedy");
         Multipart multipart = new MimeMultipart();
         multipart.addBodyPart(messageBodyPart);

         messageBodyPart = new MimeBodyPart();
         String loc = "C:\\Users\\Krishna Lakhi\\Desktop\\attachment1.txt";   //include the location of your attachment
         DataSource source = new FileDataSource(loc);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName(loc);
         multipart.addBodyPart(messageBodyPart);

         // Send the complete message parts
         msg.setContent(multipart);
           Transport.send(msg);
           return msg;
           }catch(MessagingException e)
           {
               System.out.println(e);
           }
           
           return null;
            
       }
}

Thus in this article, we have seen how we can send an email using javax.mail API and related classes.


I hope this article was useful to you.
If you have any doubts or suggestions please leave a comment down below.

Leave a Reply

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