Could not connect to SMTP host: smtp.163.com, port: 25;阿里雲 ECS

ECS基於安全考慮,目前已禁用25端口。

如果您的發送程序部署在阿里雲ECS上,建議您不勾選SSL時,使用80端口,勾選SSL時,使用465端口。

測試端口   telnet smtp.163.com 25

測試網絡 ping smtp.163.com

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SimpleAliDMSendMail {
    private static final String ALIDM_SMTP_HOST = "smtpdm.aliyun.com";
    private static final int ALIDM_SMTP_PORT = 25;

    public static void main(String[] args) throws MessagingException {
        // 配置發送郵件的環境屬性
        final Properties props = new Properties();
        // 表示SMTP發送郵件,需要進行身份驗證
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", ALIDM_SMTP_HOST);
        props.put("mail.smtp.port", ALIDM_SMTP_PORT);   
        // 如果使用ssl,則去掉使用25端口的配置,進行如下配置, 
        // props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        // props.put("mail.smtp.socketFactory.port", "465");
        // props.put("mail.smtp.port", "465");


        // 發件人的賬號
        props.put("mail.user", "***");
        // 訪問SMTP服務時需要提供的密碼
        props.put("mail.password", "***");

        // 構建授權信息,用於進行SMTP進行身份驗證
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用戶名、密碼
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用環境屬性和授權信息,創建郵件會話
        Session mailSession = Session.getInstance(props, authenticator);
        // 創建郵件消息
        MimeMessage message = new MimeMessage(mailSession);
        // 設置發件人
        InternetAddress form = new InternetAddress(
                props.getProperty("mail.user"));
        message.setFrom(form);

        // 設置收件人
        InternetAddress to = new InternetAddress("***");
        message.setRecipient(MimeMessage.RecipientType.TO, to);

        // 設置郵件標題
        message.setSubject("測試郵件");
        // 設置郵件的內容體
        message.setContent("測試的HTML郵件", "text/html;charset=UTF-8");

        // 發送郵件
        Transport.send(message);
    }
}

發佈了48 篇原創文章 · 獲贊 8 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章