Java邮件发送

2021/7/14 17:05:54

本文主要是介绍Java邮件发送,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1、导入依赖

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

<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>

2、添加yml配置文件

spring:
  mail:
    # 服务器地址 qq邮箱的为smtp.qq.com,163邮箱则为smtp.163.com
    host: smtp.qq.com
    # 服务协议
    protocol: smtp
    # 编码
    default-encoding: UTF-8
    # 发送方邮件的账户
    username: 10001@qq.com
    #授权码 QQ邮箱–>邮箱设置–>账户,下滑找到POP3/IMAP/SMTP/Exchange/CardDav/CalDav服务,开启POP3/SMTP服务 下方有生成授权码的提示,生成一组授权码16位授权码
    password: kcsusbogbwhudizb
    test-connection: true
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true

3、添加一个实体类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class EmailModel {

    /**
     * 主题
     */
    private String subject;

    /**
     * 内容
     */
    private String text;

    /**
     * 接收人邮箱列表
     */
    private String[] tos;
}

4、添加一个接口

public interface EmailService {

    void sendEmail(EmailModel emailModel);
}

5、添加接口实现类

@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender mailSender;

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

    @Override
    public void sendEmail(EmailModel emailModel) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setSubject(emailModel.getSubject());
        message.setText(emailModel.getText());
        message.setTo(emailModel.getTos());
        mailSender.send(message);
    }
}

6、添加前端控制器接口

import com.example.fullspeedmanageback.model.EmailModel;
import com.example.fullspeedmanageback.service.EmailService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@RequestMapping("/email")
public class EmailController {

    @Autowired
    private EmailService emailService;

    @PostMapping("/sendEmail")
    public void sendEmail(EmailModel emailModel) {
        emailService.sendEmail(emailModel);
    }


这篇关于Java邮件发送的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程