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:

Biểu thức Lambda trong Java 8 – Lambda Expressions
Jackson vs Gson
REST Pagination in Spring
Most commonly used String methods in Java
Java Program to Implement Warshall Algorithm
Check If a String Is Numeric in Java
Hướng dẫn Java Design Pattern – Abstract Factory
Java Program to Find the Number of Ways to Write a Number as the Sum of Numbers Smaller than Itself
Java Program to Construct a Random Graph by the Method of Random Edge Selection
Deploy a Spring Boot App to Azure
Spring Security and OpenID Connect
Java Program to Find the Peak Element of an Array O(n) time (Naive Method)
Hướng dẫn sử dụng Java Generics
Java Program to Show the Duality Transformation of Line and Point
Receive email using POP3
How To Serialize and Deserialize Enums with Jackson
Java Program to Implement Affine Cipher
How to Build an Authentication API with JWT Token in Node.js
Lập trình đa luồng với CompletableFuture trong Java 8
Java Program to Generate Random Numbers Using Middle Square Method
Java Program to Implement ArrayBlockingQueue API
Setting Up Swagger 2 with a Spring REST API
Java Program to Implement Find all Back Edges in a Graph
Composition, Aggregation, and Association in Java
Concrete Class in Java
Primitive Type Streams in Java 8
Java Program to Check if any Graph is Possible to be Constructed for a Given Degree Sequence
Java – InputStream to Reader
Spring Data MongoDB Transactions
Java Program to Compute Discrete Fourier Transform Using the Fast Fourier Transform Approach
Java Program to Implement Lloyd’s Algorithm
Spring Data – CrudRepository save() Method