java 465端口发送邮件

Wesley13
• 阅读 422
package com.fr.function;

import java.io.IOException;
import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
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;

import com.sun.mail.util.MailSSLSocketFactory;

public class MailTest {
    public static void main(String[] args) throws Exception {
        MailUtil.sendEmil465("*****@qq.com", "国家能源集团邮箱测试4");
    }

    /**
     * 使用加密的方式,利用465端口进行传输邮件,开启ssl
     * @param to    为收件人邮箱
     * @param message    发送的消息
     */
    public static void sendEmil465(String to, String message) {
        try { 
            final String smtpHost="mail.chnenergy.com.cn";
            final String smtpPort="465";
            final String username = "****@chnenergy.com.cn";
            final String password = "****";
            final String subject="国家能源集团邮件发送测试5";
                      
            
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());            
           
            //设置邮件会话参数
            Properties props = new Properties();
            //邮箱的发送服务器地址
            props.setProperty("mail.smtp.host", smtpHost);
            props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            
            //SSL认证,注意腾讯邮箱是基于SSL加密的,所有需要开启才可以使用,很多人不成功是因为漏写了下面的代码
            MailSSLSocketFactory sf = new MailSSLSocketFactory();  
            sf.setTrustAllHosts(true);  
            props.put("mail.smtp.ssl.socketFactory", sf);  
            props.setProperty("mail.smtp.ssl.enable", "true");
            
            //邮箱发送服务器端口,这里设置为465端口
            props.setProperty("mail.smtp.port", smtpPort);
            props.setProperty("mail.smtp.socketFactory.port", smtpPort);
            props.put("mail.smtp.auth", "true");
            
            //获取到邮箱会话,利用匿名内部类的方式,将发送者邮箱用户名和密码授权给jvm
            Session session = Session.getDefaultInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
            session.setDebug(true);
            //通过会话,得到一个邮件,用于发送
            Message msg = new MimeMessage(session);
            //设置发件人
            msg.setFrom(new InternetAddress(username));
            //设置收件人,to为收件人,cc为抄送,bcc为密送
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
            //msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(to, false));
            //msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to, false));
            msg.setSubject(subject);
            //设置邮件消息
            msg.setText(message);
            //设置发送的日期
            msg.setSentDate(new Date());
            
            //调用Transport的send方法去发送邮件
            Transport.send(msg);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

465端口失败原因,注释

In earlier releases it was necessary to explicitly set a socket  
factory property to enable use of SSL.  In almost all cases, this  
is no longer necessary.  SSL support is built in.  However, there  
is one case where a special socket factory may be needed.  
  
JavaMail now includes a special SSL socket factory that can simplify  
dealing with servers with self-signed certificates.  While the  
recommended approach is to include the certificate in your keystore  
as described above, the following approach may be simpler in some cases.  
  
The class com.sun.mail.util.MailSSLSocketFactory can be used as a  
simple socket factory that allows trusting all hosts or a specific set  
of hosts.  For example:  
  
    MailSSLSocketFactory sf = new MailSSLSocketFactory();  
    sf.setTrustAllHosts(true);  
    // or  
    // sf.setTrustedHosts(new String[] { "my-server" });  
    props.put("mail.smtp.ssl.enable", "true");  
    // also use following for additional safety  
    //props.put("mail.smtp.ssl.checkserveridentity", "true");  
    props.put("mail.smtp.ssl.socketFactory", sf);  
  
Use of MailSSLSocketFactory avoids the need to add the certificate to  
your keystore as described above, or configure your own TrustManager  
as described below.(使用MailSSLSocketFactory避免了需要添加证书,你的密钥库如上所述,或配置自己的TrustManager。如下所述。

 转载自:https://blog.csdn.net/allen_zs/article/details/50753311

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
待兔 待兔
3年前
Java中遍历HashMap的5种方式
本教程将为你展示Java中HashMap的几种典型遍历方式。如果你使用Java8,由于该版本JDK支持lambda表达式,可以采用第5种方式来遍历。如果你想使用泛型,可以参考方法3。如果你使用旧版JDK不支持泛型可以参考方法4。1、通过ForEach循环进行遍历importjava.io.IOException;importjav
Wesley13 Wesley13
2年前
javamail邮件工具类(增加465端口发送,收件,无效收件人过滤)
packagecom.flysand;importcom.alibaba.fastjson.JSON;importcom.google.common.collect.Lists;importcom.j1cn.bizclient.meta.entity.email.EmailEntity;imp
Wesley13 Wesley13
2年前
Java爬虫之JSoup使用教程
title:Java爬虫之JSoup使用教程date:201812248:00:000800update:201812248:00:000800author:mecover:https://imgblog.csdnimg.cn/20181224144920712(https://www.oschin
Wesley13 Wesley13
2年前
Java日期时间API系列31
  时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总毫秒数,是所有时间的基础,其他时间可以通过时间戳转换得到。Java中本来已经有相关获取时间戳的方法,Java8后增加新的类Instant等专用于处理时间戳问题。 1获取时间戳的方法和性能对比1.1获取时间戳方法Java8以前
Wesley13 Wesley13
2年前
Java日期时间API系列35
  通过Java日期时间API系列1Jdk7及以前的日期时间类(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fwww.cnblogs.com%2Fxkzhangsanx%2Fp%2F12032719.html)中得知,Java8以前除了java.sql.Timestamp扩充
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Docker 部署SpringBoot项目不香吗?
  公众号改版后文章乱序推荐,希望你可以点击上方“Java进阶架构师”,点击右上角,将我们设为★“星标”!这样才不会错过每日进阶架构文章呀。  !(http://dingyue.ws.126.net/2020/0920/b00fbfc7j00qgy5xy002kd200qo00hsg00it00cj.jpg)  2
京东云开发者 京东云开发者
6个月前
Java服务总在半夜挂,背后的真相竟然是... | 京东云技术团队
最近有用户反馈测试环境Java服务总在凌晨00:00左右挂掉,用户反馈Java服务没有定时任务,也没有流量突增的情况,Jvm配置也合理,莫名其妙就挂了