(入门SpringBoot)SpringBoot发送邮件(十一)

SpringBoot配置邮件服务:

1.引入jar

 

 

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-mailartifactId>
dependency>

2.配置资源文件,邮箱参数:

#邮件:邮件服务器
spring.mail.host=smtp.163.com
#发件人邮箱
spring.mail.username=xxx@163.com
#授权码:
spring.mail.password=abc123
#编码:
spring.mail.default-encoding=UTF-8

3.准备发送邮件方法:

service层读取配置文件参数,注入JavaMailSender

@Value("${spring.mail.username}")
private String sender; //读取配置文件中的参数
@Autowired
private JavaMailSender mailSender; //自动注入的Bean

 

/**
 * 发送普通文本:
 * @param to 发送人:
 * @param subject 发送标题:
 * @param context  发送内容:
 */
@Override
public void sendSimpleMail(String to, String subject, String context) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(sender);
    message.setTo(to);
   message.setSubject(subject);
   message.setText(context);
   mailSender.send(message);

}

/**
 * 发送html:
 * @param to 发送人:
 * @param subject 发送标题:
 * @param context  发送内容:
 */
@Override
public void sendSimpleMailHTML(String to, String subject, String context) {
    MimeMessage message = null;
    try {
        message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(sender);
        helper.setTo(to);
        helper.setSubject("标题:发送Html内容");

        StringBuffer sb = new StringBuffer();
        sb.append("

大标题-h1

")
                .append("

红色字

"
)
                .append("

右对齐

"
);
        helper.setText(sb.toString(), true);
    } catch (Exception e) {
        e.printStackTrace();
    }
    mailSender.send(message);
}

 推荐学习网址:https://github.com/ityouknow/awesome-spring-boot

 

 

你可能感兴趣的:((入门SpringBoot)SpringBoot发送邮件(十一))