봄 부팅 (X) - 전자 메일 예

블로그의 보내기 이메일 요약

머리말

1, 간단한 텍스트 메시지를 보내는 : 사실, 메일을 보내는 것은 네 가지 범주로 나누어, 여기에 요약, 상대적으로 간단한 조작이지만, 이전 요약하지 않았다. 2, 첨부 파일이있는 메시지를 보냅니다. 3, HTML 링크와 함께 메시지를 보낼 수 있습니다. 4, 전송 전자 메일 템플릿 렌더링.

준비

그것이 될 것입니다 동안, 예를 들어, 예를 들면, QQ 메일로가는 길 전자 메일에 대한 스스로의 예제를 완료합니다. 준비 작업은 하나의 수입 프로그램 구성에이고 다른 하나는 자신의 SMTP 메일 서비스를 열 수 있습니다, 사실은 2 장으로 나뉘어 수행해야합니다.

오픈 SMTP 서비스

하나는 자신의 사서함에 다음 버튼 설정을 찾아
그림 삽입 설명 여기
,이 계정 탭을 입력

그림 삽입 설명 여기

3 다음 POP3 / SMTP 서비스의 개통 다음과 같은 옵션을 찾을 수

그림 삽입 설명 여기

또한 다음과 같은 인증 코드를 클릭해야하고, 로컬 파일에 다음 구성 인증 코드, 다음 얻을, 저장 설정 페이지를 클릭 할 필요가 열 경우, 열려 여기에 있었다.

관련 구성의 도입

1, 메일 서비스의 도입에 따라 다르다

<!--email-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2, 전자 메일 구성의 도입

##发送邮件的配置信息
spring.mail.host=smtp.qq.com
spring.mail.port=587	//相关端口,这个
spring.mail.username=********* //这里配置自己的邮件用户名
spring.mail.password=********* //这里就是配置的授权码
spring.mail.protocol=smtp
spring.mail.needAuth=true
spring.mail.sslClass=javax.net.ssl.SSLSocketFactory	//指定加密认证方式

우리는 모든 일을 할 준비가 된이 시점에서 특정 인스턴스를 시작할 수 있습니다

간단한 문자 메시지를 보내기

일단 구성되면, 준비가 직접 클래스, 그것에 주입 JavaMailSender 자신의 정의에 대한 서비스, 여기에 코드를 붙여 넣습니다

@Autowired
private JavaMailSender mailSender;

/**
 * 发送简单的文本消息邮件
 *
 * @param subject 邮件主题
 * @param content 邮件内容
 * @param tos     目的邮箱(可以多个)
 */
public void sendSimpleMail(final String subject, final String content, final String[] tos) {
    SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
    //这里写在配置文件中了,这里应该指定自己的邮件服务器的账户
    simpleMailMessage.setFrom(environment.getProperty("mail.send.from")); //指定那个人发的
    simpleMailMessage.setTo(tos); //指定邮件发往何处
    simpleMailMessage.setSubject(subject); //指定发送邮件的主题
    simpleMailMessage.setText(content);
    mailSender.send(simpleMailMessage);
    log.info("简单文本邮件发送成功:{}", simpleMailMessage);

}

컨트롤러 테스트 코드

@RequestMapping(value = prefix + "/send/simple", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public BaseResponse sendSimpleMail(@RequestBody @Validated MailRequest mailRequest, BindingResult bindingResult) {
    BaseResponse response = new BaseResponse(StatusCode.Success);
    try {
        String checkResult = ValidatorUtils.checkResult(bindingResult);
        if (StringUtils.isNotBlank(checkResult)) {
            return new BaseResponse(StatusCode.Invalid_Params);
        }
        log.info("发送简单文本邮件参数为:{}", mailRequest);
        String[] mailTos = StringUtils.split(mailRequest.getMailTos(), ",");
		//只需要关注这个就可以,这个就是调用service的发送邮件
        mailService.sendSimpleMail(mailRequest.getSubject(), mailRequest.getContent(), mailTos);
    } catch (Exception e) {
        response = new BaseResponse(StatusCode.Fail);
        log.error("发送邮件异常:{}", e);
    }
    return response;
}

첨부 파일이있는 메일 보내기

첨부 파일이있는 메시지를 보내, 당신은 첨부 파일 주소를 구성해야

#附件文件的文件夹地址
mail.send.attachment.location.root.url=D:\\MailAttachment

##第一个附件文件的文件名和文件地址
mail.send.attachment.one.location=${mail.send.attachment.location.root.url}\\image1.jpg
mail.send.attachment.one.name=图片1.jpg

##第二个附件文件的文件名和文件地址
mail.send.attachment.two.location=${mail.send.attachment.location.root.url}\\image2.jpg
mail.send.attachment.two.name=图片2.jpg

##第三个附件文件的文件名和文件地址,这里故意将文件名弄的有点长
mail.send.attachment.three.location=${mail.send.attachment.location.root.url}\\SpringBoot邮件测试发送附件文件.docx
mail.send.attachment.three.name=SpringBoot邮件测试发送附件文件测试长文件名称的文件附件这个文件的文件名字就是怎么长不要怀疑.docx

설정 후, 실시 예에서 이용 될 수있는 MimeMessageHelper다음과 같은 특정 코드를 송신하는 완전한 형식의 메시지를 구성 :

    /**
     * 发送带有附件的邮件
     *
     * @param subject
     * @param content
     * @param tos
     */
    public void sendAttachmentMail(final String subject, final String content, final String[] tos) throws Exception {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //这里如果要发送附件,需要将第二个参数置为true,将邮件信息对象切换到多模块模式。
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
        messageHelper.setFrom(environment.getProperty("mail.send.from"));
        messageHelper.setTo(tos);
        messageHelper.setSubject(subject);
        //加入简单文本消息
        messageHelper.setText(content);
        //加入附件文件
        messageHelper.addAttachment(environment.getProperty("mail.send.attachment.one.name"), new File(environment.getProperty("mail.send.attachment.one.location")));
        messageHelper.addAttachment(environment.getProperty("mail.send.attachment.two.name"), new File(environment.getProperty("mail.send.attachment.two.location")));
        messageHelper.addAttachment(environment.getProperty("mail.send.attachment.three.name"), new File(environment.getProperty("mail.send.attachment.three.location")));

        mailSender.send(mimeMessage);
        log.info("发送带附件的邮件成功:{}", mimeMessage);

    }

컨트롤러 테스트 파일

/**
 * 发送带附件的邮件
 *
 * @param mailRequest
 * @param bindingResult
 * @return
 */
@RequestMapping(value = prefix + "/send/attachment", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public BaseResponse sendAttachmentMail(@RequestBody @Validated MailRequest mailRequest, BindingResult bindingResult) {
    BaseResponse response = new BaseResponse(StatusCode.Success);
    try {
        String checkResult = ValidatorUtils.checkResult(bindingResult);
        if (StringUtils.isNotBlank(checkResult)) {
            return new BaseResponse(StatusCode.Invalid_Params);
        }
        log.info("开始发送带有附件的邮件:{}", mailRequest);
        String[] mailTos = StringUtils.split(mailRequest.getMailTos(), ",");
		
		//只需要关注这里就好
        mailService.sendAttachmentMail(mailRequest.getSubject(), mailRequest.getContent(), mailTos);
    } catch (Exception e) {
        response = new BaseResponse(StatusCode.Fail);
        log.error("发送带附件的邮件异常,异常信息为:{}", e);
    }
    return response;
}

최종 결과는, 당신은 결과에 문제가있을 것입니다받은 찾을 수

그림 삽입 설명 여기

세 번째 문서의 파일 이름이 너무 오래 직접 왜곡, 그리고, 마지막으로 (필자는 찾을 이유가 잊어 버린) 소스를 찾는하여이 당황가 발견, 사실, 파일 이름 길이의 결과로, 열 기본 속성이 존재 아래와 같이 더 (60)보다, 그것은,이 속성을 해제 시작할 때 필요한 자동으로 분할입니다 것입니다 :

/**
 * 如果附件中指示的文件名过长,则会出现文件乱码的问题,是因为默认的属性
 * mail.mime.splitlongparameters=true所致,这里需要将其置为false
 */
@PostConstruct
public void init() {
    System.setProperty("mail.mime.splitlongparameters", "false");
}

검사 결과는 정상 후

HTML 텍스트 메시지 보내기

이러한 필요성은 기초에 전에 매개 변수를 수정

/**
 * 发送HTML类型的邮件
 *
 * @param subject
 * @param content
 * @param tos
 */
public void sendHTMLMail(final String subject, final String content, final String[] tos) throws Exception {
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
    messageHelper.setFrom(environment.getProperty("mail.send.from"));
    messageHelper.setTo(tos);
    messageHelper.setSubject(subject);
    log.info(content);
    messageHelper.setText(content, true);//第二个参数设置为true,表示为发送HTML文本

    messageHelper.addAttachment(environment.getProperty("mail.send.attachment.one.name"), new File(environment.getProperty("mail.send.attachment.one.location")));
    mailSender.send(mimeMessage);
    log.info("发送带有HTML文本的邮件成功");
}

시험하는 동안, 당신이 직접 HTML의 문자열을 얻을 수 있습니다, 그것은 보통의 HTML의 내용을 표시합니다, 이상 보냈다.

보내기 전자 메일 렌더링 thymeleaf

일부 엔터프라이즈 급 이메일 관련 지정된 템플릿을 렌더링, 발송하면,이 요약있을 것입니다. thymeleaf 예에.

1, 종속 thymeleaf의 도입

<!--thymeleaf-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2 구성 파라미터 thymeleaf

#指定模板文件的名称
mail.template.file.name=mailTempOne
##thymeleaf的配置
spring.thymeleaf.enabled=true
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
#指定模板文件的文件夹地址
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.check-template-location=true
spring.thymeleaf.check-template=false
spring.thymeleaf.cache=false

3, 간단한 템플릿

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
    <p style="font-size: larger; color: burlywood">这是我发送出来的模板邮件,以下是邮件内容:</p><br/>
    内容:<span th:text="${content}"></span><br/>
    收件人:<span th:text="${mailTos}"></span><br/>
</body>
</html>

4, 템플릿 코드를 렌더링

/**
 * 渲染HTML模板
 * @param templateFile 具体的模板文件
 * @param paramMap 需要填充的参数
 */
public String renderTemplate(final String templateFile,Map<String,Object> paramMap){
    Context context=new Context(LocaleContextHolder.getLocale());
    context.setVariables(paramMap);
    return templateEngine.process(templateFile,context);
}

5, 직접 충전 한 후, 다음 전자 우편 전송 서비스에 파일의 컨트롤러

@RequestMapping(value=prefix+"/send/template",method=RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public BaseResponse sendTemplateMail(@RequestBody @Validated MailRequest mailRequest, BindingResult bindingResult){
    BaseResponse response = new BaseResponse(StatusCode.Success);
    try {
        String checkResult = ValidatorUtils.checkResult(bindingResult);
        if (StringUtils.isNotBlank(checkResult)) {
            return new BaseResponse(StatusCode.Invalid_Params);
        }
        log.info("渲染HTML模板并发送带模板的邮件:{}",mailRequest);
        Map<String,Object> paramMap= Maps.newHashMap();
        paramMap.put("content",mailRequest.getContent());
        paramMap.put("mailTos",mailRequest.getMailTos());
        
        //获取渲染之后的HTML
        String html = mailService.renderTemplate(templateFileLocation,paramMap);

        String[] tos = StringUtils.split(mailRequest.getMailTos());
        //通过发送HTML的方式发送邮件
        mailService.sendHTMLMail(mailRequest.getSubject(),html,tos);
    } catch (Exception e) {
        response = new BaseResponse(StatusCode.Fail);
        log.error("发送HTML邮件异常,异常信息为:{}", e);
    }
    return response;
}

개요

거의 대부분의 응용 프로그램 시나리오를 덮고, 메일 작업을 전송하는 네 가지

1, 간단한 텍스트 메시지를 보낼. 2, 첨부 파일이있는 메시지를 보냅니다. 3, HTML 링크와 함께 메시지를 보낼 수 있습니다. 4, 전송 전자 메일 템플릿 렌더링.

게시 된 133 개 원래 기사 · 원 찬양 37 ·은 90000 +를 볼

추천

출처blog.csdn.net/liman65727/article/details/104348617