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

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

相关推荐
执子手 吹散苍茫茫烟波12 分钟前
leetcode415. 字符串相加
java·leetcode·字符串
小韩博18 分钟前
网络安全(Java语言)脚本 汇总(二)
java·安全·web安全
萤丰信息24 分钟前
技术赋能安全:智慧工地构建城市建设新防线
java·大数据·开发语言·人工智能·智慧城市·智慧工地
带刺的坐椅44 分钟前
Java MCP 的鉴权?好简单的啦
java·鉴权·mcp·solon-ai
Pocker_Spades_A1 小时前
飞算JavaAI家庭记账系统:从收支记录到财务分析的全流程管理方案
java·开发语言
33255_40857_280591 小时前
掌握分页艺术:MyBatis与MyBatis-Plus实战指南(10年Java亲授)
java·mybatis
Ashlee_code1 小时前
香港券商智能櫃台系統技術解決方案——融合跨境清算與AI風控,助力券商把握滬港雙市爆發機遇**
java·科技·金融·重构·架构·系统架构·php
蚰蜒螟1 小时前
Spring 和 Lettuce 源码分析 Redis 节点状态检查与失败重连的工作原理
java·redis·spring
小张快跑。1 小时前
Tomcat下载、安装及配置详细教程
java·服务器·tomcat
神仙别闹2 小时前
基于 JSP+Mysql实现MVC房屋租赁系统
java·mysql·mvc