Effortless Emailing in Java : Sending Emails in 2 steps

Step 1 : First lets create email configuration, Create class called MailConfig.java and will use JavaMailSender. Add below code.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import java.util.Properties;

public class MailConfig {

public JavaMailSender getJavaMailSender() {

  JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
  Properties props = mailSender.getJavaMailProperties();
  props.put("mail.transport.protocol", "smtp");
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.debug", "true");
  return mailSender;

Step 2: Now Compose your email.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

public class SendEmailService {

private JavaMailSender javaMailSender;

public void sendSimpleMessage() {
 SimpleMailMessage message = new SimpleMailMessage();
 message.setSubject("Test Email");
 message.setText("Testing email service");
 log.info("Email send successfully");

 Call sendSimpleMessage() method from main method to trigger email.

Now run your application as java application it will send email please check your inbox.

Emailing in Java

Installing SSL on Your VPS in 5 Easy Steps

Fix 404 Page Not Found on page refresh

Google Search Console: Domains Validation in 3 Simple Steps for Enhanced Visibility


Leave a Reply

Your email address will not be published. Required fields are marked *