java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot发送邮件方式

SpringBoot实现发送邮件功能的三种方式

作者:白露与泡影

本文详细介绍了如何在SpringBoot应用中使用JavaMailSender、JavaMailAPI和ApacheCommonsEmail库发送邮件,对比了它们的优缺点,并提供了示例代码和配置指导,需要的朋友可以参考下

SpringBoot 发送邮件的三种方式

选择哪一种方案

这里对比一下Spring Framework提供的JavaMailSender、使用JavaMail API、以及Apache Commons Email库的优缺点:

1. JavaMailSender (Spring Framework)

优点:

缺点:

2. JavaMail API

优点:

缺点:

3. Apache Commons Email库

优点:

缺点:

JavaMailSender 示例

以下是一个简单的Spring Boot邮件发送的示例代码:

首先,确保你的Spring Boot项目中包含了Spring Boot Starter Mail库。在pom.xml中添加以下依赖:

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

然后,创建一个服务类来处理邮件发送:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
 
@Service
public class EmailService {
 
    @Autowired
    private JavaMailSender javaMailSender;
 
    public void sendEmail(String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
 
        javaMailSender.send(message);
    }
}
 

接下来,在你的应用程序中,你可以使用EmailService类来发送电子邮件。以下是一个简单的示例控制器:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
@RequestMapping("/email")
public class EmailController {
 
    @Autowired
    private EmailService emailService;
 
    @GetMapping("/send")
    public String sendEmail(@RequestParam String to, @RequestParam String subject, @RequestParam String text) {
        emailService.sendEmail(to, subject, text);
        return "Email sent successfully!";
    }
}
 

在上述代码中,通过调用sendEmail方法,你可以发送一封包含指定主题和文本内容的电子邮件。

确保在application.propertiesapplication.yml文件中配置SMTP服务器的相关信息,例如:

  mail:
    host: smtp.163.com
    username: 邮箱名字
    password: 邮箱密码或者密钥
    port: 465
    protocol: smtp
    default-encoding: utf-8
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true
          ssl:
            enable: true
          socketFactory:
            port: 465
            class: javax.net.ssl.SSLSocketFactory

可以用 swagger 测试请求,也可以用 postman 工具测试。

测试结果如下:

使用JavaMail API来发送邮件

在Spring Boot应用程序中使用JavaMail API发送电子邮件。

添加依赖

在你的pom.xml文件中,添加以下依赖:

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

邮箱配置

确保在application.propertiesapplication.yml文件中配置SMTP服务器的相关信息,例如:

  mail:
    host: smtp.163.com
    username: 邮箱名字
    password: 邮箱密码或者密钥
    port: 465
    protocol: smtp
    default-encoding: utf-8
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true
          ssl:
            enable: true
          socketFactory:
            port: 465
            class: javax.net.ssl.SSLSocketFactory

编写发送邮件的代码

使用JavaMail API发送电子邮件。以下是一个简单的例子:

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
 
@Service
public class EmailService {
 
    @Value("${spring.mail.username}")
    private String from;
 
    @Autowired
    private JavaMailSender javaMailSender;
 
    public void sendSimpleEmail(String to, String subject, String text) throws MessagingException {
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "your_smtp_host");
        properties.put("mail.smtp.port", "your_smtp_port");
 
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, "your_email_password");
            }
        });
 
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSubject(subject);
        message.setText(text);
 
        Transport.send(message);
    }
}
 

使用服务类发送邮件:

@RestController
@RequestMapping("/email")
public class EmailController {
 
    @Autowired
    private EmailService emailService;
 
    @GetMapping("/send")
    public String sendEmail(@RequestParam String to, @RequestParam String subject, @RequestParam String text) {
        try {
            emailService.sendSimpleEmail(to, subject, text);
            return "Email sent successfully!";
        } catch (MessagingException e) {
            e.printStackTrace();
            return "Failed to send email.";
        }
    }
}
 

Apache Commons Email 库

添加依赖:

在你的pom.xml文件中,添加 Apache Commons Email库的依赖:

xmlCopy code
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-email</artifactId>
    <version>1.5</version> <!-- 替换为最新版本 -->
</dependency>

确保这个依赖被正确地添加到你的项目中。

配置SMTP服务器:

在你的application.propertiesapplication.yml文件中配置SMTP服务器的相关信息,例如:

propertiesCopy code
spring.mail.host=your_smtp_host
spring.mail.port=your_smtp_port
spring.mail.username=your_email@gmail.com
spring.mail.password=your_email_password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

编写发送邮件的代码

创建一个服务类,使用Apache Commons Email库发送电子邮件。以下是一个简单的例子:

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
 
@Service
public class EmailService {
 
    @Value("${spring.mail.username}")
    private String from;
 
    public void sendSimpleEmail(String to, String subject, String text) throws EmailException {
        SimpleEmail email = new SimpleEmail();
        email.setHostName("your_smtp_host");
        email.setSmtpPort(Integer.parseInt("your_smtp_port"));
        email.setAuthenticator(new DefaultAuthenticator(from, "your_email_password"));
        email.setStartTLSEnabled(true);
 
        email.setFrom(from);
        email.addTo(to);
        email.setSubject(subject);
        email.setMsg(text);
 
        email.send();
    }
}

使用服务类发送邮件

在你的控制器或其他地方调用EmailService发送邮件:

javaCopy code
@RestController
@RequestMapping("/email")
public class EmailController {
 
    @Autowired
    private EmailService emailService;
 
    @GetMapping("/send")
    public String sendEmail(@RequestParam String to, @RequestParam String subject, @RequestParam String text) {
        try {
            emailService.sendSimpleEmail(to, subject, text);
            return "Email sent successfully!";
        } catch (EmailException e) {
            e.printStackTrace();
            return "Failed to send email.";
        }
    }
}

这样,你就可以使用Apache Commons Email库发送邮件了。确保替换配置中的实际值,并根据你的需求进行定制。

以上就是SpringBoot实现发送邮件功能的三种方式的详细内容,更多关于SpringBoot发送邮件方式的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文