阿里雲封25端口,怎麼使用java發送郵件呢

阿里雲服務器25端口默認被封

我用的阿里雲centos7是默認封禁了TCP 25端口出方向的訪問流量,所以用戶無法使用25號端口郵件服務,如果你是使用25端口進行簡單郵件發送是會報連接超時的錯誤的

解決辦法

一. 向阿里雲申請開放25端口

這是申請地址和方法 :申請開放25端口

二. 改用更安全更推薦的465端口進行郵件發送

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

/**
 * Description: sendEmail
 * Created by danqing on 2020/4/23 21:31
 */
public class SendEmail {
    public static void sendEmailCode(String receiveEmail,String content)
    {
        // 收件人電子郵箱
        String to = receiveEmail;

        // 發件人電子郵箱
        String from = "[email protected]";

        // 指定發送郵件的主機爲 smtp.163.com
        String host = "smtp.163.com";  // 郵件服務器

        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        //設置郵件會話參數
        Properties properties = new Properties();

        // 設置郵件服務器
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        properties.setProperty("mail.smtp.socketFactory.fallback", "false");
        
        //郵箱發送服務器端口,這裏設置爲465端口
        properties.setProperty("mail.smtp.port", "465");
        properties.setProperty("mail.smtp.socketFactory.port", "465");
        properties.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(properties,new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                    //這裏的username是你的郵箱賬戶 和上面的發件人郵箱是一樣的
                    //password是你的郵箱服務器的授權碼
                        return new PasswordAuthentication("username", "password");
                    }
                });

        try{
            // 創建默認的 MimeMessage 對象
            MimeMessage message = new MimeMessage(session);

            // Set From: 頭部頭字段 發件人暱稱和字符集
            message.setFrom(new InternetAddress(from,"暱稱","UTF-8"));

            // Set To: 頭部頭字段
            message.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(to));

            // Set Subject: 頭部頭字段
            message.setSubject("shiro_ssm權限管理系統登錄");

            // 設置消息體
            message.setText(content);

            // 發送消息
            Transport.send(message);
            
            System.out.println("Sent message successfully....");
        }catch (MessagingException | UnsupportedEncodingException mex) {
            mex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        sendEmailCode("[email protected]","使用465端口發送一封郵件");
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章