通過(guò)25端口發(fā)送郵件不安全,改為ssl加密方式發(fā)送郵件,比較常見(jiàn)的2中實(shí)現(xiàn)類(lèi)發(fā)送郵件如下所示。
1、JavaMailSenderImpl 類(lèi)
使用該實(shí)現(xiàn)類(lèi)發(fā)送郵件,ssl加密使用端口號(hào)為465,借助Properties類(lèi)設(shè)置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");//啟用調(diào)試
//properties.setProperty("mail.smtp.timeout", "1000");//設(shè)置鏈接超時(shí)
//設(shè)置通過(guò)ssl協(xié)議使用465端口發(fā)送、使用默認(rèn)端口(25)時(shí)下面三行不需要
properties.setProperty("mail.smtp.auth", "true");//開(kāi)啟認(rèn)證
properties.setProperty("mail.smtp.socketFactory.port", "465");//設(shè)置ssl端口
properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
senderImpl.setJavaMailProperties(properties);
MimeMessage message = senderImpl.createMimeMessage();
//true表示需要?jiǎng)?chuàng)建一個(gè)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("郵件發(fā)送成功");
//保存發(fā)送日志
mailLogEntity.setCreateUserId(Constant.SUPER_ADMIN);
mailLogEntity.setCreateUserOrgNo(Constant.SUPER_ADMIN_ORG);
mailLogEntity.setSender(user.getEmail());
mailLogEntity.setType(Constant.USER_SEND);
result = true;
2、JavaMailSender類(lèi)
網(wǎng)上資料較少,自己記錄一下。
修改application.yml文件配置文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-663365.html
spring:
mail:
host: xxx郵件系統(tǒng)服務(wù)器域名或Ip
port: 465
username: xxx賬號(hào)
password: xxx
default-encoding: UTF-8
# 這里填發(fā)送郵箱對(duì)應(yīng)的SMTP地址 ,忽略證書(shū),信任域名
properties:
mail.smtp.ssl.trust: 郵件系統(tǒng)服務(wù)器域名或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
至于能否都采用第二種方式來(lái)實(shí)現(xiàn),沒(méi)做測(cè)試。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-663365.html
到了這里,關(guān)于java ssl加密發(fā)送郵件的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!