java Mail使用SSl,端口465加密发送邮件配置

转载于 https://www.cnblogs.com/hoojjack/p/8025284.html

一、一般配置

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

1 
2         
3             javax.mail
4             mail
5             1.4
6         

SSL加密方式需要用到MailSSLSocketFactory类


        
            com.sun.mail
            javax.mail
            1.4.4
        

获取配置文件:

复制代码

 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.infrastructure
  4  * 
  5  */
  6 package com.tyky.educloud.platform.util;
  7 
  8 /** 
  9  * @ClassName: SendEmail 
 10  * @Description: TODO(这里用一句话描述这个类的作用) 
 1
 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      * 获取Session
 42      * 
 43      * @return
 44      */
 45     private static Session getSession(final String from, final String pwd) {
 46 
 47         Authenticator authenticator = new Authenticator() {
 48 
 49             @Override
 50             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 message
 75         Message msg = new MimeMessage(session);
 76         // Set message attributes
 77         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 message
 84         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("" + 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("");
107         return sb.toString();
108     }
109 
110 }

复制代码

邮件发送完整的代码:

复制代码

  1 /** 
  2  * @ClassName: SendEmail 
  3  * @Description: TODO(这里用一句话描述这个类的作用) 
  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      * 获取Session
 40      * 
 41      * @return
 42      */
 43     private static Session getSession(final String from, final String pwd) {
 44 
 45         Authenticator authenticator = new Authenticator() {
 46 
 47             @Override
 48             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 message
 73         Message msg = new MimeMessage(session);
 74         // Set message attributes
 75         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 message
 82         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("" + 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("");
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 = "[email protected]";
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("[email protected]"));
36             message.setRecipients(Message.RecipientType.TO,
37                 InternetAddress.parse("[email protected]"));
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("[email protected]"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("[email protected]"));
            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,ssl,javamail,加密解密)