当前位置:   article > 正文

springboot整合javaMail_springboot javamail

springboot javamail

SMTP:简单邮件传输协议,用于发送电子邮件的协议
POP3 ( Post Office Protocol - Version3) :用于接收电子邮件的标准协议
IMAP ( Internet Mail Access Protocol) :互联网消息协议,是POP3的替代协议

第一步,引入依赖

   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
  • 1
  • 2
  • 3
  • 4

第二步 写接口与实现类

public interface MailService {
    void sendSimpleMail(String from,String to,String cc,String subject,String content);
}
  • 1
  • 2
  • 3
import com.example.rabbitmq.service.MailService;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class tomailimpl  implements MailService {

        @Resource
        JavaMailSender javaMailSender;

        /**
         * 最简单的邮件发送
         * @param from  发送方
         * @param to    接收方
         * @param cc    第三方(非必填)
         * @param subject   标题
         * @param content   内容
         */
        @Override
        public void sendSimpleMail(String from, String to, String cc, String subject, String content){
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setFrom(from);
            simpleMailMessage.setTo(to);
            simpleMailMessage.setCc(cc);
            simpleMailMessage.setSubject(subject);
            simpleMailMessage.setText(content);
            javaMailSender.send(simpleMailMessage);
        }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

第三步 配置文件

spring:
  mail:
    host: smtp.qq.com
    port: 465
    username: 发送方@qq.com
    password: QQ邮箱秘钥 不是QQ密码 
    default-encoding: UTF-8
    properties:
      mail:
        smtp:
          socketFactory:
            class: javax.net.ssl.SSLSocketFactory
        debug: true
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

测试

import com.example.rabbitmq.service.MailService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;

@SpringBootTest
class RabbitmqApplicationTests {

    @Resource
    MailService mailService;
    @Test
    public void sendSimpleMail(){
        mailService.sendSimpleMail("自己@qq.com","发送方@qq.com","发送方@qq.com","标题111","Hello World");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/95388?site
推荐阅读
相关标签
  

闽ICP备14008679号