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 ...
随机推荐
- ABBYY FineReader 14助力2017,正式进入新纪元
ABBYY FineReader 12自2014年推出以来,已经给万千用户的工作带来了便捷,蝉联优秀殊荣这么久,相信不少用户早在期待新版本的到来了吧.这不,ABBYY FineReader 14问世了 ...
- MVC學習網站
http://www.cnblogs.com/haogj/archive/2011/11/23/2246032.html
- 运行jsp常犯的错误
error 未启动tomcat服务 tomcat端口是否已改动 404: 未部署web应用 运行时URL输入错误 检查文件的存放位置(存放文件的目录无法对外引用,如WEB-INF , META-INF ...
- python 导入模块的坑。为什么整个项目能运行,单独运行某个文件模块就报错?多层目录不同文件夹怎么导入?
一些文章介绍了python不同目录怎么导入问题,但py文件运行起点却从来没有文章说过!这是相当重要的!! 这个连接是网上99%的所讲的导入 https://www.cnblogs.com/luoye0 ...
- js中的string.format
String.prototype.format = function(args) { var result = this; if (arguments.length > 0) { if (arg ...
- Servlet入门总结及第一个Servlet程序
目录 一了解Servlet的概念 二Servlet技术功能 三 Servlet技术特点 四 Servlet生命周期 五servlet工作过程 六 Servlet与JSP区别 七Servlet代码结构 ...
- 新版本的body-parser中间件和morgan中间件引用问题:body-parser deprecated bodyParser和morgan deprecated morgan(options)
引用新版本的body-parser中间件和morgan中间件时,报如下问题: Fri, 09 Jan 2015 06:32:04 GMT morgan deprecated morgan(option ...
- 通过SSH实现Windows与linux之间传输文件
Linux是非常好的开发环境,但很多时候我们希望能够在Windows上操作,通过SSH协议可以实现两者之间传输文件. 一 需要在Linux系统上安装ssh-server,有的linux系统自带了. 查 ...
- video标签 api
video 设置及控制:http://www.w3school.com.cn/tags/html_ref_audio_video_dom.asp video 事件:http://www.w3schoo ...
- SaltStack salt 命令
salt 是服务端远程批量操作多台客户端需要使用到的命令,常见用法如下: salt '*' # 指定对所有客户端主机进行操作 salt 'minion01' # 指定对单台客户端主机进行操作 salt ...