郵件發送端口是否加密問題


發送郵件時候,出現一個問題:使用 25 端口的時候正常,但是使用 465端口的時候卻總是不行。

1.問題

Exception in thread "main" java.lang.RuntimeException: org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.qq.com:465
    at com.rjj.tool.EmailTool.sendEmail(EmailTool.java:41)
    at com.rjj.tool.EmailTool.main(EmailTool.java:54)
Caused by: org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.qq.com:465
    at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1242)
    at org.apache.commons.mail.Email.send(Email.java:1267)
    at com.rjj.tool.EmailTool.sendEmail(EmailTool.java:39)
    ... 1 more
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.qq.com, port: 465, response: -1
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1379)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
    at javax.mail.Service.connect(Service.java:310)
    at javax.mail.Service.connect(Service.java:169)
    at javax.mail.Service.connect(Service.java:118)
    at javax.mail.Transport.send0(Transport.java:188)
    at javax.mail.Transport.send(Transport.java:118)
    at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1232)
    ... 3 more

2.項目引入的jar都是有的

端口也是全部開放的。

 

3.代碼是這樣子的

 public static String sendEmail(String emailServer, Integer port, String fromEmail, String password, String toEmail,
            String title, String content) {

        SimpleEmail email = new SimpleEmail();
        // email.setSSL(true);
        if (StrKit.notBlank(emailServer)) {
            email.setHostName(emailServer);
        } else {
            // 默認使用本地 postfix 發送,這樣就可以將postfix 的 mynetworks 配置為 127.0.0.1 或
            // 127.0.0.0/8 了
            email.setHostName("127.0.0.1");
        }

        // 如果密碼為空,則不進行認證
        if (StrKit.notBlank(password)) {
            email.setAuthentication(fromEmail, password);
        }

        // 端口號不為空,使用配置的端口
        if (port != null) {
            //email.setSslSmtpPort(port.toString());
            email.setSmtpPort(port);
        }

        email.setCharset("utf-8");
        try {
            email.addTo(toEmail);
            email.setFrom(fromEmail);
            email.setSubject(title);
            email.setMsg(content);
            return email.send();
        } catch (EmailException e) {
            throw new RuntimeException(e);
        }
    }

找出問題所在是端口的問題,發郵件時候25端口不用加密也是可以使用,發郵件的的,但是465端口使用的時候需要加密的。

解決:代碼中已經標識了,這里在發郵件的時候需要把郵件設置
SSL加密,就可以了,這里有兩種方式:
1.端口加密:email.setSslSmtpPort(port.toString());
2.直接開啟ssl加密: email.setSSL(true);

這樣就可以正常發送郵件了。

一點一滴記錄遇到的問題與解決方式。。。

 


免責聲明!

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



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