javamail例子

public  boolean SendMail(TestBean testBean){
     int port   = 25;         //smtp端口
        String server  = "smtp.126.com";      //smtp服務器地址
        String from  = "發送者@126.com";  //發送者
        String user  = "發送者";     //發送者用戶名
        String password = "***************";      //發送者密碼
        try {
               Properties props = new Properties();
               //smtp參數設置
               props.put("mail.smtp.host", server);
               props.put("mail.smtp.port", String.valueOf(port));
               props.put("mail.smtp.auth", "true");  //smtp是否需要認證
               Transport transport = null;
               //創建Session
               Session session = Session.getDefaultInstance(props, null);
               //通過Session創建Transport
               transport = session.getTransport("smtp");
               transport.connect(server, user, password); //建立同服務器的連接
               //創建Message
               MimeMessage msg = new MimeMessage(session);
               msg.setSentDate(new Date());  //設置發送時間
               InternetAddress fromAddress = new InternetAddress(from);
               msg.setFrom(fromAddress);  //設置發送人地址
               InternetAddress[] toAddress = new InternetAddress[1];
               toAddress[0] = new InternetAddress("接收者@qq.com");
               msg.setRecipients(Message.RecipientType.TO, toAddress); //設置收件人地址
               msg.setSubject("email-測試", "UTF-8"); //設置主題信息
               msg.setText("發送郵件內容測試", "UTF-8"); //設置內容信息
               msg.saveChanges();
               //Transport完成向Recipients發送Message
               transport.sendMessage(msg, msg.getAllRecipients());
               transport.close();                       //關閉
        } catch (NoSuchProviderException e) {
               logger.error(e);
        } catch (MessagingException e) {
               logger.error(e);
        }
        return true;
}
發佈了19 篇原創文章 · 獲贊 5 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章