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

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

相关推荐
哈哈哈笑什么17 分钟前
SpringBoot 企业级接口加密【通用、可配置、解耦的组件】「开闭原则+模板方法+拦截器/中间件模式」
java·后端·安全
期待のcode18 分钟前
springboot依赖管理机制
java·spring boot·后端
WX-bisheyuange25 分钟前
基于Spring Boot的智慧校园管理系统设计与实现
java·大数据·数据库·毕业设计
深紫色的三北六号1 小时前
大疆不同任务类型执行逻辑,上云API源码分析
java·无人机·springboot·大疆·上云api
BD_Marathon1 小时前
【JavaWeb】IDEA运行并部署JavaWeb项目原理
java·ide·intellij-idea
7ioik1 小时前
什么是类加载机制?
java
洛阳泰山1 小时前
Java实现周易六爻自动排盘:根据起卦的公历时间换算农和干支时间,推算日柱空亡(旬空)
java·开发语言·周易·六爻·算卦
一只游鱼1 小时前
我的第一个微服务项目cy-fang1.0
java·后端·spring cloud
缘来是庄1 小时前
invalid comparison
java·spring boot·mybatis
哈哈哈笑什么1 小时前
3 次生产系统崩溃复盘:Java 后端从踩坑到封神的排查优化之路
java·后端·性能优化