1. 程式人生 > 實用技巧 >Java使用qq郵箱發郵件實現

Java使用qq郵箱發郵件實現

public class MailDemo1 {
      public static void main(String[] args) throws Exception{
        Properties prop = new Properties();
        prop.setProperty("mail.host","smtp.qq.com");//設定qq郵件伺服器
        prop.setProperty("mail.transport.protocol","smtp");//郵件傳送協議
        prop.setProperty("mail.smtp.auth","true");//需要驗證使用者名稱密碼

        //關於QQ郵箱,還要設定SSL加密
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable","true");
        prop.put("mail.smtp.ssl.socketFactory",sf);


        //使用JavaMail傳送郵件的六個步驟
        //1.建立定義整個應用程式所需要的環境資訊的Session物件

        //QQ獨有
        Session session=Session.getDefaultInstance(prop, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("獲取授權碼的郵箱","授權碼");
            }
        });

        //開啟Session的Debug模式,可以看到程式傳送Email的執行狀態
        session.setDebug(true);

        //2.通過Session物件獲取transport物件
        Transport ts = session.getTransport();

        //3.使用郵箱的使用者名稱和授權碼連上郵件伺服器
        ts.connect("smtp.qq.com","獲取授權碼的郵箱","授權碼");

        //4.建立郵件
        //建立郵件物件
        MimeMessage message = new MimeMessage(session);
        //指定郵件的發件人
        message.setFrom(new InternetAddress("[email protected]"));
        //指明郵件的收件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress("[email protected]"));
        //郵件的標題
        message.setSubject("Your Baby!!");
        //郵件的文字內容
        message.setContent("<h1 style='color:pink'>愛你呦</h1>","text/html;charset=UTF-8");
        //5.傳送郵件
        ts.sendMessage(message,message.getAllRecipients());

        //6.關閉連線
        ts.close();
    }
}