Send email with authentication

import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

import java.util.Properties;


public class SimpleMail {

    private static final String SMTP_HOST_NAME = "smtp.myserver.com";
    private static final String SMTP_AUTH_USER = "myusername";
    private static final String SMTP_AUTH_PWD  = "mypwd";

    public static void main(String[] args) throws Exception{
       new SimpleMail().test();
    }

    public void test() throws Exception{
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");

        Authenticator auth = new SMTPAuthenticator();
        Session mailSession = Session.getDefaultInstance(props, auth);
        // uncomment for debugging infos to stdout
        // mailSession.setDebug(true);
        Transport transport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        message.setContent("This is a test", "text/plain");
        message.setFrom(new InternetAddress("info@maixuanviet.com"));
        message.addRecipient(Message.RecipientType.TO,
             new InternetAddress("maixuanviet.com@gmail.com"));

        transport.connect();
        transport.sendMessage(message,
            message.getRecipients(Message.RecipientType.TO));
        transport.close();
    }

    private class SMTPAuthenticator extends javax.mail.Authenticator {
        public PasswordAuthentication getPasswordAuthentication() {
           String username = SMTP_AUTH_USER;
           String password = SMTP_AUTH_PWD;
           return new PasswordAuthentication(username, password);
        }
    }
}

NOTE: The JavaMail Authenticator is found in the javax.mail package and is different from the java.net class of the same name. The two don’t share the same Authenticator as the JavaMail API works with Java 1.1, which didn’t have the java.net variety.

Related posts:

Using a List of Values in a JdbcTemplate IN Clause
How to Read a File in Java
Spring Boot Integration Testing with Embedded MongoDB
Getting the Size of an Iterable in Java
How to Manually Authenticate User with Spring Security
Java Program to Create the Prufer Code for a Tree
Java Program to Implement Shoelace Algorithm
Spring Webflux with Kotlin
Refactoring Design Pattern với tính năng mới trong Java 8
Primitive Type Streams in Java 8
Runnable vs. Callable in Java
Lập trình đa luồng với CompletableFuture trong Java 8
Java Program to Implement the Edmond’s Algorithm for Maximum Cardinality Matching
A Guide to WatchService in Java NIO2
Introduction to Thread Pools in Java
Arrays.asList vs new ArrayList(Arrays.asList())
Form Validation with AngularJS and Spring MVC
Hướng dẫn Java Design Pattern – Prototype
Xây dựng ứng dụng Client-Server với Socket trong Java
Serverless Functions with Spring Cloud Function
Hướng dẫn sử dụng Java Generics
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found
Convert Character Array to String in Java
Hướng dẫn Java Design Pattern – Visitor
Object cloning trong java
Java Program to Implement Shell Sort
Java Program to Implement Binomial Tree
Batch Processing with Spring Cloud Data Flow
Getting Started with Stream Processing with Spring Cloud Data Flow
Java Program to Implement Segment Tree
Java Program to Implement Network Flow Problem
Jackson Unmarshalling JSON with Unknown Properties