java ssl加密发送邮件

通过25端口发送邮件不安全,改为ssl加密方式发送邮件,比较常见的2中实现类发送邮件如下所示。

1、JavaMailSenderImpl 类

使用该实现类发送邮件,ssl加密使用端口号为465,借助Properties类设置ssl的各种配置。

复制代码
		SysUserEntity user = userService.getById(fromUserId);
        JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        senderImpl.setHost(user.getEmailHost());
        senderImpl.setUsername(user.getEmail());
        senderImpl.setPassword(user.getEmailPw());
        senderImpl.setDefaultEncoding("UTF-8");
        senderImpl.setJavaMailProperties(props);
        Properties properties = new Properties();
        //properties.setProperty("mail.debug", "true");//启用调试
        //properties.setProperty("mail.smtp.timeout", "1000");//设置链接超时
        //设置通过ssl协议使用465端口发送、使用默认端口(25)时下面三行不需要
        properties.setProperty("mail.smtp.auth", "true");//开启认证
        properties.setProperty("mail.smtp.socketFactory.port", "465");//设置ssl端口
        properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        senderImpl.setJavaMailProperties(properties);

        MimeMessage message = senderImpl.createMimeMessage();

        //true表示需要创建一个multipart message
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(user.getEmail());
        helper.setTo(to.split(","));
        helper.setSubject(subject);
        helper.setText(content + Constant.SIGNATURE_STR, true);

        senderImpl.send(message);
        log.info("邮件发送成功");

        //保存发送日志
        mailLogEntity.setCreateUserId(Constant.SUPER_ADMIN);
        mailLogEntity.setCreateUserOrgNo(Constant.SUPER_ADMIN_ORG);
        mailLogEntity.setSender(user.getEmail());
        mailLogEntity.setType(Constant.USER_SEND);
        result = true;

2、JavaMailSender类

网上资料较少,自己记录一下。

修改application.yml文件配置

复制代码
spring:
	mail:
	    host: xxx邮件系统服务器域名或Ip
	    port: 465
	    username: xxx账号
	    password: xxx
	    default-encoding: UTF-8
	    # 这里填发送邮箱对应的SMTP地址 ,忽略证书,信任域名
	    properties:
	      mail.smtp.ssl.trust: 邮件系统服务器域名或Ip
	      mail.smtp.auth: true
	      mail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactory
	      mail.smtp.socketFactory.port: 465
	      mail.smtp.starttls.enable: true
	      mail.smtp.starttls.required: true

至于能否都采用第二种方式来实现,没做测试。

相关推荐
2401_8414956410 小时前
【数据结构】基于Prim算法的最小生成树
java·数据结构·c++·python·算法·最小生成树·prim
木井巳11 小时前
[Java数据结构和算法] HashMap 和 HashSet
java·数据结构·1024程序员节
祈祷苍天赐我java之术12 小时前
解析常见的限流算法
java·数据结构·算法
摇滚侠12 小时前
IDEA 启动前端项目 IDEA 切换分支
java·ide·intellij-idea
元直数字电路验证12 小时前
Jakarta EE开发中,如何配置IntelliJ IDEA的远程调试?
java·eureka·intellij-idea
石头wang12 小时前
idea字体的问题(idea应用本身的字体问题)
java·ide·intellij-idea
孔明兴汉13 小时前
第一章-第三节-Java开发环境配置
java·开发语言
小王不爱笑13214 小时前
Java 核心知识点查漏补缺(一)
java·开发语言·python
空空kkk14 小时前
Java——类和对象
java·开发语言
JIngJaneIL14 小时前
篮球论坛|基于SprinBoot+vue的篮球论坛系统(源码+数据库+文档)
java·前端·数据库·vue.js·论文·毕设·篮球论坛系统