【Springboot实战】发送邮件

摘要:
          项目中,有可能需要通过一个请求,然后想客户或者某某的邮箱发送邮件。本章将介绍如何通过springboot来发送邮件。
 

第一步:pom文件中引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.jp</groupId>
    <artifactId>giftshow</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
    </parent>
    <properties>
        <druid.version>1.0.26</druid.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <!--制作发送邮件的模板用-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                    <showWarnings>true</showWarnings>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

 这里依赖的spring-boot-starter-mail是springframework中的JavaMailSender 来实现邮件发送。springboot会自动对其进行配置

第二步:配置yml文件

application.yml
server:
  port: 8081

spring:
  mail:
    host: smtp.163.com #发送邮件服务器
    username: ****@163.com #你的邮箱地址
    password: 123RYGGQ321  #邮箱里设置的授权码,不是登录密码,授权码需要自己到邮箱里面设置
    protocol: smtp #发送邮件协议
#    properties.mail.smtp.auth: true
#    properties.mail.smtp.port: 994 #465或者994
#    properties.mail.display.sendmail: aaa #可以任意
#    properties.mail.display.sendname: bbb #可以任意
#    properties.mail.smtp.starttls.enable: true
#    properties.mail.smtp.starttls.required: true
#    properties.mail.smtp.ssl.enable: true #开启SSL
    default-encoding: utf-8
  #制作邮件的模板
  freemarker:
      cache: false # 缓存配置 开发阶段应该配置为false 因为经常会改
      suffix: .html # 模版后缀名 默认为ftl
      charset: UTF-8 # 文件编码
      template-loader-path: classpath:/templates/email/  # 存放模板的文件夹,以resource文件夹为相对路径

第三步:创建启动类:

@SpringBootApplication
public class ApplicationRunner{
    public static void main(String[] args) {
        SpringApplication.run(ApplicationRunner.class, args);
    }
}

第四步:创建controller,实现邮件发送功能

package com.qq.test.controller;

import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;


@RestController
public class TestController {
  @Autowired
  private JavaMailSender mailSender;

  /**
   * 发送最简单的邮件,仅发送文字
  **/
  @GetMapping("/email")
  public String sendEmail() {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo("your_email@163.com");
    message.setFrom("to_person@163.com");
    message.setSubject("邮件测试");
    message.setText("你收到一条邮件");

    mailSender.send(message);
    return String.format("emial is sent!");
  }

  /**
   * 发送html格式的邮件
  **/
  @GetMapping("/htmlemail")
  public void sendHtmlMail(){
    MimeMessage message = mailSender.createMimeMessage();
    String content="<html>\n"+
        "<body>\n"+
        "<h3>hello 明天要加油哦!</h3>\n"+
        "</body>\n"+
        "</html>";
    try {
      MimeMessageHelper helper = new MimeMessageHelper(message,true);
      helper.setTo("your_email@163.com");
      helper.setFrom("to_person@163.com");
      helper.setSubject("邮件测试");
      helper.setText(content,true);
      mailSender.send(message);

    } catch (MessagingException e) {
      e.printStackTrace();
    }
  }

  @Autowired
  private FreeMarkerConfigurer freeMarkerConfigurer;
  /**
   * 发送一个freemark制作的html模板作为邮件内容的邮件。
  **/
  @GetMapping("/tempemail")
  public void sendFreemarkMail() throws Exception{
    // 获得模板
    Template template = freeMarkerConfigurer.getConfiguration().getTemplate("temp1.html");
    // 使用Map作为数据模型,定义属性和值
    Map<String,Object> model = new HashMap<>();
    model.put("myname","ZYF");
    // 传入数据模型到模板,替代模板中的占位符,并将模板转化为html字符串
    String templateHtml = FreeMarkerTemplateUtils.processTemplateIntoString(template,model);

    // 该方法本质上还是发送html邮件,调用之前发送html邮件的方法
    MimeMessage message = mailSender.createMimeMessage();
    try {
      MimeMessageHelper helper = new MimeMessageHelper(message,true);
      helper.setTo("your_email@163.com");
      helper.setFrom("to_person_email@163.com");
      helper.setSubject("邮件测试");
      helper.setText(templateHtml,true);
      mailSender.send(message);

    } catch (MessagingException e) {
      e.printStackTrace();
    }
  }


}

模板temp1.html内容

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8" />
  <title>freemarker简单示例</title>
</head>
<body>
<h1>Hello Freemarker</h1>
<div>My name is ${myname}</div>
</body>
</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值