2017  Kodetalk | Feedback | Privacy Policy | Terms | About

How to send mail using java mail api

Way to send mail using java mail api.


To send mail using java we can use below method:

import java.util.Base64;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMail {

    private static Session session;
    private static Properties props = new Properties();

    static {
        props.put("mail.smtp.host", <Mail Host Name>);
        props.put("mail.smtp.socketFactory.port", <SMTP Port Number>);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.port", <SMTP Port Number>);

        session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(<User Id e.g abc@abc.com>,

    public void sendMailForActivateUserAccount(String message) {

               try {
                       Message message = new MimeMessage(session);
                       message.setContent(message, "text/html");
                       message.setFrom(new InternetAddress(<Mail User id [Basicaly the id from where mail will trigger]>));
                       message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(userMailId));
                       message.setSubject(<Mail Subject>);
        } catch (MessagingException e) {
            throw new RuntimeException(e);

This above code will help to trigger mail using java mail api.

Answer is