一、一般配置

发送邮件需要用到  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. Windows 安装 adt-bundle的方法

    Refer:http://my.eoe.cn/shuhai/archive/19381.html Windows 安装 adt-bundle的方法 很多大神说Windows下Eclipse启动不起来, ...

  2. PHP 使用memcached

    1.添加扩展包 php_memcache.dll 2.在PHP.INI添加 extension=php_memcache.dll 3.程序 <?php //创建一个mem对象实例 $mem=ne ...

  3. MsChart,饼状图

    HTML 后台代码:(dt为数据源)数据库中数据Sample 1 Chart1.Series["Series1"].Label = "#PERCENT{P}"; ...

  4. VB2008新特性

    1.扩展方法 (Extension Methods) 给Person类扩展Print方法 Public Module PersonExtension <System.Runtime.Compil ...

  5. Centos6.3 下使用 Tomcat-6.0.43 非root用户 部署 生产环境 端口转发方式

    一.安装JDK环境 方法一. 官方下载链接 http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260 ...

  6. css后台页面布局技巧

    目标: 实现左边侧边栏固定,右边内容区自适应 侧边栏内容较少时背景100%高度展示 侧边栏内容较多时可以滚动,且不让显示滚动条(显示太丑) 内容区较少时不出现滚动条,较多时可以滚动 code: < ...

  7. android 网络检测

    这个过程我觉得有必要记录一下事情的起因是这样的, 写的程序在虚拟机下面无法连接到服务器,首先想到的是,虚拟机能不能访问外网,打开某搜索网站,正常,想用ping命令来ping服务器,于是就有了下面的过程 ...

  8. JavaScript之with语句

    with 语句的作用是将代码的作用域设置到一个特定的对象中. with可以简化多次写同一个对象的工作, 示例: var o={name:'a',age:25,sex:'male'} var na=o. ...

  9. vux (scroller)上拉刷新、下拉加载更多

    1)比较关键的地方是要在 scroller 组件上里加一个 ref 属性 <scroller :lockX=true height="-170" :pulldown-conf ...

  10. cannot access android.support.v4.app.BaseFragmentActivityJB的解决

    //implementation 'com.android.support:appcompat-v7:26.1.0' 改成implementation 'com.android.support:app ...