java

How to send mail in Java using Gmail

In this tutorial, we are going to see how to send an email in Java using the Gmail SMTP server.

Sending emails in java using Gmail SMTP and the JavaMail API is easy. The principle of sending emails is done by the JavaMail API (using GMail) and we just need to pass it the required parameters. With each release, the JavaMail API gets sophisticated, and sending emails with GMail is just a click away.

To send an email using the JavaMail API, you need to download the two jar files:

  • mailapi.jar
  • smtp.jar
Download the two files by clicking here.

 

 

Java Program to send mail in Java using Gmail:
import javax.mail.internet.*; 
import java.util.Properties;  
import javax.mail.*;  


class Mail {
  public static void send(String from,String pwd,String to,String sub,String msg){
    //Properties
    Properties p = new Properties();
    p.put("mail.smtp.host", "smtp.gmail.com");
    p.put("mail.smtp.socketFactory.port", "465");
    p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    p.put("mail.smtp.auth", "true");
    p.put("mail.smtp.port", "465");
    //Session
    Session s = Session.getDefaultInstance(p,
      new javax.mail.Authenticator() {
      protected PasswordAuthentication getPasswordAuthentication() {
         return new PasswordAuthentication(from, pwd);
      }
    });
    //compose message
    try {
      MimeMessage m = new MimeMessage(s);
      m.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
      m.setSubject(sub);
      m.setText(msg);
      //send the message
      Transport.send(m);
      System.out.println("Message sent successfully");
    } catch (MessagingException e) {
      e.printStackTrace();
    }
  }
}
public class Main {
 public static void main(String[] args) {
	 //from, password, to, subject, message
	 Mail.send(
		"[email protected]",
		"password",
		"[email protected]",
		"Bienvenu sur StackHowTo",
		"test mail!"
	);
 }
}

Output:

Message sent successfully

Don’t forget to change the e-mail and password. Now let’s look at how to run the program:

1- Load the jar files:

c:\> set classpath=mailapi.jar;smtp.jar;.;

 

 
2- Compile the java file:

c:\> javac Main.java

 
3- Run the code:

c:\> java Main

 

 
If you encounter this kind of error:
 

 
You need to configure the security settings of GMAIL, by visiting the following link https://myaccount.google.com/security
 

 
Scroll down the page until you find Less secure application access, then click Enable access as shown in the image below:
 

 
Click to activate the option.
 

 
Now check, if all goes well you should see the success message “Message sent successfully” in your command line.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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