Created
February 16, 2019 16:12
-
-
Save DeBukkIt/cdb697bf45bf15fe83e67e6a5256a8d6 to your computer and use it in GitHub Desktop.
This file contains 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
package com.blogspot.debukkitsblog.mailing; | |
import java.io.IOException; | |
import java.util.Arrays; | |
import java.util.Properties; | |
import javax.mail.Flags; | |
import javax.mail.Folder; | |
import javax.mail.Message; | |
import javax.mail.MessagingException; | |
import javax.mail.Session; | |
import javax.mail.Store; | |
import com.sun.mail.imap.IMAPStore; | |
public class StartMailEmpfaenger { | |
public static void main(String[] args) { | |
try { | |
MailEmpfaenger empf = new MailEmpfaenger(); | |
empf.login("imap.gmail.com", "993", Zugangsdaten.USERNAME(), Zugangsdaten.PASSWORD()); | |
empf.check(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
public static class MailEmpfaenger { | |
protected IMAPStore imapStore; | |
public void login(String host, String port, String username, String password) throws MessagingException { | |
Properties props = new Properties(); | |
props.put("mail.store.protocol", "imaps"); | |
props.put("mail.imaps.port", port); | |
props.put("mail.imaps.starttls.enable", "true"); | |
Session mailSession = Session.getDefaultInstance(props); | |
Store store = mailSession.getStore("imaps"); | |
store.connect(host, username, password); | |
this.imapStore = (IMAPStore) store; | |
} | |
public void check() throws MessagingException, IOException { | |
if(imapStore == null) { | |
throw new IllegalStateException("Du musst dich zuerst einloggen (login()-Methode)!"); | |
} | |
Folder mailFolder = imapStore.getFolder("INBOX"); | |
mailFolder.open(Folder.READ_ONLY); | |
System.out.println("Anzahl E-Mails: " + mailFolder.getMessageCount()); | |
System.out.println("-- davon ungelesen: " + mailFolder.getUnreadMessageCount()); | |
Message[] messages = mailFolder.getMessages(mailFolder.getMessageCount() - 10, mailFolder.getMessageCount()); | |
System.out.println("\n== Alle ungelesenen Nachrichten =="); | |
for(int i = 0; i < messages.length; i++) { | |
Message aktuelleMessage = messages[i]; | |
if(!aktuelleMessage.isSet(Flags.Flag.SEEN)) { | |
System.out.println(" Datum/Uhrzeit: " + aktuelleMessage.getReceivedDate()); | |
System.out.println(" Von: " + Arrays.toString(aktuelleMessage.getFrom())); | |
System.out.println(" Betreff: " + aktuelleMessage.getSubject()); | |
System.out.println(" Inhalt: " + aktuelleMessage.getContent()); | |
} | |
} | |
System.out.println("== Ende der ungelesenen Nachrichten =="); | |
mailFolder.close(); | |
imapStore.close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment