spring boot发邮件

1、引入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、然后在配置文件配置发送方的信息
spring:
  mail:
    host: smtp.163.com
    username: 13560524547@163.com
    password: xxxxx
    properties:
      mail:
          smtp:
            auto: true
            timeout: 25000

server:
  context-path: /demo
  port: 8088
3、创建EmailConfig,用来读取配置文件里面的发件人的信息
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;


/**
 * Created by hongzhenyue on 18/2/26.
 */
@Data
@ConfigurationProperties(prefix = "spring.mail")
@Component
public class EmailConfig {

    private String username;
}
4、创建service

EmailService:

import java.io.File;
import java.util.List;

/**
 * Created by hongzhenyue on 18/2/27.
 */
public interface EmailService {
    /**
     * 发送简单邮件
     *
     * @param sendTo  收件人地址
     * @param titel   邮件标题
     * @param content 邮件内容
     */
    public void sendSimpleMail(String sendTo, String titel, String content);

    /**
     * 发送简单邮件
     *
     * @param sendTo  收件人地址
     * @param titel   邮件标题
     * @param content 邮件内容
     * @param file    附件列表
     */
    public void sendAttachmentsMail(String sendTo, String titel, String content, List<File> file);

    /**
     * 发送模板邮件
     *
     * @param sendTo              收件人地址
     * @param titel               邮件标题
     * @param content  邮件内容
     * @param fileList  附件列表
     */
    public void sendTemplateMail(String sendTo, String titel, String content, List<File> fileList);
}
EmailServiceImpl:

import com.example.demo.config.EmailConfig;
import com.example.demo.config.VelocityEngineBean;
import com.example.demo.service.interf.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.velocity.VelocityEngineUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by hongzhenyue on 18/2/27.
 */
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private EmailConfig emailConfig;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private VelocityEngineBean velocityEngine;

    @Override
    public void sendSimpleMail(String sendTo, String title, String content) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSentDate(new Date());
        simpleMailMessage.setFrom(emailConfig.getUsername());
        simpleMailMessage.setTo(sendTo);
        simpleMailMessage.setSubject(title);
        simpleMailMessage.setText(content);
        mailSender.send(simpleMailMessage);
    }

    @Override
    public void sendAttachmentsMail(String sendTo, String titel, String content, List<File> targetFile) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(emailConfig.getUsername());
            helper.setTo(sendTo);
            helper.setSubject(titel);
            helper.setText(content, true);

            if (targetFile.size() > 0) {
                for (File fileItem : targetFile) {
                    FileSystemResource file = new FileSystemResource(fileItem);
                    helper.addAttachment(fileItem.getName(), file);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        mailSender.send(mimeMessage);
    }

    @Override
    public void sendTemplateMail(String sendTo, String titel, String content, List<File> targetFile) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(emailConfig.getUsername());
            helper.setTo(sendTo);
            helper.setSubject(titel);
            helper.setText(content);
            Map<String, Object> model = new HashMap();
            model.put("username", sendTo);
            String text = VelocityEngineUtils.mergeTemplateIntoString(
                    velocityEngine, "./src/main/resources/templates/template.vm", "UTF-8", model);
            helper.setText(text, true);

            if (targetFile.size() > 0) {
                for (File fileItem : targetFile) {
                    FileSystemResource file = new FileSystemResource(fileItem);
                    helper.addAttachment(fileItem.getName(), file);
                }
            }
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
在项目的resource/templates/下面新建一个template.vm的模版,模版内容以html的形式编写
<html>
<body>
<h3>你好, ${username}, 这是一封模板邮件!</h3>
</body>
</html>

5、最后,编写controller
import com.example.demo.service.interf.EmailService;
import com.example.demo.utils.ResultVOUtil;
import com.example.demo.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by hongzhenyue on 18/2/28.
 */
@RestController
public class EmailController {
    @Autowired
    private EmailService emailService;

    @RequestMapping(value = "/getTestDemoEmail")
    public ResultVO testEmail() {
        String sendTo = "535283049@qq.com";
        String titel = "测试邮件标题";
        String content = "测试邮件内容";
        emailService.sendSimpleMail(sendTo, titel, content);
        return ResultVOUtil.success();
    }

    @RequestMapping(value = "/getTestDemoEmail2")
    public ResultVO testEmail2() {
        String sendTo = "535283049@qq.com";
        String titel = "主题:嵌入静态资源";
        String content = "<html><body>测试html</body></html>";
        List<File> fileList = new ArrayList<>();
        fileList.add(new File("/Users/hongzhenyue/Desktop/backup/spring_boot_demo/src/main/resources/file/logo.png"));
        fileList.add(new File("/Users/hongzhenyue/Desktop/backup/spring_boot_demo/src/main/resources/file/test.pdf"));
        emailService.sendAttachmentsMail(sendTo, titel, content, fileList);
        return ResultVOUtil.success();
    }

    @RequestMapping(value = "/getTestDemoEmail3")
    public ResultVO testEmail3() {
        String sendTo = "535283049@qq.com";
        String titel = "主题:嵌入静态资源";
        String content = "<html><body>测试html</body></html>";

        List<File> fileList = new ArrayList<>();
        fileList.add(new File("/Users/hongzhenyue/Desktop/backup/spring_boot_demo/src/main/resources/file/logo.png"));
        fileList.add(new File("/Users/hongzhenyue/Desktop/backup/spring_boot_demo/src/main/resources/file/test.pdf"));

        emailService.sendTemplateMail(sendTo, titel, content, fileList);
        return ResultVOUtil.success();
    }
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值