• Java Mail 发送邮件(SSL加密方式,TSL加密方式)


    一、一般配置

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

    1 <!-- https://mvnrepository.com/artifact/javax.mail/mail -->
    2         <dependency>
    3             <groupId>javax.mail</groupId>
    4             <artifactId>mail</artifactId>
    5             <version>1.4</version>
    6         </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>

    获取配置文件:

     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(这里用一句话描述这个类的作用) 
     11  * @author hoojjack 
     12  * @date 2017年7月19日 下午3:23:42 
     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("<a href="" + url + "?username=");
     95         sb.append(username);
     96         sb.append("&email=");
     97         sb.append(email);
     98         sb.append("&validateCode=");
     99         sb.append(validateCode);
    100         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("</a>");
    107         return sb.toString();
    108     }
    109 
    110 }

    邮件发送完整的代码:

      1 /** 
      2  * @ClassName: SendEmail 
      3  * @Description: TODO(这里用一句话描述这个类的作用) 
      4  * @author hoojjack 
      5  * @date 2017年7月19日 下午3:23:42 
      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("<a href="" + url + "?username=");
     93         sb.append(username);
     94         sb.append("&email=");
     95         sb.append(email);
     96         sb.append("&validateCode=");
     97         sb.append(validateCode);
     98         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("</a>");
    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 = "username@gmail.com";
    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("from-email@gmail.com"));
    36             message.setRecipients(Message.RecipientType.TO,
    37                 InternetAddress.parse("to-email@gmail.com"));
    38             message.setSubject("Testing Subject");
    39             message.setText("Dear Mail Crawler,"
    40                 + "
    
     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("from@no-spam.com"));
                message.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse("to@no-spam.com"));
                message.setSubject("Testing Subject");
                message.setText("Dear Mail Crawler," +
                        "
    
     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);
  • 相关阅读:
    LED调光,PFM即pulse frequence modulation
    调光设备术语:调光曲线(转)
    盗梦陀螺攻略5- PID平衡算法(转)
    连接池中的maxIdle,MaxActive,maxWait参数
    MyBatis 延迟加载,一级缓存,二级缓存设置
    maven常用命令介绍
    科目二倒库的感悟(附一个教练独特的调镜方法)
    科目二怎么调整后视镜
    新手学车上车起步步骤
    ActiveMQ 了解
  • 原文地址:https://www.cnblogs.com/hoojjack/p/8025284.html
Copyright © 2020-2023  润新知