Springboot 发送邮件

Spring Boot对Mail功能已经配置了相关的基本配置,我们只需要稍加修改即可使用

官方文档:https://docs.spring.io/spring/docs/5.1.2.RELEASE/spring-framework-reference/integration.html#mail


1、加入 pom 依赖

    <!-- Spring Boot 邮件依赖 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    <!-- Spring Boot 模板依赖 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <!--jasypt配置文件加解密-->
    <dependency>
      <groupId>com.github.ulisesbocchio</groupId>
      <artifactId>jasypt-spring-boot-starter</artifactId>
      <version>2.1.1</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>org.junit.vintage</groupId>
          <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

 


2、对邮箱密码进行加密操作 

  • 在 yml 配置文件中配置上 加密密码
# 配置文件项加解密密码,此处作为测试,实际情况放在代码中(放在代码中使加密密钥和密文分开)
jasypt.encryptor.password: password
  • 生成加密密码
package ch.springboot.demo.email;

import org.jasypt.encryption.StringEncryptor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest
@RunWith(SpringRunner.class)
public class CreatePW {
    @Autowired
    private StringEncryptor stringEncryptor;

    /**
     * 生成加密密码
     */
    @Test
    public void testGeneratePassword() {
        // 你的邮箱密码
        String password = "abcdefg";
        // 加密后的密码(注意:配置上去的时候需要加 ENC(加密密码))
        String encryptPassword = stringEncryptor.encrypt(password);
        String decryptPassword = stringEncryptor.decrypt(encryptPassword);

        System.out.println("密码是 : " + password);
        System.out.println("加密后密码是 " + encryptPassword);
        System.out.println("解密后密码是 " + decryptPassword);

    }
}

console->


3、设置邮箱(以 163 为例)

  登录163邮箱后 点击设置,选择POP3

POP3/SMTP 取消打钩。然后再点打钩 弹出页面,点击确定

点击开启,需要手机发送短信验证 

发送完成后填写授权码,自定义,记住该授权码,需要在代码中配置

到此邮箱配置大功告成


4、application 配置

替换密码为加密后的 授权码,替换用户名为你的邮箱 

spring:
  mail:
    host: smtp.163.com
    username: 邮箱@163.com
    # 使用 jasypt 加密密码,替换 ENC(加密密码)
    # 此处为授权码,并非登录163邮箱的登录密码
    password: ENC(P4P5DKYUhWpuHZQUMwCXKOx+Dho3mVMN)
    protocol: smtp
    default-encoding: UTF-8
    properties:
      mail.smtp.auth: true
      mail.smtp.starttls.enable: true
      mail.smtp.starttls.required: true
      mail.smtp.ssl.enable: true
      mail.display.sendmail: password
# 配置文件项加解密密码,此处作为测试完,实际情况应该注释,而放在代码中(放在代码中使加密密钥和密文分开)
jasypt:
  encryptor:
    password: password

5、发送邮件

package ch.springboot.demo.email.service;

import javax.mail.MessagingException;

/**
 * mail 接口.
 *
 * @author ch
 * @version 1.0.0
 * @since 1.0.0
 * <p>
 * Created at 2019/11/26 10:08
 */
public interface MailService {

  /**
   * 发送文本邮件
   *
   * @param to      收件人地址
   * @param subject 邮件主题
   * @param test 邮件内容
   * @param cc      抄送地址
   */
  void sendSimpleMail(String to, String subject, String test, String... cc)
      throws MessagingException;

  /**
   * 发送HTML邮件
   *
   * @param to      收件人地址
   * @param subject 邮件主题
   * @param content 邮件内容
   * @param cc      抄送地址
   * @throws MessagingException 邮件发送异常
   */
  void sendHtmlMail(String to, String subject, String content, String... cc) throws MessagingException;


  /**
   * 发送带附件的邮件
   *
   * @param to       收件人地址
   * @param subject  邮件主题
   * @param content  邮件内容
   * @param filePath 附件地址
   * @param cc       抄送地址
   * @throws MessagingException 邮件发送异常
   */
  void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) throws MessagingException;


}
package ch.springboot.demo.email.service.impl;

import ch.springboot.demo.email.service.MailService;
import java.io.File;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

/**
 * mail 实现类.
 *
 * @author ch
 * @version 1.0.0
 * @since 1.0.0
 * <p>
 * Created at 2019/11/26 10:20 下午
 */
@Service
public class MailServiceImpl implements MailService {

  @Autowired
  private JavaMailSender mailSender;

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

  @Override
  public void sendSimpleMail(String to, String subject, String text, String... cc)
      throws MessagingException {
    SimpleMailMessage mailMessage = new SimpleMailMessage();
    // 邮箱用户名
    mailMessage.setFrom(from);
    // 邮件接收人
    mailMessage.setTo(to);
    // 设置邮件主题
    mailMessage.setSubject(subject);
    // 设置邮件内容
    mailMessage.setText(text);
    // 设置抄送人
    if (cc != null && cc.length != 0) {
      mailMessage.setCc(cc);
    }
    // 发送邮件
    mailSender.send(mailMessage);
  }

  /**
   * @param to      收件人地址
   * @param subject 邮件主题
   * @param content 邮件内容
   * @param cc      抄送地址
   * @throws MessagingException
   */
  @Override
  public void sendHtmlMail(String to, String subject, String content, String... cc)
      throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content, true);
    if (cc != null && cc.length != 0) {
      helper.setCc(cc);
    }
    mailSender.send(message);

  }

  /**
   * 发送带附件的邮件
   *
   * @param to       收件人地址
   * @param subject  邮件主题
   * @param content  邮件内容
   * @param filePath 附件地址
   * @param cc       抄送地址
   * @throws MessagingException 邮件发送异常
   */
  @Override
  public void sendAttachmentsMail(String to, String subject, String content, String filePath,
      String... cc) throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content, true);
    if (cc != null && cc.length != 0) {
      helper.setCc(cc);
    }
    FileSystemResource file = new FileSystemResource(new File(filePath));
    String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
    helper.addAttachment(fileName, file);

    mailSender.send(message);
  }

}

参考文献:https://github.com/xkcoding/spring-boot-demo/tree/master/spring-boot-demo-email

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中发送邮件需要使用JavaMailSender接口来实现。以下是一个简单的示例代码: 首先,确保在你的项目中添加了相关依赖。在pom.xml文件中添加以下代码: ```xml <dependencies> <!-- Spring Boot Starter Mail --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> </dependencies> ``` 然后,在你的应用程序中创建一个类来发送邮件。例如,你可以创建一个名为EmailSender的类: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Component; @Component public class EmailSender { @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); } } ``` 在上述示例中,我们使用了@Autowired注解来自动注入JavaMailSender对象,该对象是由Spring Boot自动配置提供的。 现在,你可以在你的应用程序的任何地方使用EmailSender类来发送邮件。例如,你可以在控制器中使用它: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class EmailController { @Autowired private EmailSender emailSender; @PostMapping("/sendEmail") public String sendEmail(@RequestBody EmailRequest emailRequest) { emailSender.sendEmail(emailRequest.getTo(), emailRequest.getSubject(), emailRequest.getText()); return "Email sent successfully!"; } } ``` 上述示例中,我们创建了一个名为EmailController的REST控制器,它接收一个包含收件人、主题和内容的EmailRequest对象,并使用EmailSender发送邮件。 请注意,你需要适当配置你的邮件服务器信息。在Spring Boot的application.properties(或application.yml)文件中添加以下配置: ```yaml spring.mail.host=your-mail-server spring.mail.port=your-mail-server-port spring.mail.username=your-username spring.mail.password=your-password spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true ``` 以上是一个简单的示例,你可以根据你的实际需求进行修改和扩展。希望对你有帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值