Đọc gmail với JavaMail API
Trong bài này tôi sẽ hướng dẫn các bạn cách thức đọc gmail với JavaMail API.
Đầu tiên bạn sẽ phải download JavaMail API về và thiết lập classpath đến nó. Phần này có nói trong bài Gửi mail có chứng thực trong java.
Với google mail, ta cần biết vài thông số về nó:
1. Mail host: pop.gmail.com
2. Mail Port:587
3. Provider :pop3s
Thiết lập các thông số
| props.put(“mail.smtp.host”, “pop.gmail.com”); props.put(“mail.smtp.port”, “587″); props.put(“mail.smtp.starttls.enable”,”true”); |
Tạo Authentication
| javax.mail.Authenticator pa = null; //default: no authentication if (username != null && password != null) { props.put(“mail.smtp.auth”, “true”); pa = new javax.mail.Authenticator (){ public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }; }//else: no authentication |
Kết nối đến POP3 server
| Session session = Session.getDefaultInstance(props, pa); Store store = session.getStore(provider); store.connect(host, username, password); |
Bây giờ bạn có thể đọc mail
| Folder inbox = store.getFolder(“INBOX”);
//… inbox.open(Folder.READ_ONLY); //… Message[] messages = inbox.getMessages(); |
Sau đây là code hoàn chỉnh của ứng dụng. Chúc thành công!
import java.util.Properties; import javax.mail.Folder; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Store; public class POP3Client { public static void main(String[] args) { Properties props =System.getProperties(); String host = “pop.gmail.com”; final String username = “username của bạn, không có @gmail.com. ví dụ: vovanhaiqn”; final String password = “mật khẩu hợp thư”; String provider = “pop3s“; try { props.put(“mail.smtp.host”, “pop.gmail.com”); props.put(“mail.smtp.port”, “587″); props.put(“mail.smtp.starttls.enable”,“true”); javax.mail.Authenticator pa = null; //default: no authentication if (username != null && password != null) { props.put(“mail.smtp.auth”, “true”); pa = new javax.mail.Authenticator (){ public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }; }//else: no authentication // Kết nối đến POP3 server Session session = Session.getDefaultInstance(props, pa); Store store = session.getStore(provider); store.connect(host, username, password); // Mở thư mục INBOX Folder inbox = store.getFolder(“INBOX”); if (inbox == null) { System.out.println(“No INBOX”); System.exit(1); } inbox.open(Folder.READ_ONLY); // Lấy messages từ server Message[] messages = inbox.getMessages(); if(messages.length<1) System.out.println(“Không có mail mới nào cả!”); for (int i = 0; i < messages.length; i++) { System.out.println(“———— Message ” + (i+1) + “ ————”); //Xuất toàn bộ thông tin của mail ra màn hình console messages[i].writeTo(System.out); //In ra subject của message //System.out.println(messages[i].getSubject()); } // Đóng kết nối nhưng không xóa message inbox.close(false); store.close(); } catch (Exception ex) { ex.printStackTrace(); } } } |
Tài liệu tham khảo: http://java.sun.com/products/javamail/FAQ.html#webmail
Kết quả chạy với 1 mail mới có tiêu đề “read mail with java”, nội dung mail: “Đọc gmail với JavaMail từ http://vovanhai.wordpress.com. Good luck!” từ username vovanhaiqn@yahoo.com đến nth001@gmail.com như sau:
| ———— Message 1 ———— Delivered-To: nth001@gmail.com Received: by 10.100.13.5 with SMTP id 5cs299858anm; Thu, 20 Nov 2008 00:47:32 -0800 (PST) Received: by 10.65.233.16 with SMTP id k16mr1800286qbr.40.1227170851473; Thu, 20 Nov 2008 00:47:31 -0800 (PST) Return-Path: <vovanhaiqn@yahoo.com> Received: from web36102.mail.mud.yahoo.com (web36102.mail.mud.yahoo.com [66.163.179.216]) by mx.google.com with SMTP id k7si369877qba.3.2008.11.20.00.47.29; Thu, 20 Nov 2008 00:47:30 -0800 (PST) Received-SPF: pass (google.com: domain of vovanhaiqn@yahoo.com designates 66.163.179.216 as permitted sender) client-ip=66.163.179.216; DomainKey-Status: good (test mode) Authentication-Results: mx.google.com; spf=pass (google.com: domain of vovanhaiqn@yahoo.com designates 66.163.179.216 as permitted sender) smtp.mail=vovanhaiqn@yahoo.com; domainkeys=pass (test mode) header.From=vovanhaiqn@yahoo.com Received: (qmail 28383 invoked by uid 60001); 20 Nov 2008 08:47:29 -0000 DomainKey-Signature: a=rsa-sha1; q=dns; c=nofws; s=s1024; d=yahoo.com; h=X-YMail-OSG:Received:X-Mailer:Date:From:Reply-To:Subject:To:MIME-Version:Content-Type:Message-ID; b=1N2bi6C3FmrX+VPea/njJFHmTnGFQ79aRqk1M7NPeFYOf9afjf33QoxvtT8zGozi0KA4Fa2mA0tJdOyWCB+GK5pust7WVSIEtVtER2xetb6QllkTTt32LEZjzK5URWsNbHtxR8+U6/7KcaCoYLWh+g+7KLUgRaZwqWwm7C1e9wc=; X-YMail-OSG: CqyskJwVM1lT3VdlWIcAzyLCxNqdeSSPaxb6FEghM57FfyBVxvFZ5ELBzRrzE3frzBxoQACbbIc_nmH3hLj7VP1mCJs1CJO8AwtxgAukvknchUVa6XrWTA6UIX_68OdpZHIpsaWkxph6ou3ML6_XsuRg9c1lqpCdOuI1pXpuiyDScPDwQSq.muVktPT0 Received: from [203.162.3.168] by web36102.mail.mud.yahoo.com via HTTP; Thu, 20 Nov 2008 00:47:29 PST X-Mailer: YahooMailWebService/0.7.260.1 Date: Thu, 20 Nov 2008 00:47:29 -0800 (PST) From: vo van hai <vovanhaiqn@yahoo.com> Reply-To: vovanhaiqn@yahoo.com Subject: read mail with java To: nth001@gmail.com MIME-Version: 1.0 Content-Type: multipart/alternative; boundary=”0-1081161653-1227170849=:28212″ Message-ID: <681888.28212.qm@web36102.mail.mud.yahoo.com> –0-1081161653-1227170849=:28212 =C4=90=E1=BB=8Dc gmail v=E1=BB=9Bi JavaMail t=E1=BB=AB http://vovanhai.word= <table cellspacing=3D”0″ cellpadding=3D”0″ border=3D”0″ ><tr><td valign=3D”= |
aaaa said
code này chạy bằng chương trình gì? ví dụ chạy trên eclipse sẻver tom cat dc ko hay là cái gì khác
Abac said
chỉ tui cách chạy đoạn code này với ,chạy như thế nào đẻ nhận thư vậy .Sớm nha Thanks……
vovanhai said
Chạy bình thường. có hàm main mà!
cmd:
java POP3Client
lại Việt anh said
Cảm ơn về bài viết
Nhat said
Làm ơn cho em hỏi cái này làm sao để mình lấy được nội dung của email vậy?
Trọng Long said
Rất cám ơn tác giả. Mình đã làm theo hướng dẫn và thành công với Gmail.
Hiện tại mình đang chạy mail server là Mdaemon ver11, mình muốn sử dụng đoạn code trên để gửi và nhận mail trên server này. Mình đã thay đổi thông số và đã gửi được mail với các thông số mail server của mình, tuy nhiên phần nhận mail thì có gặp trục trặc:
javax.mail.MessagingException: Connect failed;nested exception is:
java.net.SocketException: Network is unreachable: connect
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:176)
at javax.mail.Service.connect(Service.java:291)
at javax.mail.Service.connect(Service.java:172)
at POP3Client.main(POP3Client.java:59)
Caused by: java.net.SocketException: Network is unreachable: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:550)
at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:141)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:284)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227)
at com.sun.mail.pop3.Protocol.(Protocol.java:98)
at com.sun.mail.pop3.POP3Store.getPort(POP3Store.java:227)
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:172)
... 3 more
Mình xin hỏi đây là lỗi gì? và Provider: Pop3s ở đây có cần thay đổi không-hay là áp dụng chung cho các mail server?
thai vu said
anh Hải cho hỏi dùng gói Javamail API để làm trên giao diện được k
Võ Văn Hải said
Anh dùng ở đâu cũng được mà!
minh said
chỉ đọc đc những mail mới gửi đến chứ ko đọc đc những mail đã đọc.
thuy said
chỉ đọc được những mail vừa mới nhận, những mail đã được đọc thì ko xem đc. làm thế nào bây h
thuy said
chạy không ổn định, lúc thì ra lúc ko ra. thử các hòm thư gmail khác nhau, mỗi cái ra một kiểu. cái hiện thư cái thì hiện thiếu. chắc do gmail
^^
thuy said
lúc xem đc nội dung lúc thì không ra. thế mới tức chứ !
Hungnt said
Em làm theo bài viết của thầy. đã chạy được nhưng làm sao tách riêng tiêu đề,nội dung ra để đưa lên Jtable. Thầy cho em xin đoạn code đó được không thầy.
Baoyen said
Minh dung giao thuc POS3 de nhan mail nhu tren nhung tai sao minh chi nhan duoc nhung mail moi ma thoi, con nhung mail cu minh da doc thi khong nhan duoc nua
Võ Văn Hải said
Không phải POS3 mà là POP3. Để lấy được những mail đã đọc thì bạn phải tìm hiểu thêm thôi.
sangkien said
Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\kien>e:
E:\>cd MAIL
E:\MAIL>javac -d . NhanMail.java
NhanMail.java:13: class POP3Client is public, should be declared in a file named
POP3Client.java
public class POP3Client {
^
1 error
E:\MAIL>
chao anh em da chay phan gui mail o bai truoc cua anh nhung toi phan nhan mail nay khi bien dich bi loi nhu tren khong cahy duoc. Vay anh cho biet la loi gi kg? Thieu