Spring Boot (17) 发送邮件

添加依赖

        <!--发送邮件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

在application.yml中设置发送账号


spring:
mail:
host: smtp.163.com
username: **********
password: **********

简单发送

    @Autowired
    private JavaMailSender javaMailSender;
    
    @GetMapping("/send")
    public String sendMail(){
        try{
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("****@163.com");
            message.setTo("853020304@qq.com");
            message.setSubject("hi i'm david");
            message.setText("this is  my first spring boot email");
            javaMailSender.send(message);
            return "success";
        }catch (Exception ex){
            return "faild";
        }
    }

 

发送含附件的

@GetMapping("/sendMailFile")
    public String sendMailFile() throws MessagingException {
        //需要创建一个MimeMessageHelper对象,相关参数和简单邮件类似
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom("18511500@163.com");
        helper.setTo("85302030@qq.com");
        helper.setSubject("邮件标题");
        //将邮件内容设置为html格式
        helper.setText("<html><body><h1>hello world</h1></body></html>",true);
        //定义文件,这是java.main.resources也就是classpach路径下的文件
        ClassPathResource file = new ClassPathResource("/shizi.jpg");
        //添加附件文件
        helper.addAttachment("shizi.jpg", file);
        javaMailSender.send(mimeMessage);
        return "success";
    }

 

posted @ 2018-05-30 17:19  海盗船长  阅读(208)  评论(0编辑  收藏  举报