JAVA MAIL 发送邮件(SSL加密方式,TSL加密方式)

2023-12-13 02:58

本文主要是介绍JAVA MAIL 发送邮件(SSL加密方式,TSL加密方式),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、一般配置

发送邮件需要用到  mail包 maven 依赖如下:

1 <!-- https://mvnrepository.com/artifact/javax.mail/mail -->
2         <dependency>
3             <groupId>javax.mail</groupId>
4             <artifactId>mail</artifactId>
5             <version>1.4</version>
6         </dependency>

SSL加密方式需要用到MailSSLSocketFactory类

<!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail --><dependency><groupId>com.sun.mail</groupId><artifactId>javax.mail</artifactId><version>1.4.4</version></dependency>

 

获取配置文件:

复制代码
 1 //获取邮箱发送邮件的配置信息2     public Properties getEmailProperties(){3         Properties props = new Properties();4         String host = evn.getProperty("email.host");5         String protocol = evn.getProperty("email.protocol");6         String port = evn.getProperty("email.port");7         String from = evn.getProperty("email.from");8         String pwd = evn.getProperty("email.password");9         props.put("mail.smtp.host", host);//设置服务器地址  
10         props.put("mail.store.protocol" , protocol);//设置协议  
11         props.put("mail.smtp.port", port);//设置端口  
12         props.put("from" , from);  
13         props.put("pwd" , pwd);  
14         props.put("mail.smtp.auth" , "true");
15         return props;
16     }
复制代码

 

 

邮件发送代码类:

复制代码
  1 /** 2  *3  * @file springBootExample.example.infrastructure4  * 5  */6 package com.tyky.educloud.platform.util;7 8 /** 9  * @ClassName: SendEmail 10  * @Description: TODO(这里用一句话描述这个类的作用) 11  * @author hoojjack 12  * @date 2017年7月19日 下午3:23:42 13  *  14  */15 import java.util.Date;16 import java.util.Properties;17 18 import javax.mail.Authenticator;19 import javax.mail.Message;20 import javax.mail.MessagingException;21 import javax.mail.PasswordAuthentication;22 import javax.mail.Session;23 import javax.mail.Transport;24 import javax.mail.internet.AddressException;25 import javax.mail.internet.InternetAddress;26 import javax.mail.internet.MimeMessage;27 28 public class SendEmail {29 30     public static Properties props = new Properties();31 32     public static void setProps(Properties props) {33         SendEmail.props = props;34     }35 36     public static Properties getProps() {37         return props;38     }39 40     /**41      * 获取Session42      * 43      * @return44      */45     private static Session getSession(final String from, final String pwd) {46 47         Authenticator authenticator = new Authenticator() {48 49             @Override50             protected PasswordAuthentication getPasswordAuthentication() {51                 return new PasswordAuthentication(from, pwd);52             }53 54         };55         Session session = Session.getDefaultInstance(props, authenticator);56 57         return session;58     }59 60     public static void send(String content, String toEmail) throws AddressException, MessagingException {61         Properties properties = getProps();62         String from = properties.getProperty("from");63         String pwd = properties.getProperty("pwd");64         String subject = properties.getProperty("subject");65         66         if (null == from || null == pwd) {67             System.out.println("发送邮箱为空");68             return;69         }70         if (null == subject) {71             subject = "平台";72         }73         Session session = getSession(from, pwd);74         // Instantiate a message75         Message msg = new MimeMessage(session);76         // Set message attributes77         msg.setFrom(new InternetAddress(from));78         InternetAddress[] address = { new InternetAddress(toEmail) };79         msg.setRecipients(Message.RecipientType.TO, address);80         msg.setSubject(subject);81         msg.setSentDate(new Date());82         msg.setContent(content, "text/html;charset=utf-8");83         // Send the message84         Transport.send(msg);85     }86 87     public static String generateContent(String contentTitle, String url, String username, String email,88             String validateCode) {89 90         // String validataCode = MD5Util.encode2hex(email);91 92         /// 邮件的内容93         StringBuffer sb = new StringBuffer(contentTitle);94         sb.append("<a href=\"" + url + "?username=");95         sb.append(username);96         sb.append("&email=");97         sb.append(email);98         sb.append("&validateCode=");99         sb.append(validateCode);
100         sb.append("\">" + url + "?username=");
101         sb.append(username);
102         sb.append("&email=");
103         sb.append(email);
104         sb.append("&validateCode=");
105         sb.append(validateCode);
106         sb.append("</a>");
107         return sb.toString();
108     }
109 
110 }
复制代码

 

邮件发送完整的代码:

复制代码
  1 /** 2  * @ClassName: SendEmail 3  * @Description: TODO(这里用一句话描述这个类的作用) 4  * @author hoojjack 5  * @date 2017年7月19日 下午3:23:42 6  *  7  */8 import java.util.Date;9 import java.util.Properties;10 11 import javax.mail.Authenticator;12 import javax.mail.Message;13 import javax.mail.MessagingException;14 import javax.mail.PasswordAuthentication;15 import javax.mail.Session;16 import javax.mail.Transport;17 import javax.mail.internet.AddressException;18 import javax.mail.internet.InternetAddress;19 import javax.mail.internet.MimeMessage;20 21 public class SendEmail {22 23     public static Properties props = new Properties();24 25     public static void setProps(Properties props) {26         SendEmail.props = props;27     }28 29     public static Properties getProps() {30         props.put("mail.smtp.host", "smtp.163.com");// 设置服务器地址31         props.put("mail.store.protocol", "smtp.163.com");// 设置协议32         props.put("mail.smtp.port", 25);// 设置端口33         props.put("from", "XXX");34         props.put("pwd", "XXX");35         props.put("mail.smtp.auth", "true");36     }37 38     /**39      * 获取Session40      * 41      * @return42      */43     private static Session getSession(final String from, final String pwd) {44 45         Authenticator authenticator = new Authenticator() {46 47             @Override48             protected PasswordAuthentication getPasswordAuthentication() {49                 return new PasswordAuthentication(from, pwd);50             }51 52         };53         Session session = Session.getDefaultInstance(props, authenticator);54 55         return session;56     }57 58     public static void send(String content, String toEmail) throws AddressException, MessagingException {59         Properties properties = getProps();60         String from = properties.getProperty("from");61         String pwd = properties.getProperty("pwd");62         String subject = properties.getProperty("subject");63         64         if (null == from || null == pwd) {65             System.out.println("发送邮箱为空");66             return;67         }68         if (null == subject) {69             subject = "平台";70         }71         Session session = getSession(from, pwd);72         // Instantiate a message73         Message msg = new MimeMessage(session);74         // Set message attributes75         msg.setFrom(new InternetAddress(from));76         InternetAddress[] address = { new InternetAddress(toEmail) };77         msg.setRecipients(Message.RecipientType.TO, address);78         msg.setSubject(subject);79         msg.setSentDate(new Date());80         msg.setContent(content, "text/html;charset=utf-8");81         // Send the message82         Transport.send(msg);83     }84 85     public static String generateContent(String contentTitle, String url, String username, String email,86             String validateCode) {87 88         // String validataCode = MD5Util.encode2hex(email);89 90         /// 邮件的内容91         StringBuffer sb = new StringBuffer(contentTitle);92         sb.append("<a href=\"" + url + "?username=");93         sb.append(username);94         sb.append("&email=");95         sb.append(email);96         sb.append("&validateCode=");97         sb.append(validateCode);98         sb.append("\">" + url + "?username=");99         sb.append(username);
100         sb.append("&email=");
101         sb.append(email);
102         sb.append("&validateCode=");
103         sb.append(validateCode);
104         sb.append("</a>");
105         return sb.toString();
106     }
107 
108 }
复制代码

 

 

 以下是两种不同加密方式的代码,与上面默认25端口的方式差别较小,注意不同加密方式红色部分。

 

1. JavaMail – via TLS

 

复制代码
 1 package com.mkyong.common;2 3 import java.util.Properties;4 5 import javax.mail.Message;6 import javax.mail.MessagingException;7 import javax.mail.PasswordAuthentication;8 import javax.mail.Session;9 import javax.mail.Transport;
10 import javax.mail.internet.InternetAddress;
11 import javax.mail.internet.MimeMessage;
12 
13 public class SendMailTLS {
14 
15     public static void main(String[] args) {
16 
17         final String username = "username@gmail.com";
18         final String password = "password";
19 
20         Properties props = new Properties();
21         props.put("mail.smtp.auth", "true");
22         props.put("mail.smtp.starttls.enable", "true");
23         props.put("mail.smtp.host", "smtp.gmail.com");
24         props.put("mail.smtp.port", "587");
25 
26         Session session = Session.getInstance(props,
27           new javax.mail.Authenticator() {
28             protected PasswordAuthentication getPasswordAuthentication() {
29                 return new PasswordAuthentication(username, password);
30             }
31           });
32 
33         try {
34             Message message = new MimeMessage(session);
35             message.setFrom(new InternetAddress("from-email@gmail.com"));
36             message.setRecipients(Message.RecipientType.TO,
37                 InternetAddress.parse("to-email@gmail.com"));
38             message.setSubject("Testing Subject");
39             message.setText("Dear Mail Crawler,"
40                 + "\n\n No spam to my email, please!");
41 
42             Transport.send(message);
43             System.out.println("Done");
44 
45         } catch (MessagingException e) {
46             throw new RuntimeException(e);
47         }
48     }
49 }
复制代码

 

2. JavaMail – via SSL

复制代码
package com.mkyong.common;import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;public class SendMailSSL {public static void main(String[] args) {Properties props = new Properties();props.put("mail.smtp.host", "smtp.gmail.com");props.put("mail.smtp.socketFactory.port", "465");props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");props.put("mail.smtp.auth", "true");props.put("mail.smtp.port", "465");Session session = Session.getDefaultInstance(props,new javax.mail.Authenticator() {protected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication("username","password");}});try {Message message = new MimeMessage(session);message.setFrom(new InternetAddress("from@no-spam.com"));message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("to@no-spam.com"));message.setSubject("Testing Subject");message.setText("Dear Mail Crawler," +"\n\n No spam to my email, please!");Transport.send(message);System.out.println("Done");} catch (MessagingException e) {throw new RuntimeException(e);}}
}
复制代码

 注意:如果以上ssl不行可以尝试将ssl红色部分用以下代码替换:

复制代码
1      MailSSLSocketFactory sf = null;
2      try {
3            sf = new MailSSLSocketFactory();
4            sf.setTrustAllHosts(true);
5      } catch (GeneralSecurityException e1) {
6            e1.printStackTrace();
7      }
8      props.put("mail.smtp.ssl.enable", "true");
9      props.put("mail.smtp.ssl.socketFactory", sf);
复制代码

 

这篇关于JAVA MAIL 发送邮件(SSL加密方式,TSL加密方式)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/486897

相关文章

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

Oracle数据库定时备份脚本方式(Linux)

《Oracle数据库定时备份脚本方式(Linux)》文章介绍Oracle数据库自动备份方案,包含主机备份传输与备机解压导入流程,强调需提前全量删除原库数据避免报错,并需配置无密传输、定时任务及验证脚本... 目录说明主机脚本备机上自动导库脚本整个自动备份oracle数据库的过程(建议全程用root用户)总结

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav

深入浅出SpringBoot WebSocket构建实时应用全面指南

《深入浅出SpringBootWebSocket构建实时应用全面指南》WebSocket是一种在单个TCP连接上进行全双工通信的协议,这篇文章主要为大家详细介绍了SpringBoot如何集成WebS... 目录前言为什么需要 WebSocketWebSocket 是什么Spring Boot 如何简化 We