Java send mail using Gmail SMTP

  • 14 July, 2018
  • Renish Khunt
  • JAVA
  • 132

Java send mail using Gmail SMTP. Today we are learning how to send mailĀ using Gmail SMTP JAVA. Let’s see the code for sending the mail using Gmail SMTP or you can set your own server SMTP detail instead of Gmail. You can send mail using below code.

import java.util.*;
import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.*;
import javax.mail.Provider;
import javax.mail.internet.*;

public class Themail {

    public static void main(String[] args) {
        final String username="";
        final String password="yourpassword";
        Properties prop=new Properties();
        prop.put("mail.smtp.auth", "true");
        prop.put("", "");
        prop.put("mail.smtp.port", "587");
        prop.put("mail.smtp.starttls.enable", "true");

        Session session = Session.getDefaultInstance(prop,
      	new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
      	try {
            String htmlBody = "<strong>This is an HTML Message</strong>";
            String textBody = "This is a Text Message.";
		    Message message = new MimeMessage(session);
		    message.setFrom(new InternetAddress(""));
	        message.setSubject("Testing Subject");
	        MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
	        mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
	        mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
	        mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
	        mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
	        mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
            message.setContent(textBody, "text/html");


        } catch (MessagingException e) {

I hope this email sending code is working for you.

If you have any issue after using this code please write the comment below.