Java send mail using Gmail SMTP

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="youremail@gmail.com";
        final String password="yourpassword";
        Properties prop=new Properties();
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.host", "smtp.gmail.com");
        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("fromemail@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("toemail@gmail.com"));
	        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");
	        CommandMap.setDefaultCommandMap(mc);
	        message.setText(htmlBody);
            message.setContent(textBody, "text/html");
        	Transport.send(message);

        	System.out.println("Done");

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

I hope this email sending code is working for you.

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s