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;

@Configuration
public class MailConfig {

@Bean
public JavaMailSender getJavaMailSender() {

  JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
  mailSender.setHost("smtp.gmail.com");
  mailSender.setPort(587);
  mailSender.setUsername("youemail@mail.com");
  mailSender.setPassword("yourmailpassword");
  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;

@Service
@Slf4j
public class SendEmailService {

@Autowired
private JavaMailSender javaMailSender;

public void sendSimpleMessage() {
 SimpleMailMessage message = new SimpleMailMessage();
 message.setFrom("fromemailid@mail.com");
 message.setTo("tomailid@mail.com");
 message.setSubject("Test Email");
 message.setText("Testing email service");
 javaMailSender.send(message);
 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 *