javamail騰訊企業郵箱發送郵件


1 此代碼用的jar文件:mail.jar(1.4.5版本);
2 如果jdk用的是1.8版本會出現SSL錯誤:這個問題是jdk導致的,jdk1.8里面有一個jce的包,安全性機制導致的訪問https會報錯,官網上有替代的jar包,如果替換掉就可以了.
3 這兩個jar包的下載地址:http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
4 下載之后,把這個壓縮文件解壓,得到兩個jar包去覆蓋jdk安裝目錄下的jre\lib\security\下相同的jar包就能解決java8的郵件發送問題。
public static void main(String[] args) throws Exception {
        Properties prop = new Properties();
        //協議
        prop.setProperty("mail.transport.protocol", "smtp");
        //服務器
        prop.setProperty("mail.smtp.host", "smtp.exmail.qq.com");
        //端口
        prop.setProperty("mail.smtp.port", "465");
        //使用smtp身份驗證
        prop.setProperty("mail.smtp.auth", "true");
        //使用SSL,企業郵箱必需!
        //開啟安全協議
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
        } catch (GeneralSecurityException e1) {
            e1.printStackTrace();
        }
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);
        //
        //獲取Session對象
        Session s = Session.getDefaultInstance(prop,new Authenticator() {
            //此訪求返回用戶和密碼的對象
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                PasswordAuthentication pa = new PasswordAuthentication("wygm@daee.cn", "Ok1234");
                return pa;
            }
        });
        //設置session的調試模式,發布時取消
        s.setDebug(true);
        MimeMessage mimeMessage = new MimeMessage(s);
        try {
            mimeMessage.setFrom(new InternetAddress("wygm@daee.cn","wygm@daee.cn"));
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("1938859832@qq.com"));
            //設置主題
            mimeMessage.setSubject("賬戶密碼重置");
            mimeMessage.setSentDate(new Date());
            //設置內容
            mimeMessage.setText("您使用了密碼重置功能");
            mimeMessage.saveChanges();
            //發送
            Transport.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        
    }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM