Example of sending email in Java

John Doe ·

441 Views
package com.phenomena.xxx.test.mail;

import jakarta.mail.*;
import jakarta.mail.internet.*;
import java.util.*;

public class MailSendTest {
	
	private static final String SMTP_HOST_NAME   = "smtp.test.com"; //or simply "localhost"
    private static final String SMTP_AUTH_USER   = "test"; // id
    private static final String SMTP_AUTH_PWD    = "1234"; // pw
    private static final String emailMsgTxt      = "Hell World";
    private static final String emailSubjectTxt  = "Title";
    private static final String emailFromAddress = "test@phenomena.com";
  
    // Add List of Email address to who email needs to be sent to
    private static final String[] emailList = {"contact@me.com"};
    
	public static void main(String args[]) throws AuthenticationFailedException, MessagingException {
		MailSendTest smtpMailSender = new MailSendTest();
        smtpMailSender.postMail( emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
        System.out.println("Sucessfully Sent mail to All Users");	
	}
	
	public void postMail( String recipients[], String subject, String message , String from) throws MessagingException, AuthenticationFailedException {
		boolean debug = false;
		
		// Set the host smtp address
		Properties props = new Properties();
		props.put("mail.smtp.host", SMTP_HOST_NAME);
		props.put("mail.smtp.port", "666"); //TLS Port
		props.put("mail.smtp.auth", "true"); //enable authentication
		props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
		props.put("mail.debug", "true");
		props.put("mail.smtp.ssl.enable", "true"); //Important
		Authenticator auth = new SMTPAuthenticator();
		Session session = Session.getDefaultInstance(props, auth);
		
		session.setDebug(debug);
		
		// create a message
		Message msg = new MimeMessage(session);
		
		// set the from and to address
		InternetAddress addressFrom = new InternetAddress(from);
		msg.setFrom(addressFrom);
		
		InternetAddress[] addressTo = new InternetAddress[recipients.length];
		for (int i = 0; i < recipients.length; i++) {
			addressTo[i] = new InternetAddress(recipients[i]);
		}
		msg.setRecipients(Message.RecipientType.TO, addressTo);
		
		// Setting the Subject and Content Type
		msg.setSubject(subject);
		msg.setContent(message, "text/plain");
		Transport.send(msg);
	}
	    
	private class SMTPAuthenticator extends jakarta.mail.Authenticator {
	    public PasswordAuthentication getPasswordAuthentication() {
	        String username = SMTP_AUTH_USER;
	        String password = SMTP_AUTH_PWD;
	        return new PasswordAuthentication(username, password);
	    }
	}

}

 

Ref.

I use brand new spring boot project with next Maven dependency &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-star...

 

Jakarta mail