Send Email using Gmail in Java

Here is another code for sending email using Java.  My Previous code, it needs to have access to application-specific password(Sending Email Using Java). Here you just need to enter your email address and password.

Requirements:
1. you need mail.jar and activation.jar to be added to your project
2.  Sign in your gmail, go to Account–> Connected Apps and Sites –> Allow less secure apps: turn it ON

//Send email using gmail in java
public class checkmail {
    public static void main(String[] args) {
               
                
                
		final String username = "youremail@gmail.com";
		final String password = "password";

		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.port", "587");

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

		try {

			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("youremail@gmail.com"));
			message.setRecipients(Message.RecipientType.TO,
				InternetAddress.parse("receiver@gmail.com"));
			message.setSubject("Java Mailer");
			message.setText("Hello this mail is sent from java code");

			Transport.send(message);

			

		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
                }
                
	
    
}

 

By Sri

One thought on “Send Email Using Gmail in Java”

Leave a Reply

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