Home > Enterprise >  Sending email via Spring Boot
Sending email via Spring Boot

Time:12-10

I'm trying to create a contact form. I am using Spring Boot 3.0.0. and Thymeleaf. Everything runs on localhost. I get an unexpected error when I want to send a message:

javax.mail.Provider: com.sun.mail.imap.IMAPProvider not a subtype java.util.ServiceConfigurationError: javax.mail.Provider: com.sun.mail.imap.IMAPProvider not a subtype

pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
    <version>3.0.0</version>
</dependency>

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>

Message class:

public class MessageInfoDto {
    private String name;
    private String email;
    private String text;

    public String getName() {
        return name;
    }

    public String getEmail() {
        return email;
    }

    public String getText() {
        return text;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setText(String text) {
        this.text = text;
    }

Controller:

@Controller
public class MessageInfoController {
    MessageInfoService messageInfoService;

    public MessageInfoController(MessageInfoService messageInfoService) {
        this.messageInfoService = messageInfoService;
    }

    @GetMapping("/contact")
    public String emialForm(Model model) {
        model.addAttribute("message", new MessageInfoDto());
        return "contact";
    }

    @PostMapping("/send")
    public String getMessage(MessageInfoDto message) {
        messageInfoService.sendEmail(message);
        return "redirect:/contact";
    }
}

Service:

@Service
public class MessageInfoService {
    private final JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String owner;

    public MessageInfoService(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void sendEmail(MessageInfoDto message) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setTo(owner);
        simpleMailMessage.setFrom(message.getEmail());
        simpleMailMessage.setText(message.getText());
        simpleMailMessage.setSubject("New Message");
        simpleMailMessage.setReplyTo(message.getEmail());
        mailSender.send(simpleMailMessage);
    }
}

HTML(contact.html):

<body>
<main  layout:fragment="content">
  <h2 >Send us a message</h2>
  <form action="#" th:action="@{/send}" method="post" enctype="multipart/form-data"  th:object="${message}">
    <label for="name">Your Name</label>
    <input type="text" id="name" placeholder="Your Name" th:field="*{name}" required>
    <label for="email">Your e-mail</label>
    <input type="text" id="email" placeholder="e-mail" th:field="*{email}">
    <label for="message">Your message</label>
    <textarea id="message" rows="10" th:field="*{text}"></textarea>
    <button type="submit">Send</button>
  </form>
</main>
</body>

application.yml:

spring:
  mail:
    host: smtp.gmail.com
    port: 587
    username: 10*****@gmail.com
    password: [genereted password]
    properties:
      smtp:
        auth: true
        starttles:
          enable: true
          required: true

Please help, I've been googling this since yesterday and couldn't find an answer.

I've also tried with javax.mail-api.

CodePudding user response:

  1. You don't need this, please remove it.

<dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency>

  1. Check MailSender import

USE import org.springframework.mail.MailSender;

NOT import org.springframework.mail.javamail.JavaMailSender;

  1. spring-boot-starter-mail will create default MailSender , you don't create it (MailSender), just use @Autowired private MailSender javaMailSender;

Hello.java

package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
//import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.MailSender;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController

public class Hello {
    @Autowired
    private MailSender javaMailSender;
    @RequestMapping("/sendMail")
    public String sendConfirmationEmail() {
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setTo("aaa@localhost");
        msg.setSubject("Testing from Spring Boot");
        msg.setText("Hello World from Spring Boot Email");
        javaMailSender.send(msg);
        return "OK";
    }
}

I am test ok in my simple test project.

curl http://localhost:8080/sendMail

And I use FakeSmtp jar to my fake mail server.

my spring boot 3 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo-mail</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo-mail</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

MY application.properties

spring.mail.host=localhost
spring.mail.port=2525
spring.mail.username=demo@localhost
spring.mail.password=demopassword

spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.transport.protocol=smtp
spring.mail.properties.mail.smtps.quitwait=false
spring.mail.properties.mail.smtp.socketFactory.port=465
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory

DemoMailApplication.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoMailApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoMailApplication.class, args);
    }
}
  • DemoMailApplication.java
  • Hello.java
  • application.properties
  • pom.xml

CodePudding user response:

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

public void sendEmail(){
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.gmail.com");
mailSender.setPort(587);
mailSender.setUsername("[email protected]");
mailSender.setPassword("yourPassword");
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("[email protected]");
message.setTo("[email protected]");
message.setSubject("Test Email");
message.setText("This is a test email sent using Spring Boot");
mailSender.send(message);
}
  • Related