閱讀795 返回首頁    go 團貸網


SMTP之JAVA調用示例__SMTP接口說明_郵件推送-阿裏雲

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);
    }
}

最後更新:2016-11-24 11:23:48

  上一篇:go SMTP服務地址__SMTP接口說明_郵件推送-阿裏雲
  下一篇:go SMTP之CSharp調用示例__SMTP接口說明_郵件推送-阿裏雲