Category Archives: Spring Boot

Using Gmail as SMTP server from Java, Spring Boot apps

Gmail users can use Gmail’s SMTP server smtp.gmail.com to send emails from their Spring Boot apps. For this let us do some setup in the app:

  1. Provide SMTP connection properties in the application.properties file:
    spring.mail.host=smtp.gmail.com
    spring.mail.username=<your gmail/google app email>
    spring.mail.password=*****
    spring.mail.port=587
    spring.mail.properties.mail.smtp.starttls.enable=true
    spring.mail.properties.mail.smtp.auth=true
    spring.mail.properties.mail.smtp.starttls.required=true
  2. Use Spring Boot Email tools library – which is a wrapper over Spring Boot Email starter library.  Add the following in your pom.xml:
    <dependency>
        <groupId>it.ozimov</groupId>
        <artifactId>spring-boot-email-core</artifactId>
        <version>0.6.3</version>
    </dependency>
  3. Annotation your application’s main class (i.e class annotated with @SpringBootApplication) with @EnableEmailTools:
    @SpringBootApplication
    @EnableEmailTools
    public class EmailApplication {
        public static void main(String[] args){
            SpringApplication.run(EmailApplication.class, args);
        }
    }
  4. Let’s write a test which uses it.ozimov.springboot.mail.service.EmailService bean to send an email:
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class EmailServiceTest {
        @Autowired 
        it.ozimov.springboot.mail.service.EmailService emailService; 
    
        @Value("${spring.mail.username}") String fromEmail; 
        @Test 
        public void testSendEmail() throws UnsupportedEncodingException { 
            User user = new User(); 
            user.setEmail("sanaulla123@gmail.com"); 
            user.setDisplayName("Mohamed Sanaulla"); 
            final Email email = DefaultEmail.builder() 
                .from(new InternetAddress(fromEmail, "From Name"))
                .to(Lists.newArrayList(new InternetAddress(
                    user.getEmail(), user.getDisplayName()))) 
                .subject("Testing email")
                .body("Testing body ...")
                .encoding("UTF-8").build();
            emailService.send(email); 
        }
    }

Continue reading

Advertisements