java-springboot整合发送邮件|告警邮件|注册邮件

一、基础知识

邮件传输协议:

  • SMTP协议(简单邮件传输协议,属于TCP/IP协议簇,应用层协议)
  • POP3协议(邮局协议版本3,是TCP/IP协议族中的一员,本协议主要用于支持使用客户端远程管理在服务器上的电子邮件。提供了SSL加密的POP3协议被称为POP3S)
  • IMAP协议(邮件客户端(可以通过这种协议从邮件服务器上获取邮件的信息,下载邮件等它与POP3协议的主要区别是用户可以不用把所有的邮件全部下载,可以通过客户端直接对服务器上的邮件进行操作。 )
  • Mime协议

发送流程:
java-springboot整合发送邮件|告警邮件|注册邮件_第1张图片

springboot
请自行参考其他博客

二、项目起步

1.使用maven创建springboot项目/注册邮箱开通pop3stmp
java-springboot整合发送邮件|告警邮件|注册邮件_第2张图片

2.添加,导入主要依赖

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

3.添加相关配置参数application

spring.mail.host=smtp.126.com
spring.mail.username=********@126.com
#注意:需要126开通授权码服务填入下面
spring.mail.password=*****
spring.mail.default-encoding=UTF-8

4.发送邮件服务示例

import com.honghe.managerTool.service.SendMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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 javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @author: zhaojianyu
 * @create: 2018-09-10 10:43
 **/
@Service
public class SendMailServiceImpl implements SendMailService{

    @Value("${spring.mail.username}")
    private String whoAmI;

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 发送简单邮件
     * @param to 发送给谁
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        message.setFrom(whoAmI);
        mailSender.send(message);
    }

    /**
     * 发送html邮件
     * @param to
     * @param subject
     * @param content
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message,true);
            helper.setTo(to);
            helper.setFrom(whoAmI);
            helper.setSubject(subject);
            helper.setText(content,true);
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

    /**
     * 发送附件邮件
     * @param to
     * @param subject
     * @param content
     * @param filePath
     */
    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message,true);
            helper.setTo(to);
            helper.setFrom(whoAmI);
            helper.setSubject(subject);
            helper.setText(content,true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = file.getFilename();
            //此处可以添加多个附件 zjy0910
            helper.addAttachment(fileName,file);

            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送图片邮件
     * @param to
     * @param subject
     * @param content
     * @param rscPath 图片路径
     * @param rscId
     */
    @Override
    public void sendInlinResourceMail(String to, String subject, String content,
										     String rscPath, String rscId) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(to);
            helper.setFrom(whoAmI);
            helper.setSubject(subject);
            helper.setText(content,true);

            //可以添加多个图片
            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId,res);

            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

}

使用方法

	//发送简单邮件
    sendMailService.sendSimpleMail("ai10*****[email protected]","标题","内容");
    //发送html邮件
    String content = "\n" +
         "\n"
         +"

html邮件内容


火车开走了□□□□□□□o0O```\n"
+""; sendMailService.sendHtmlMail("1******[email protected]","给你的",content); //发送附件邮件示例 sendMailService.sendAttachmentsMail("117***[email protected]","给你的",content,"C:\\Users\\Administrator\\Pictures\\999.jpg"); //发送图片邮件示例 String resId ="id001"; String content = "\n" + "

html邮件内容


+resId+"\'>" + ""; //发图片邮件 sendMailService.sendInlinResourceMail("ai*****[email protected]","标题", content,"C:\\Users\\Administrator\\Pictures\\\\999.jpg",resId);

常见异常处理

javax.mail.AuthenticationFailedException: 535 authentication failed

邮件模板

1.添加依赖

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

2.创建模板邮件内容,文件名 ,文件目录如下
java-springboot整合发送邮件|告警邮件|注册邮件_第3张图片

3.html文件编写(采用thymeleaf)


<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>告警邮件title>
head>
<body>
    您好,您的服务器磁盘或内存达到危险值,请检查服务器内存和磁盘情况!<br>
    <a href="#" th:href="@{https://www.baidu.com/}">进入查看a>
    <a href="#" th:href="@{https://www.baidu.com/{id}(id=${id})}">进入查看2a>
body>
html>

4.服务层编写(采用发送html邮件的方法)

	/**
     * 发送html邮件
     * @param to
     * @param subject
     * @param content
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message,true);
            helper.setTo(to);
            helper.setFrom(whoAmI);
            helper.setSubject(subject);
            helper.setText(content,true);
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

5.控制层代码展示

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
{
	@Autowired
    private SendMailService sendMailService;

    @Autowired
    //注入模板引擎
    private TemplateEngine templateEngine;

    @RequestMapping("/test")
    public Object test(){
        Context context = new Context();
		//给模板html内注入值
        context.setVariable("id","006");
		//获取html内容
        String emailContent = templateEngine.process("emailTemplate",context);
        //发送邮件
        sendMailService.sendHtmlMail("ai******[email protected]","模板邮件-邮件主题",emailContent);
        return "ok";
    }
}

666666.成果展示
java-springboot整合发送邮件|告警邮件|注册邮件_第4张图片


与本文类似的相关参考

你可能感兴趣的:(后端/java/web框架)