springboot 학습 (29) springboot 으로 메 일 보 내기

일반 텍스트, html, 첨부 파일, 템 플 릿 html
1. springboot 의존 패 키 지 를 도입 합 니 다. 여 기 는 gradle 을 사용 합 니 다. maven 을 사용 하여 해당 하 는 의존 으로 바 꾸 십시오.
 compile group: 'org.springframework.boot', name: 'spring-boot-starter-mail'
 compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'
spring-boot-starter-mail 메 일 발송 spring-boot-starter-thymeleaf 템 플 릿 생 성 실현
2 resources / templates 에 템 플 릿 html: emailTemplate. html 만 들 기

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>         title>
head>
<body><br/>
<a href="#" th:href="@{http://www.lalalala.com/{userid}(userid=${userid})}">    a>
body>
html>

3 네 가지 메 일 발송 테스트 코드
package com.iscas.biz.test.controller;

import com.iscas.templet.common.BaseController;
import com.iscas.templet.common.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
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.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 *       
 *
 * @author zhuquanwen
 * @vesion 1.0
 * @date 2020/8/12 21:16
 * @since jdk1.8
 */
@RestController
@RequestMapping("/send/email/test")
@Slf4j
public class SendEmailController extends BaseController {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private TemplateEngine templateEngine;

    /**
     *           
     * */
    @GetMapping("/text")
    public ResponseEntity testText() {

        SimpleMailMessage message = new SimpleMailMessage();
        //      
        message.setFrom("[email protected]");
        //      
        message.setTo("[email protected]");
        //     
        message.setSubject("      ");
        //     
        message.setText("      ");

        javaMailSender.send(message);
        log.debug("    !");

        return getResponse();
    }

    /**
     *     HTML  
     * */
    @GetMapping("/html")
    public ResponseEntity testHtml() throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();
        //              
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        //      
        helper.setFrom("[email protected]");
        //      
        helper.setTo("[email protected]");
        helper.setSubject("  html  ");
        //   HTML  
        String html = "

"
; helper.setText(html, true); javaMailSender.send(message); log.debug(" "); return getResponse(); } /** * * */ @GetMapping("/attachment") public ResponseEntity testAttachment() throws MessagingException { MimeMessage message = javaMailSender.createMimeMessage(); // MimeMessageHelper helper = new MimeMessageHelper(message, true); // helper.setFrom("[email protected]"); // helper.setTo("[email protected]"); helper.setSubject(" "); // HTML String html = "

"
; helper.setText(html, true); // FileSystemResource file = new FileSystemResource("E:\\test\\repo1\\a.txt"); // String fileName = file.getFilename(); helper.addAttachment(fileName, file); javaMailSender.send(message); log.debug(" "); return getResponse(); } /** * thymeleaf * */ @GetMapping("/template") public ResponseEntity testTemplate() throws MessagingException { MimeMessage message = javaMailSender.createMimeMessage(); // MimeMessageHelper helper = new MimeMessageHelper(message, true); // helper.setFrom("[email protected]"); // helper.setTo("[email protected]"); helper.setSubject(" "); // html Context context = new Context(); // id resources/templates ${userid} context.setVariable("userid", 1); // "emailTemplate" resources/templates String html = templateEngine.process("emailTemplate", context); helper.setText(html, true); // FileSystemResource file = new FileSystemResource("E:\\test\\repo1\\a.txt"); // String fileName = file.getFilename(); helper.addAttachment(fileName, file); javaMailSender.send(message); log.debug(" "); return getResponse(); } }

4 메 일 을 도구 클래스 로 보 내기
package com.iscas.base.biz.service.common;

import cn.hutool.core.io.IoUtil;
import com.iscas.templet.common.ResponseEntity;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
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.web.bind.annotation.GetMapping;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 *       
 *
 * @author zhuquanwen
 * @vesion 1.0
 * @date 2020/8/12 21:52
 * @since jdk1.8
 */
@Service
@Slf4j
public class SendEmailService {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private TemplateEngine templateEngine;

    /**
     *         
     *
     * @version 1.0
     * @since jdk1.8
     * @date 2020/8/12
     * @param from       
     * @param to       
     * @param title     
     * @param content       
     * */
    public void sendText(String from, String to, String title, String content) {


        SimpleMailMessage message = new SimpleMailMessage();
        //      
        message.setFrom(from);
        //      
        message.setTo(to);
        //     
        message.setSubject(title);
        //     
        message.setText(content);

        javaMailSender.send(message);
        log.debug("      !");
    }

    /**
     *   HTML  
     * @version 1.0
     * @since jdk1.8
     * @date 2020/8/12
     * @param from       
     * @param to       
     * @param title     
     * @param html     html
     * */
    public void sendHtml(String from, String to, String title, String html) throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();
        //              
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        //      
        helper.setFrom(from);
        //      
        helper.setTo(to);
        helper.setSubject(title);
        //   HTML  
        helper.setText(html, true);

        javaMailSender.send(message);
        log.debug("      ");

    }

    /**
     *     
     *
     *
     * @version 1.0
     * @since jdk1.8
     * @date 2020/8/12
     * @param from       
     * @param to       
     * @param title     
     * @param html     html
     * @param inputStream      
     * @param fileName     
     *
     * */
    public void sendAttachment(String from, String to, String title, String html, InputStream inputStream, String fileName) throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();
        //              
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        //      
        helper.setFrom(from);
        //      
        helper.setTo(to);
        helper.setSubject(title);
        //   HTML
        helper.setText(html, true);

        //    

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IoUtil.copy(inputStream, baos);

        ByteArrayResource byteArrayResource = new ByteArrayResource(baos.toByteArray());
        //      
        helper.addAttachment(fileName, byteArrayResource);

        javaMailSender.send(message);
        log.debug("    ");

    }

    /**
     *     thymeleaf    
     * templateName   resources/templates 
     *
     * @version 1.0
     * @since jdk1.8
     * @date 2020/8/12
     * @param from       
     * @param to       
     * @param title     
     * @param templateName     ,templateName   resources/templates 
     * @param context         ,          
     * */
    @GetMapping("/template")
    public void sendTemplate(String from, String to, String title, String templateName, Context context) throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();
        //              
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        //      
        helper.setFrom(from);
        //      
        helper.setTo(to);
        helper.setSubject(title);

        //      html
        String html = templateEngine.process(templateName, context);
        helper.setText(html, true);

        javaMailSender.send(message);
        log.debug("      ");

    }

    /**
     *     thymeleaf    ,     
     * templateName   resources/templates 
     * @version 1.0
     * @since jdk1.8
     * @date 2020/8/12
     * @param from       
     * @param to       
     * @param title     
     * @param templateName     ,templateName   resources/templates 
     * @param context         ,          
     * @param inputStream      
     * @param fileName     
     * */
    public void sendTemplateWithAttachment(String from, String to, String title, String templateName, Context context, InputStream inputStream, String fileName) throws MessagingException {
        //      html
        String html = templateEngine.process(templateName, context);
        sendAttachment(from, to, title, html, inputStream, fileName);
    }
}


5 단원 테스트
package com.iscas.biz.service;

import com.iscas.base.biz.service.common.SendEmailService;
import com.iscas.biz.BizApp;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 *       
 *
 * @author zhuquanwen
 * @vesion 1.0
 * @date 2020/8/12 22:05
 * @since jdk1.8
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = BizApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EnableAutoConfiguration
public class SendEmailServiceTests {
    @Autowired
    private SendEmailService sendEmailService;
    /**
     *           
     * */
    @Test
//    @Ignore
    public void testText() {
        sendEmailService.sendText("[email protected]", "[email protected]", "      ", "      ");
    }

    /**
     *     HTML  
     * */
    @Test
//    @Ignore
    public void testHtml() throws MessagingException {
        String html = "

"
; sendEmailService.sendHtml("[email protected]", "[email protected]", " html ", html); } /** * * */ @Test // @Ignore public void testAttachment() throws MessagingException, IOException { InputStream is = new FileInputStream("E:\\test\\repo1\\a.txt"); String html = "

"
; sendEmailService.sendAttachment("[email protected]", "[email protected]", " html ", html, is, " .txt"); } /** * thymeleaf * */ @Test // @Ignore public void testTemplate() throws MessagingException { // html Context context = new Context(); // id resources/templates ${userid} context.setVariable("userid", 1); // "emailTemplate" resources/templates sendEmailService.sendTemplate("[email protected]", "[email protected]", " ", "emailTemplate", context); } /** * thymeleaf , * */ @Test // @Ignore public void testTemplateWithAttachment() throws MessagingException, IOException { // html Context context = new Context(); // id resources/templates ${userid} context.setVariable("userid", 1); // "emailTemplate" resources/templates InputStream is = new FileInputStream("E:\\test\\repo1\\a.txt"); sendEmailService.sendTemplateWithAttachment("[email protected]", "[email protected]", " ", "emailTemplate", context, is, " .txt"); } }

좋은 웹페이지 즐겨찾기