springboot 학습 (29) springboot 으로 메 일 보 내기
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");
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
thymeleaf로 HTML 페이지를 동적으로 만듭니다 (spring + gradle)지난번에는 에서 화면에 HTML을 표시했습니다. 이번에는 화면을 동적으로 움직여보고 싶기 때문에 입력한 문자를 화면에 표시시키고 싶습니다. 초보자의 비망록이므로 이상한 점 등 있으면 지적 받을 수 있으면 기쁩니다! ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.