springboot邮件服务

2020-06-02   94 次阅读


1. 导入相关依赖

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

2.pom.xml配置

spring.mail.default-encoding=utf-8
spring.mail.host=smtp.qq.com
spring.mail.password=cufznkexeecihfgb
spring.mail.username=1877067164@qq.com
#开启加密验证
spring.mail.properties.mail.smtp.ssl.enable=true

3.简单邮件发送

package cn.hm1006.springbootstudy;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import javax.annotation.Resource;

@SpringBootTest
class SpringbootstudyApplicationTests {


    @Resource
    JavaMailSenderImpl javaMailSenderImpl;
    @Test
    void MailUtils() {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject("标题");
        mailMessage.setText("内容");
        //发件人
        mailMessage.setFrom("1877067164@qq.com");
        //收件人
        mailMessage.setTo("1441786178@qq.com");
        javaMailSenderImpl.send(mailMessage);
    }
}

image.png

4.复杂邮件发送

    //复杂邮件,增加附件
    @Test
    void MailUtils2() throws Exception{
        MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject("标题");
        helper.setText("内容");
        //附件
        helper.addAttachment("1.jpg",new File("C:\\Users\\1\\Pictures\\logo.png"));

        //发件人
        helper.setFrom("1877067164@qq.com");
        //收件人
        helper.setTo("1441786178@qq.com");
        javaMailSenderImpl.send(mimeMessage);
    }

image.png

Q.E.D.

知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议

如人饮水、冷暖自知