Monday, October 13, 2014

ส่งเมลส์ด้วย javaMail ผ่าน gmail

วันนี้ได้ทดลองส่งเมลส์ด้วย javaMail ดู แต่ก่อนหน้านี้ก็ได้ลองทำแล้วแต่ใช้ mail ที่ localhost
เริ่มเลยละกัน ออ ผมใช้ netbean นะครับ ฉนั้นพวก import เนี่ยผมไม่พูดละกันมันหาให้เองแหละ

-การจะติดต่อได้ก็ต้องมี API ก่อนนะ ผมใช้ javaMail คือมีทั้ง javax.mail และ activation หาโหลดเองนะครับ ผมลืมแล้วว่าเว็บไหน ปรึกษา google ได้เลย จากนั้นก็เอาไปไว้ที่ WEB-INF\lib

-จากนั้นก็เขียน code กัน อันนี้เป็นที่ผมทำไว้ใน web นะครับ ใช้ได้เลย(ลองในเครื่องตัวเองนะ)
การใช้ javaMail นั้นมีอยู่ด้วยกัน 3 แบบนะ ปกติ smtp จะเป็น port 25 นะ แต่ gmail.com จะใ้ห้เราใช้ port อื่น เพราะต้องใช้ Authen ด้วย
1. ใช้ smtp ไม่ใช้ Authen
2. ใช้ smtp ใช้ TLS Authen
3. ใช้ smtp ใช้ SSL Authen

สำหรับ gmail.com จะใช้ได้ทั้ง TLS และ SSL นะครับ สำหรับผมใช้แบบ TLS Authen

        String auth_host = "smtp.gmail.com";//กำหนด host
        String auth_port = "587";//กำหนด port
        final String auth_email = "satravel@gmail.com";//กำหนด email
        final String auth_password = "password";//กำหนด password

       // Get system properties object
        Properties properties = System.getProperties();

       // Setup mail server โดยใช้ TLS Authentication
        properties.put("mail.smtp.host", auth_host);
        properties.put("mail.smtp.port", auth_port);
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");

        try {
         
            Authenticator auth = new Authenticator(){
                @Override
                public PasswordAuthentication getPasswordAuthentication(){
                    return new PasswordAuthentication(auth_email,auth_password);
                }
            };
         
            Session mailSession = Session.getInstance( properties , auth);//สร้าง session
            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(mailSession);
            // Set From: header field of the header.
            message.setFrom(new InternetAddress(from,"Budsatravel"));//กำหนดชื่อผู้ส่งนะ
            //Set Reply To
            message.setReplyTo(InternetAddress.parse("satravel@gmail.com",false));//กำหนด reply
            // Set To: header field of the header.
            message.addRecipient(Message.RecipientType.TO,new InternetAddress(to,false));//ผู้รับ
            // Set Subject: header field
            message.setSubject("Booking From Budsatravel.com");//หัวข้ออีเมลส์
            // Now set the actual message
            message.setContent(content,"text/html");//ส่งเป็น html โดย content จะต้องมีลักษณะเป็น html
         
            // Send message
            Transport.send(message);
            return true;
        } catch (Exception mex) {
            return false;
        }

       เรียบร้อยครับผม
       ออในส่วนของ conten ตัวอย่างเช่น content = หัวข้อ ประมาณนี้ครับผม

      ข้อควรระวังอีกอย่าง ปิดการทำงานของ antivirus ด้วย ไม่งั้นอาจจะมีปัญหาเกี่ยวกับ Authen ได้ครับ

No comments: