Home > AI > Backend > SpringBoot >

send email

Step 1: install dependency

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

Available classes (optional)

The interfaces and classes for Java mail support in the Spring framework are organized as follows:

  1. MailSender interface: the top-level interface that provides basic functionality for sending simple emails
  2. JavaMailSender interface: the subinterface of the above MailSender. It supports MIME messages and is mostly used in conjunction with the MimeMessageHelper class for the creation of a MimeMessage. It’s recommended to use the MimeMessagePreparator mechanism with this interface.
  3. JavaMailSenderImpl class provides an implementation of the JavaMailSender interface. It supports the MimeMessage and SimpleMailMessage.
  4. SimpleMailMessage class: used to create a simple mail message including the from, to, cc, subject and text fields
  5. MimeMessagePreparator interface provides a callback interface for the preparation of MIME messages.
  6. MimeMessageHelper class: helper class for the creation of MIME messages. It offers support for images, typical mail attachments and text content in an HTML layout.

In the following sections, we show how to use these interfaces and classes.

Step 2: server config

# Mail
spring.mail.host=
spring.mail.port=465
spring.mail.protocol=smtp
spring.mail.username=
spring.mail.password=
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.smtp.starttls.enable=true

Step 3: codes

EmailServiceImp.java

@Service
public class EmailServiceImp  {
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender mailSender;

    public boolean sendEmail(String email, String username){
        System.out.println("send Email");

        String code = "123456";
        System.out.println("verify code:" + code);

        SimpleMailMessage message = new SimpleMailMessage();

        message.setTo(email);
        message.setSubject("Verify your new CowPte account!");
        message.setText(String.format(
                "To verify your email address, please use the following One Time Password (OTP):\n" +
                        "%s \n"  +
                        "Do not share this OTP with anyone. Amazon takes your account security very seriously. CowPte Customer Service will never ask you to disclose or verify your CowPte password, OTP, credit card, or banking account number. If you receive a suspicious email with a link to update your account information, do not click on the link—instead, report the email to CowPte for investigation.\n" +
                        "Thank you!", code));
        message.setFrom(from);
        System.out.println("server: " + from);
        System.out.println("destination: " + email);

        try {
            mailSender.send(message);
        } catch (MailException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}

DemoApplication.java

@SpringBootApplication
@EnableSwagger2
@RestController
public class PteApplication {

    @Autowired
    EmailServiceImp emailServiceImp;

    public static void main(String[] args) {
        SpringApplication.run(PteApplication.class, args);
    }

    @GetMapping("/good")
    public void good() {
        emailServiceImp.sendEmail("limindeng92@gmail.com", "sharkdeng");
    }
}

AutoWired object cannot in static function.

And if you initialize the EmailServiceImp in main function, it will throw NotFoundError for JavaMailSender

Leave a Reply