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:

Transactions with Spring and JPA
Java Program to Implement a Binary Search Tree using Linked Lists
Create Java Applet to Simulate Any Sorting Technique
Mệnh đề Switch-case trong java
Luồng Daemon (Daemon Thread) trong Java
Spring 5 Testing with @EnabledIf Annotation
Hướng dẫn Java Design Pattern – Iterator
Java Program to implement Sparse Vector
Merging Streams in Java
Spring AMQP in Reactive Applications
Hướng dẫn Java Design Pattern – Flyweight
@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll
Java Program to Implement Gauss Seidel Method
JPA/Hibernate Persistence Context
Java Program to Find a Good Feedback Edge Set in a Graph
Implementing a Runnable vs Extending a Thread
Object cloning trong java
4 tính chất của lập trình hướng đối tượng trong Java
Java Program to Decode a Message Encoded Using Playfair Cipher
Introduction to Java 8 Streams
Java Program to Find Maximum Element in an Array using Binary Search
Tạo ứng dụng Java RESTful Client với thư viện Retrofit
Java program to Implement Tree Set
Java Program to do a Breadth First Search/Traversal on a graph non-recursively
Java Program to Perform the Shaker Sort
Spring Boot - OAuth2 with JWT
Java Program to Create a Minimal Set of All Edges Whose Addition will Convert it to a Strongly Conne...
Receive email using POP3
Java Program to Solve the Fractional Knapsack Problem
How to Read a Large File Efficiently with Java
Java Program to Implement Dijkstra’s Algorithm using Queue
Hướng dẫn Java Design Pattern – Facade