一、一般配置

发送邮件需要用到  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加密方式)的更多相关文章

  1. Spring Boot 揭秘与实战(七) 实用技术篇 - Java Mail 发送邮件

    文章目录 1. Spring Boot 集成 Java Mail 2. 单元测试 3. 源代码 Spring 对 Java Mail 有很好的支持.因此,Spring Boot 也提供了自动配置的支持 ...

  2. java mail(发送邮件--163邮箱)

    package com.util.mail; /** * 发送邮件需要使用的基本信息 */ import java.util.Properties; public class MailSenderIn ...

  3. Java mail 发送邮件 主题(标题)乱码

    最近开发遇到Javamail  发送邮件标题乱码问题,腾讯.网易邮箱不会乱码,阿里邮箱  标题则会乱码.解决办法: String subject = MimeUtility.encodeWord(ma ...

  4. 使用java mail 发送邮件

    1.关联jar包:   activation.jar   mail.jar 2.调用 @Test public void test1() { List<String> imageUrlLi ...

  5. java mail发送邮件

    最近做了自动发送邮件功能,带附件的:需要的jar包有

  6. 使用Java Mail发送邮件

    本笔记参考自:高爽|Coder,原文地址:http://blog.csdn.net/ghsau/article/details/17839983 JavaMail是SUN提供给开发人员在应用程序中实现 ...

  7. 简单的java mail发送邮件实例

    mail.jar ,commons-email-X.X.jar ,activation.jar ,log4j.jar  这四个jar,放进项目里 下载地址 http://www.oracle.com/ ...

  8. 利用java mail发送邮件(转)

    JavaMail是SUN提供给开发者在应用程序中实现邮件发送和接收功能而提供的一套标准开发类库,支持经常使用的邮件协议,如SMTP.POP3.IMAP.开发者使用JavaMail编写邮件程序时,无需考 ...

  9. 利用java mail发送邮件

    import java.util.Date; import java.util.Properties; import javax.activation.DataHandler; import java ...

随机推荐

  1. 自动构建工具Gulp

    摘要:  gulp与grunt一样,都是自动构建工具.和grunt相比它更突出一个流的概念,任务是一个接一个执行的.今天就分享如何用gulp做自动化. 安装: gulp也是基于node环境,所以安装g ...

  2. nyoj 1239 引水project (河南省第八届acm程序设计大赛)

    题目1239 pid=1239" style="color:rgb(55,119,188)">题目信息 pid=1239" style="col ...

  3. [转]spring 官方下载地址(Spring Framework 3.2.x&Spring Framework 4.0.x)

    SPRING官方网站改版后,建议都是通过 Maven和Gradle下载,对不使用Maven和Gradle开发项目的,下载就非常麻烦,下给出Spring Framework jar官方直接下载路径: h ...

  4. PostgreSQL的表空间

    1. 表空间的概念 PostgreSQL中的表空间允许在文件系统中定义用来存放表示数据库对象的文件的位置.在PostgreSQL中表空间实际上就是给表指定一个存储目录. 2. 表空间的作用 官方解释 ...

  5. NTP服务器时间集群借节点之间同步

    1.三个节点时间同步,cdh1,cdh2,cdh3 2.做法:cdh1从网络时间同步,然后cdh2和cdh3从cdh1节点同步 3.安装与自启动设置 yum install ntp 按上面的安装方式在 ...

  6. java的代理和动态代理简单测试

    什么叫代理与动态代理? 1.以买火车票多的生活实例说明. 因为天天调bug所以我没有时间去火车票,然后就给火车票代理商打电话订票,然后代理商就去火车站给我买票.就这么理解,需要我做的事情,代理商帮我办 ...

  7. 一句话木马:ASP篇

    ASP一句话木马收集: <%eval request("chopper")%> <%execute request("chopper")%&g ...

  8. tablayout在中间显示

    <android.support.design.widget.TabLayout android:id="@+id/tabLayout" android:layout_wid ...

  9. Fragment切换问题

    片断一: add hind @Overridepublic void onCheckedChanged(RadioGroup group, int checkedId) { switch (check ...

  10. PowerShell的初步学习

    今天要重新学习一钟语法,由于工作中项目的需要,不得不说学习新的语言是必不可少的.          Windows PowerShell 是一种命令行外科程序和脚本环境,使命令行用户和脚本编写者可以利 ...