Springboot整合JavaMail实现邮件发送

 简单邮件发送:

1.在pom.xml中导入依赖

第一个是springboot整合javamail,第二个是javamail的jar包,理论上只导入第一个就行了,但是jdk17会报错说找不到javax.mail,原因可能是maven导入的是jarkata.mail,名字不匹配。暂时解决方案是重新导入javax.mail包。


    org.springframework.boot
    spring-boot-starter-mail


    javax.mail
    javax.mail-api
    1.6.2

2.编写配置文件application.yml

  • host:发送协议.邮件供应商

  • username:发件人邮箱名

  • password:POP3/SMTP授权码,不是邮箱密码!

spring:
    mail:
        host: smtp.qq.com
        username: [email protected]
        password: asdffghjkl

3.编写service接口及其实现类

MailService.java

public interface MailService {
    public void sendMail();
}

MailServiceImpl.java

@Service
public class MailServiceImpl implements MailService {
    @Autowired
    private JavaMailSender javaMailSender;		

    //发送人
    private String from = "[email protected]";
    //接收人
    private String to = "[email protected]";
    //标题
    public String subject = "test title";
    //正文
    public String text = "test text...";

    @Override
    public void sendMail() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        javaMailSender.send(message);
    }
}

最后在测试类中调用MailService的sendMail方法即可。

你可能感兴趣的:(Springboot,java,spring,boot)