Last active
August 1, 2017 02:34
-
-
Save alamenai/aeb369d14243512dce34a1b54da43e97 to your computer and use it in GitHub Desktop.
Receive mail using java mail API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* To change this license header, choose License Headers in Project Properties. | |
* To change this template file, choose Tools | Templates | |
* and open the template in the editor. | |
*/ | |
package SimpleMail; | |
import com.sun.mail.pop3.POP3Store; | |
import java.io.IOException; | |
import java.util.Properties; | |
import javax.mail.Authenticator; | |
import javax.mail.Folder; | |
import javax.mail.Message; | |
import javax.mail.MessagingException; | |
import javax.mail.NoSuchProviderException; | |
import javax.mail.PasswordAuthentication; | |
import javax.mail.Session; | |
import javax.mail.Store; | |
/** | |
* | |
* @author Ala_Eddine | |
*/ | |
public class ReceiveMail { | |
public static void receiveEmail(String pop3Host, String storeType, | |
String user, String password) throws NoSuchProviderException, MessagingException { | |
Properties properties = new Properties(); | |
properties.setProperty("mail.host", "imap.gmail.com"); | |
properties.setProperty("mail.port", "995"); | |
properties.setProperty("mail.transport.protocol", "imaps"); | |
properties.put("mail.debug", "true"); | |
Session session = Session.getInstance(properties, | |
new javax.mail.Authenticator() { | |
@Override | |
protected PasswordAuthentication getPasswordAuthentication() { | |
return new PasswordAuthentication(user, password); | |
} | |
}); | |
session.setDebug(true); | |
Store store = session.getStore("imaps"); | |
store.connect(); | |
Folder inbox = store.getFolder("Inbox"); | |
inbox.open(Folder.READ_ONLY); | |
// get the list of inbox messages | |
Message[] messages = inbox.getMessages(); | |
if (messages.length == 0) { | |
System.out.println("No messages found."); | |
} | |
for (int i = 0; i < messages.length; i++) { | |
// stop after listing ten messages | |
if (i > 10) { | |
System.exit(0); | |
inbox.close(true); | |
store.close(); | |
} | |
System.out.println("Message " + (i + 1)); | |
System.out.println("From : " + messages[i].getFrom()[0]); | |
System.out.println("Subject : " + messages[i].getSubject()); | |
System.out.println("Sent Date : " + messages[i].getSentDate()); | |
System.out.println(); | |
} | |
inbox.close(true); | |
store.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment