2009-01-27 55 views
10

Tôi cần một thư viện cho phép tôi thực hiện các thao tác email (ví dụ: thư đã gửi/nhận) trong Gmail bằng cách sử dụng Java.Truy cập gmail từ Java

+6

Thiệt hại, Google có xuống nữa không? – Bombe

+1

Qua IMAP? Qua POP3/SMTP? Cung cấp thêm thông tin, nếu không thì đó là câu hỏi "Hỏi Google". – guerda

Trả lời

13

Bạn đã xem g4j - GMail API for Java chưa?

API GMailer cho Java (g4j) được đặt là API cho phép lập trình Java liên lạc với GMail. Với G4J , các lập trình viên có thể thực hiện ứng dụng dựa trên bộ nhớ rất lớn của Gmail.

+0

Điều gì về việc sử dụng pop3? Và không g4j ở hiện tại khi/nếu gmail cập nhật/thay đổi khách hàng rendererd html của họ? – Zombies

1

Trước tiên, định cấu hình tài khoản Gmail của bạn để chấp nhận quyền truy cập POP3. Sau đó, chỉ cần truy cập tài khoản thư của bạn bằng cách sử dụng Javamail!

+1

thậm chí tốt hơn: IMAP – jamesh

9

Bạn có thể sử dụng Javamail cho điều đó. Điều cần ghi nhớ là GMail sử dụng SMTPS chứ không phải SMTP.

import javax.mail.*; 
import javax.mail.internet.*; 

import java.util.Properties; 


public class SimpleSSLMail { 

    private static final String SMTP_HOST_NAME = "smtp.gmail.com"; 
    private static final int SMTP_HOST_PORT = 465; 
    private static final String SMTP_AUTH_USER = "[email protected]"; 
    private static final String SMTP_AUTH_PWD = "mypwd"; 

    public static void main(String[] args) throws Exception{ 
     new SimpleSSLMail().test(); 
    } 

    public void test() throws Exception{ 
     Properties props = new Properties(); 

     props.put("mail.transport.protocol", "smtps"); 
     props.put("mail.smtps.host", SMTP_HOST_NAME); 
     props.put("mail.smtps.auth", "true"); 
     // props.put("mail.smtps.quitwait", "false"); 

     Session mailSession = Session.getDefaultInstance(props); 
     mailSession.setDebug(true); 
     Transport transport = mailSession.getTransport(); 

     MimeMessage message = new MimeMessage(mailSession); 
     message.setSubject("Testing SMTP-SSL"); 
     message.setContent("This is a test", "text/plain"); 

     message.addRecipient(Message.RecipientType.TO, 
      new InternetAddress("[email protected]")); 

     transport.connect 
      (SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD); 

     transport.sendMessage(message, 
      message.getRecipients(Message.RecipientType.TO)); 
     transport.close(); 
    } 
} 

ref: Send email with SMTPS (eg. Google GMail) (Javamail)

Các vấn đề liên quan