Java Mail 发送邮件(SSL加密方式,TSL加密方式)
一、一般配置
发送邮件需要用到 mail包 maven 依赖如下:
<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</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>
获取配置文件:
//获取邮箱发送邮件的配置信息
public Properties getEmailProperties(){
Properties props = new Properties();
String host = evn.getProperty("email.host");
String protocol = evn.getProperty("email.protocol");
String port = evn.getProperty("email.port");
String from = evn.getProperty("email.from");
String pwd = evn.getProperty("email.password");
props.put("mail.smtp.host", host);//设置服务器地址
props.put("mail.store.protocol" , protocol);//设置协议
props.put("mail.smtp.port", port);//设置端口
props.put("from" , from);
props.put("pwd" , pwd);
props.put("mail.smtp.auth" , "true");
return props;
}
邮件发送代码类:
/**
*
* @file springBootExample.example.infrastructure
*
*/
package com.tyky.educloud.platform.util; /**
* @ClassName: SendEmail
* @Description: TODO(这里用一句话描述这个类的作用)
* @author hoojjack
* @date 2017年7月19日 下午3:23:42
*
*/
import java.util.Date;
import java.util.Properties; import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage; public class SendEmail { public static Properties props = new Properties(); public static void setProps(Properties props) {
SendEmail.props = props;
} public static Properties getProps() {
return props;
} /**
* 获取Session
*
* @return
*/
private static Session getSession(final String from, final String pwd) { Authenticator authenticator = new Authenticator() { @Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, pwd);
} };
Session session = Session.getDefaultInstance(props, authenticator); return session;
} public static void send(String content, String toEmail) throws AddressException, MessagingException {
Properties properties = getProps();
String from = properties.getProperty("from");
String pwd = properties.getProperty("pwd");
String subject = properties.getProperty("subject"); if (null == from || null == pwd) {
System.out.println("发送邮箱为空");
return;
}
if (null == subject) {
subject = "平台";
}
Session session = getSession(from, pwd);
// Instantiate a message
Message msg = new MimeMessage(session);
// Set message attributes
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = { new InternetAddress(toEmail) };
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setContent(content, "text/html;charset=utf-8");
// Send the message
Transport.send(msg);
} public static String generateContent(String contentTitle, String url, String username, String email,
String validateCode) { // String validataCode = MD5Util.encode2hex(email); /// 邮件的内容
StringBuffer sb = new StringBuffer(contentTitle);
sb.append("<a href=\"" + url + "?username=");
sb.append(username);
sb.append("&email=");
sb.append(email);
sb.append("&validateCode=");
sb.append(validateCode);
sb.append("\">" + url + "?username=");
sb.append(username);
sb.append("&email=");
sb.append(email);
sb.append("&validateCode=");
sb.append(validateCode);
sb.append("</a>");
return sb.toString();
} }
邮件发送完整的代码:
/**
* @ClassName: SendEmail
* @Description: TODO(这里用一句话描述这个类的作用)
* @author hoojjack
* @date 2017年7月19日 下午3:23:42
*
*/
import java.util.Date;
import java.util.Properties; import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage; public class SendEmail { public static Properties props = new Properties(); public static void setProps(Properties props) {
SendEmail.props = props;
} public static Properties getProps() {
props.put("mail.smtp.host", "smtp.163.com");// 设置服务器地址
props.put("mail.store.protocol", "smtp.163.com");// 设置协议
props.put("mail.smtp.port", 25);// 设置端口
props.put("from", "XXX");
props.put("pwd", "XXX");
props.put("mail.smtp.auth", "true");
} /**
* 获取Session
*
* @return
*/
private static Session getSession(final String from, final String pwd) { Authenticator authenticator = new Authenticator() { @Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, pwd);
} };
Session session = Session.getDefaultInstance(props, authenticator); return session;
} public static void send(String content, String toEmail) throws AddressException, MessagingException {
Properties properties = getProps();
String from = properties.getProperty("from");
String pwd = properties.getProperty("pwd");
String subject = properties.getProperty("subject"); if (null == from || null == pwd) {
System.out.println("发送邮箱为空");
return;
}
if (null == subject) {
subject = "平台";
}
Session session = getSession(from, pwd);
// Instantiate a message
Message msg = new MimeMessage(session);
// Set message attributes
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = { new InternetAddress(toEmail) };
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setContent(content, "text/html;charset=utf-8");
// Send the message
Transport.send(msg);
} public static String generateContent(String contentTitle, String url, String username, String email,
String validateCode) { // String validataCode = MD5Util.encode2hex(email); /// 邮件的内容
StringBuffer sb = new StringBuffer(contentTitle);
sb.append("<a href=\"" + url + "?username=");
sb.append(username);
sb.append("&email=");
sb.append(email);
sb.append("&validateCode=");
sb.append(validateCode);
sb.append("\">" + url + "?username=");
sb.append(username);
sb.append("&email=");
sb.append(email);
sb.append("&validateCode=");
sb.append(validateCode);
sb.append("</a>");
return sb.toString();
} }
以下是两种不同加密方式的代码,与上面默认25端口的方式差别较小,注意不同加密方式红色部分。
1. JavaMail – via TLS
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 SendMailTLS { public static void main(String[] args) { final String username = "username@gmail.com";
final String password = "password"; Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587"); Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}); try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from-email@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-email@gmail.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);
}
}
}
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红色部分用以下代码替换:
MailSSLSocketFactory sf = null;
try {
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
} catch (GeneralSecurityException e1) {
e1.printStackTrace();
}
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
Java Mail 发送邮件(SSL加密方式,TSL加密方式)的更多相关文章
- Spring Boot 揭秘与实战(七) 实用技术篇 - Java Mail 发送邮件
文章目录 1. Spring Boot 集成 Java Mail 2. 单元测试 3. 源代码 Spring 对 Java Mail 有很好的支持.因此,Spring Boot 也提供了自动配置的支持 ...
- java mail(发送邮件--163邮箱)
package com.util.mail; /** * 发送邮件需要使用的基本信息 */ import java.util.Properties; public class MailSenderIn ...
- Java mail 发送邮件 主题(标题)乱码
最近开发遇到Javamail 发送邮件标题乱码问题,腾讯.网易邮箱不会乱码,阿里邮箱 标题则会乱码.解决办法: String subject = MimeUtility.encodeWord(ma ...
- 使用java mail 发送邮件
1.关联jar包: activation.jar mail.jar 2.调用 @Test public void test1() { List<String> imageUrlLi ...
- java mail发送邮件
最近做了自动发送邮件功能,带附件的:需要的jar包有
- 使用Java Mail发送邮件
本笔记参考自:高爽|Coder,原文地址:http://blog.csdn.net/ghsau/article/details/17839983 JavaMail是SUN提供给开发人员在应用程序中实现 ...
- 简单的java mail发送邮件实例
mail.jar ,commons-email-X.X.jar ,activation.jar ,log4j.jar 这四个jar,放进项目里 下载地址 http://www.oracle.com/ ...
- 利用java mail发送邮件(转)
JavaMail是SUN提供给开发者在应用程序中实现邮件发送和接收功能而提供的一套标准开发类库,支持经常使用的邮件协议,如SMTP.POP3.IMAP.开发者使用JavaMail编写邮件程序时,无需考 ...
- 利用java mail发送邮件
import java.util.Date; import java.util.Properties; import javax.activation.DataHandler; import java ...
随机推荐
- mysql中将一个数据类型转换成另外的数据类型?mysql中cast函数的使用?
需求描述: 今天在看mysql的函数,提到了通过cast函数将一个数据类型值转换为特定类型的结果值. 在此记录下.将一个表达式转换为特定精度的小数. 操作过程: 1.查看6/4的结果 mysql; + ...
- 开发kendo-ui弹窗组件
摘要: kendo-ui中只是提供了windwo插件,并没有提供页内弹窗插件.现在分享项目中自己定制的基于window组件的弹窗插件,如果你的项目也是用的kendo-ui,只需要将组件代码引到项目中即 ...
- pycahrm使用docstrings来指定变量类型、返回值类型、函数参数类型
py里面不需要显示声明类型,这和java c这些静态语言不同,虽然python这样做少了一些代码和写代码的困难度,但还是非常多的弊端的,运行速度 代码安全, 这些都是语言本身带来的本的弊端,这些没办法 ...
- [原]pomelo开发环境搭建
pomelo基于nodejs服务器开源框架,比较牛逼的! 1.安装nodejs(官网下载地址) 安装python等 具体见官网说明 2.安装pomelo(见官方步骤)或者 http://blog.cs ...
- [原]unity3d刀光剑影(二)
本篇研究 暴走武侠 效果.直接贴代码 Shader "Cg shader with single texture" { Properties { _MainTex ("T ...
- SpringMVC由浅入深day01_3非注解的处理器映射器和适配器
3 非注解的处理器映射器和适配器 3.1 非注解的处理器映射器 3.1.1 HandlerMapping处理器映射器 HandlerMapping 负责根据request请求找到对应的Handler ...
- django学习笔记:AdminSite界面配置
(一)重定义字段顺序: 修改对应应用目录下的admin.py class PollAdmin(admin.ModelAdmin): fields = ['pub_date', 'questio ...
- Ansible Playbook 使用循环语句
如下,with_items 是循环的对象,with_items 是 python list 数据结构,task 会循环读取 list 里面的值,key 的名称是 item [root@localhos ...
- 执行Batch批处理遇到的问题
1.务必关掉自动提交 增强执行效率 conn.setAutoCommit(false); 2.executeBatch失效问题 <1>务必将语句pstmt = conn.prepareSt ...
- 清理和关闭多余的Windows 7系统服务
清理和关闭多余的Windows 7系统服务 现在已经有不少配置不是很高的电脑用户正式用上了Windows 7(以下简称Win 7),如何让低配置电脑可以更流畅的运行Win 7呢?虽然部分软件提供了傻瓜 ...