欢迎来到徐庆高(Tea)的个人博客网站
磨难很爱我,一度将我连根拔起。从惊慌失措到心力交瘁,我孤身一人,但并不孤独无依。依赖那些依赖我的人,信任那些信任我的人,帮助那些给予我帮助的人。如果我愿意,可以分裂成无数面镜子,让他们看见我,就像看见自己。察言观色和模仿学习是我的领域。像每个深受创伤的人那样,最终,我学会了随遇而安。
当前位置: 日志文章 > 详细内容

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

2025年07月15日 Java
springboot 发送邮件的三种方式spring framework提供的javamailsender(与 spring 集成,推荐)使用javamail api来发送邮件(灵活,支持发送日程提醒

springboot 发送邮件的三种方式

  • spring framework提供的javamailsender(与 spring 集成,推荐)
  • 使用javamail api来发送邮件(灵活,支持发送日程提醒)
  • apache commons email 库(简便)

选择哪一种方案

  • 如果你的项目已经使用了spring框架,并且只需进行基本的邮件发送,那么使用javamailsender可能是一个方便的选择。
  • 如果你对邮件发送有较高的控制要求,或者需要满足一些特殊场景的需求,那么直接使用javamail api可能更为合适。
  • 如果你希望在简洁的api和灵活性之间取得平衡,并且不介意引入外部库,那么apache commons email库可能是一个中间的选择。

这里对比一下spring framework提供的javamailsender、使用javamail api、以及apache commons email库的优缺点:

1. javamailsender (spring framework)

优点:

  • 集成性高: javamailsender是 spring 的一部分,与spring框架的其他部分紧密集成,可以方便地与spring的其他功能一起使用。
  • 配置简单: spring boot 提供了自动配置,减少了配置的繁琐性。
  • 简化api: spring 提供了更高层次的抽象,简化了发送邮件的过程,使得代码更加清晰和简洁。

缺点:

  • 灵活性较低: 对于一些特定和高级的需求,可能需要更直接地使用javamail api或其他库,因为spring的抽象可能无法满足所有场景。
  • 较大的依赖: 如果你只是需要发送邮件,引入整个spring框架可能会显得过于庞大,特别是对于一些小型项目。

2. javamail api

优点:

  • 灵活性高: javamail api 提供了更底层、更直接的控制,可以满足各种邮件发送需求。
  • 标准化: javamail api 是java标准库的一部分,可移植性好,与java平台集成度高。

缺点:

  • 繁琐: 使用javamail api编写代码可能较为繁琐,需要更多的代码量,尤其是对于一些简单的邮件发送场景。
  • 学习曲线: 对于新手来说,学习javamail api可能需要一些时间。

3. apache commons email库

优点:

  • 简化api: apache commons email 库提供了更简单的api,相比javamail api,可以更容易地发送各种类型的电子邮件,包括html邮件等。
  • 减少样板代码: 相比javamail api,apache commons email库可以减少一些样板代码,使得代码更加简洁。

缺点:

  • 不如 javamail api灵活: 虽然简化了api,但相比javamail api,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发送邮件方式的资料请关注代码网其它相关文章!