春ブーツ+ JavaMailSender + Thymeleafは、メールを送信するサーバーを実装します

春Boot-は郵送を達成します


メールサービスは何ですかWhat-

初期のインターネットメールサービスでは、浮上している、そして今、インターネットは不可欠な寿命となっています。それでは、どのメールサービスの仕事はありますか?典型的なプロセスは、メッセージの送信および受信の下に与えられている:
1、送信者メールサーバAへのメッセージを転送するSMTPプロトコルを使用して、
図2に示すように、メールサーバを指定された受信者のメッセージ、対応するメールサーバBへのメッセージ配信に応じて、
3。 、受信者は、メールサーバBからのメールを受信するPOP3プロトコルを使用しています
SMTP(簡易メール転送プロトコル)RFC5321で定義されている、インターネット標準のメール(Eメール)の送信で、デフォルトのポート25を使用して、
POP3(ポストオフィスプロトコル-バージョン3)は、主に、サーバ上の電子クライアントリモート管理の使用をサポートするために使用されますメール。POPプロトコル(最新版)の第3版のために、RFC 1939で定義されています。
これら2つのプロトコルは、アプリケーション層プロトコルのTCP / IPプロトコルスイートです、それはTCP層の上に実行されます。
私たちは、日々のメールクライアントを使用して、ウェブメールは、これら二つの協定、メールの送受信の処理が完了した走行時の後ろにあります。そして今、我々は、ユーザーのメールサーバーに送信されるメッセージを送信するためにSMTPプロトコルを使用する必要があります。
クライアントからサーバーへの転送メッセージは、両側の協力、およびSMTPプロトコルで定義されたルールが必要です。私たちは今、SMTPサーバーを見つけ、その後、SMTPクライアントを実装して、クライアントがサーバーにメッセージを送信してみましょうで行う必要があります。


Why-システムがメールサービスを確立することである理由

世界中のEメールは、共通のプロトコルを持っています。つまり、あなたのメールをチェックするためにどのような方法で任意の電子メールクライアントを使用することができます。:世界の終わりにEメールクライアント未満1000種類、人口のさまざまなニーズを満たすためにさまざまな方法でそれらのすべては、メッセージには、次のような特徴を持っている
①企業内のコミュニケーションを、またはメールサービスは、インスタントメッセージングよりも「公式」と考えられています「信頼できます。」
②支持転送/ ccで、オープン、ユニファイドコミュニケーションプロトコルは、アーカイブすることができます。


メールサービスを実現する方法Why-

  • メールサーバを設定します

認証コードを設定されています:オープンSMTPサーバ、認証コードを設定し、その後の書き込みコードは、次のようなメール以外のパスワードが、認証コードでパスワードを、コーディング、認証コードを変更する必要があります123456


  • 実現のメールクライアント

①のGradleは春メール依存性を追加しました

compile group: 'org.springframework.boot', name: 'spring-boot-starter-mail'

②、application.propertiesを変更するメールボックスの設定を追加

##################################---Spring Mail发送邮件---##############################################
# JavaMailSender 邮件发送的配置
spring.mail.default-encoding=UTF-8 
spring.mail.host=smtp.163.com
spring.mail.port=465
[email protected]
# 邮箱开启的授权码
spring.mail.password=123456
spring.mail.properties.smtp.auth=true
spring.mail.properties.smtp.starttls.enable=true
spring.mail.properties.smtp.starttls.required=true
spring.mail.properties.mail.smtp.ssl.enable=true

  • プレーンテキストメッセージの送信に対応していたコード、HTML形式の電子メール、電子メールの添付ファイル、thymeleafテンプレートメッセージの種類を書くJavaMailUtil電子メールツールを送信します。
package com.javalsj.blog.mail;

import java.io.File;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.javalsj.blog.common.FileUtil;

/**
 * @description 发送邮件工具,支持发送纯文本邮件、html邮件、附件邮件、thymeleaf模板邮件类型。
 * @author WANGJIHONG
 * @date 2018年3月14日 下午10:17:40
 * @Copyright 版权所有 (c) www.javalsj.com
 * @memo 无备注说明
 */
@Component
public class JavaMailUtil {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * Java邮件发送器
     */
    @Autowired
    private JavaMailSender mailSender;

    /**
     * thymeleaf模板引擎
     */
    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 发送不含附件,且不含嵌入html静态资源页面的纯文本简单邮件
     * 
     * @param deliver
     *            发送人邮箱名 如: [email protected]
     * @param receiver
     *            收件人,可多个收件人 如:[email protected],[email protected]
     * @param carbonCopy
     *            抄送人,可多个抄送人 如:[email protected]
     * @param subject
     *            邮件主题 如:您收到一封高大上的邮件,请查收。
     * @param text
     *            邮件内容 如:测试邮件逗你玩的。
     */
    public void sendSimpleEmail(String deliver, String[] receivers, String[] carbonCopys, String subject, String text)
            throws Exception {
        sendMimeMail(deliver, receivers, carbonCopys, subject, text, false, null);
    }

    /**
     * 发送含嵌入html静态资源页面, 但不含附件的邮件
     * 
     * @param deliver
     *            发送人邮箱名 如: [email protected]
     * @param receivers
     *            收件人,可多个收件人 如:[email protected],[email protected]
     * @param carbonCopys
     *            抄送人,可多个抄送人 如:[email protected]
     * @param subject
     *            邮件主题 如:您收到一封高大上的邮件,请查收。
     * @param text
     *            邮件内容 如: <html><body>
     *            <h1>213123</h1></body></html>
     */
    public void sendHtmlEmail(String deliver, String[] receivers, String[] carbonCopys, String subject, String text)
            throws Exception {
        sendMimeMail(deliver, receivers, carbonCopys, subject, text, true, null);
    }

    /**
     * 发送含附件,但不含嵌入html静态资源页面的邮件
     * 
     * @param deliver
     *            发送人邮箱名 如: [email protected]
     * @param receivers
     *            收件人,可多个收件人 如:[email protected],[email protected]
     * @param carbonCopys
     *            抄送人,可多个抄送人 如:[email protected]
     * @param subject
     *            邮件主题 如:您收到一封高大上的邮件,请查收。
     * @param text
     *            邮件内容 如:测试邮件逗你玩的。
     * @param attachmentFilePaths
     *            附件文件路径 如:http://www.javalsj.com/resource/test.jpg,
     *            http://www.javalsj.com/resource/test2.jpg
     */
    public void sendAttachmentsEmail(String deliver, String[] receivers, String[] carbonCopys, String subject,
            String text, String[] attachmentFilePaths) throws Exception {
        sendMimeMail(deliver, receivers, carbonCopys, subject, text, false, attachmentFilePaths);
    }

    /**
     * 发送含附件,且含嵌入html静态资源页面的邮件
     * 
     * @param deliver
     *            发送人邮箱名 如: [email protected]
     * @param receivers
     *            收件人,可多个收件人 如:[email protected],[email protected]
     * @param carbonCopys
     *            抄送人,可多个抄送人 如:[email protected]
     * @param subject
     *            邮件主题 如:您收到一封高大上的邮件,请查收。
     * @param text
     *            <html><body><img src=\"cid:test\"><img
     *            src=\"cid:test2\"></body></html>
     * @param attachmentFilePaths
     *            附件文件路径 如:http://www.javalsj.com/resource/test.jpg,
     *            http://www.javalsj.com/resource/test2.jpg
     *            需要注意的是addInline函数中资源名称attchmentFileName需要与正文中cid:attchmentFileName对应起来
     */
    public void sendHtmlAndAttachmentsEmail(String deliver, String[] receivers, String[] carbonCopys, String subject,
            String text, String[] attachmentFilePaths) throws Exception {
        sendMimeMail(deliver, receivers, carbonCopys, subject, text, true, attachmentFilePaths);
    }

    /**
     * 发送thymeleaf模板邮件
     * 
     * @param deliver
     *            发送人邮箱名 如: [email protected]
     * @param receivers
     *            收件人,可多个收件人 如:[email protected],[email protected]
     * @param carbonCopys
     *            抄送人,可多个抄送人 如:[email protected]
     * @param subject
     *            邮件主题 如:您收到一封高大上的邮件,请查收。
     * @param thymeleafTemplatePath
     *            邮件模板 如:mail\mailTemplate.html。
     * @param thymeleafTemplateVariable
     *            邮件模板变量集 
     */
    public void sendTemplateEmail(String deliver, String[] receivers, String[] carbonCopys, String subject, String thymeleafTemplatePath,
            Map<String, Object> thymeleafTemplateVariable) throws Exception {
        String text = null;
        if (thymeleafTemplateVariable != null && thymeleafTemplateVariable.size() > 0) {
            Context context = new Context();
            thymeleafTemplateVariable.forEach((key, value)->context.setVariable(key, value));
            text = templateEngine.process(thymeleafTemplatePath, context);
        }
        sendMimeMail(deliver, receivers, carbonCopys, subject, text, true, null);
    }

    /**
     * 发送的邮件(支持带附件/html类型的邮件)
     * 
     * @param deliver
     *            发送人邮箱名 如: [email protected]
     * @param receivers
     *            收件人,可多个收件人 如:[email protected],[email protected]
     * @param carbonCopys
     *            抄送人,可多个抄送人 如:[email protected]
     * @param subject
     *            邮件主题 如:您收到一封高大上的邮件,请查收。
     * @param text
     *            邮件内容 如:测试邮件逗你玩的。 <html><body><img
     *            src=\"cid:attchmentFileName\"></body></html>
     * @param attachmentFilePaths
     *            附件文件路径 如:
     *            需要注意的是addInline函数中资源名称attchmentFileName需要与正文中cid:attchmentFileName对应起来
     * @throws Exception
     *             邮件发送过程中的异常信息
     */
    private void sendMimeMail(String deliver, String[] receivers, String[] carbonCopys, String subject, String text,
            boolean isHtml, String[] attachmentFilePaths) throws Exception {
        StopWatch stopWatch = new StopWatch();
        try {
            stopWatch.start();
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(deliver);
            helper.setTo(receivers);
            helper.setCc(carbonCopys);
            helper.setSubject(subject);
            helper.setText(text, isHtml);
            // 添加邮件附件
            if (attachmentFilePaths != null && attachmentFilePaths.length > 0) {
                for (String attachmentFilePath : attachmentFilePaths) {
                    File file = new File(attachmentFilePath);
                    if (file.exists()) {
                        String attachmentFile = attachmentFilePath
                                .substring(attachmentFilePath.lastIndexOf(File.separator));
                        long size = FileUtil.getDirSize(file);
                        if (size > 1024 * 1024) {
                            String msg = String.format("邮件单个附件大小不允许超过1MB,[%s]文件大小[%s]。", attachmentFilePath,
                                    FileUtil.formatSize(size));
                            throw new RuntimeException(msg);
                        } else {
                            FileSystemResource fileSystemResource = new FileSystemResource(file);
                            helper.addInline(attachmentFile, fileSystemResource);
                        }
                    }
                }
            }
            mailSender.send(mimeMessage);
            stopWatch.stop();
            logger.info("邮件发送成功, 花费时间{}秒", stopWatch.getTotalTimeSeconds());
        } catch (Exception e) {
            logger.error("邮件发送失败, 失败原因 :{} 。", e.getMessage(), e);
            throw e;
        }
    }

}

  • コントローラ送られたシンプルなテキストメッセージを書きます
@RequestMapping(value = "/sendSimpleEmail", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Result sendSimpleEmail() {
        Result result;
        try {
            javaMailUtil.sendSimpleEmail("[email protected]", new String[] { "[email protected]", "[email protected]" },
                    new String[] { "[email protected]" }, "您收到一封高大上的邮件,请查收。", "测试邮件逗你玩的。");
            result = ResultFactory.buildSuccessResult(null);
        } catch (Exception e) {
            result = ResultFactory.buildFailResult(e.getMessage());
        }
        return result;
    }

 


  • 電子メールテンプレートエンジン書かれたページを送信

mailTemplate.htmlページのコード:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
    xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>邮件模板</title>
</head>
<body>
    <div>
        用户名:<input th:text="${username}"/> <br /> 
        密码: <input th:text="${password}"/>
    </div>
</body>
</html>

コントローラのテストコード:

@RequestMapping(value = "/sendTemplateEmail", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Result sendTemplateEmail() {
        Result result = null;
        try {
            String thymeleafTemplatePath = "mail/mailTemplate";
            Map<String, Object> thymeleafTemplateVariable = new HashMap<String, Object>();
            thymeleafTemplateVariable.put("username", "javalsj");
            thymeleafTemplateVariable.put("password", "123456");
            javaMailUtil.sendTemplateEmail("[email protected]", 
                    new String[] { "[email protected]", "[email protected]" },
                    new String[] { "[email protected]" }, 
                    "您收到一封高大上的邮件,请查收。",
                    thymeleafTemplatePath,
                    thymeleafTemplateVariable);
            result = ResultFactory.buildSuccessResult(null);
        } catch (Exception e) {
            result = ResultFactory.buildFailResult(e.getMessage());
        }
        return result;
    }

 


概要

ここで使用されるように、春ブーツ+ JavaMailSender + Thymeleafが実装による春のブートデフォルトのテンプレートエンジンにプレーンテキストメッセージ、HTML形式の電子メール、電子メールの添付ファイルや電子メールThymeleafのテンプレート機能を、送信するためにサーバがThymeleafあるので、この記事を加えることなく、Thymeleafはできるデフォルトの自動設定を使用します一人でThymeleafの構成。

おすすめ

転載: blog.csdn.net/ryuenkyo/article/details/91379115