1. 程式人生 > 實用技巧 >java,qq郵箱發郵件工具類(需要部分修改)

java,qq郵箱發郵件工具類(需要部分修改)

//非同步處理,多執行緒實現使用者體驗
public class Sendmail extends Thread{
    //用於給使用者傳送郵件的郵箱
    private String from="[email protected]";
    //郵箱的使用者名稱
    private String username="[email protected]";
    //郵箱的密碼
    private String password="郵箱獲取的金鑰";
    //傳送郵件的伺服器地址
    private String host="smtp.qq.com";

    private User user;
    public Sendmail(User user){
        this.user=user;
    }

    //重寫run方法的實現,再run方法中傳送郵件給指定使用者
    @Override
    public void run() {
        try {
        Properties prop = new Properties();
        prop.setProperty("mail.host",host);//設定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(username,password);
            }
        });

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

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

        //3.使用郵箱的使用者名稱和授權碼連上郵件伺服器
        ts.connect(host,username,password);

        //4.建立郵件
        //建立郵件物件
        MimeMessage message = new MimeMessage(session);
        //指定郵件的發件人
        message.setFrom(new InternetAddress(from));//發件人
        //指明郵件的收件人 [email protected]
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(user.getEmail()));//收件人
        //郵件的標題
        message.setSubject("使用者註冊郵件");//郵件的標題
        //郵件的文字內容<h1 style='color:pink'>愛你呦</h1>
        String info="恭喜您註冊成功,您的使用者名稱:"+user.getUsername()+",您的密碼:"+user.getPassword()+",請妥善保管,如有問題請聯絡網站客服!!";
        message.setContent(info,"text/html;charset=UTF-8");
        message.saveChanges();
        //5.傳送郵件
        ts.sendMessage(message,message.getAllRecipients());

        //6.關閉連線
        ts.close();
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}