Wednesday, November 10, 2010

Accessing Gmail SMTP through JAVA

import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;


public class GmailTest {

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 = "gmailid";
private static final String SMTP_AUTH_PWD = "password";

public static void main(String[] args) throws Exception{
new GmailTest().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");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", SMTP_AUTH_USER, SMTP_AUTH_PWD);
FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.search(ft);
for(Message message1:messages) {
System.out.println(message1.getAllHeaders().nextElement());
}
}
}