CORE
HOME > JAVA > J2SE > CORE
2022.06.05 / 23:29

IMAP À̸ÞÀÏÀ» °¡Á®¿À´Â »ùÇà ¼Ò½º

ŹÃÄ
Ãßõ ¼ö 182
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.search.FlagTerm;
/**
 * IMAP À̸ÞÀÏÀ» °¡Á®¿À´Â »ùÇà ¼Ò½º
 *  - ÁÖÀÇ: °£´ÜÈ÷ POCÇÑ ¼Ò½º¶ó¼­ ¿¹¿Üó¸® ¹× ºÎ°¡Ã³¸®´Â ¿Ïº®È÷ ¾ÈµÇ¾î ÀÖÀ½
 *
 * @author ¾ö½ÂÇÏ
 */
public class IMAPEmailGetSample {
     public static void main(String[] args) throws Exception {
          System.out.println("-- IMAP Emal °¡Á®¿À±â: Start\n\n");
          String host = "ÀÔ·ÂÇÊ¿ä"; //imap È£½ºÆ® ÁÖ¼Ò. ex) imap.gmail.com
          String userEmail = "ÀÔ·ÂÇÊ¿ä"; //À¯Àú À̸ÞÀÏ ÁÖ¼Ò
          String password = "ÀÔ·ÂÇÊ¿ä"; //À¯Àú ¾ÏÈ£
          IMAPMailService mailService = new IMAPMailService();
          mailService.login(host, userEmail, password);
          int messageCount = mailService.getMessageCount();
          //Å×½ºÆ® ¸ñÀûÀÌ¶ó¼­ 5°³ ÃÊ°úÀ̸é 5°³¸¸ ó¸®: TODO »èÁ¦
          if (messageCount > 5) {
               messageCount = 5;
          }
          Message[] msgArray = mailService.getMessages(false);
          for (int i = 0; i < messageCount; i++) {
               Message msg = msgArray[i];
               if (msg.getSubject() != null) {
                    System.out.println(String.format("ÄÁÅÙÃ÷ŸÀÓ: %s", msg.getContentType()));
                    System.out.println(String.format("¹ß½ÅÀÚ[0]: %s", msg.getFrom()[0]));
                    System.out.println(String.format("¸ÞÀÏÁ¦¸ñ: %s", msg.getSubject()));
                    String mailText = mailService.getEmalText(msg.getContent());
                    System.out.println(String.format("¸ÞÀϳ»¿ë: %s", mailText));
               }
          }
          mailService.logout(); //·Î±×¾Æ¿ô
          System.out.println("\n\n-- IMAP Emal °¡Á®¿À±â: Á¾·á");
     }
}
/**
 * IMAP °ü¸® innerŬ·¡½º
 *  - Âü°í: https://javapapers.com/java/receive-email-in-java-using-javamail-gmail-imap-example/
 * 
 * @author ¾ö½ÂÇÏ
 */
class IMAPMailService {
     private Session session;
     private Store store;
     private Folder folder;
     // hardcoding protocol and the folder
     // it can be parameterized and enhanced as required
     private String protocol = "imaps";
     private String file = "INBOX";
     public IMAPMailService() {
     }
     public boolean isLoggedIn() {
          return store.isConnected();
     }
     /**
      * ¸ÞÀÏ º»¹® ÅؽºÆ® ³»¿ëÀ» °¡Á®¿È
      *
      * @param content
      * @return
      * @throws Exception
      */
     public String getEmalText(Object content) throws Exception {
          //TODO: °³¹ß ÇÊ¿ä
          System.out.println("####  ÄÁÅÙÃ÷ ŸÀÔ¿¡ µû¶ó¼­ text body ¶Ç´Â ¸ÖƼÆÄÆ® ó¸® ±â´É ±¸ÇöÀÌ ÇÊ¿ä");
          if (content instanceof Multipart) {
               System.out.println("Multipart À̸ÞÀÏÀÓ");
          } else {
               System.out.println(content);
          }
          return null;
     }
     /**
      * to login to the mail host server
      */
     public void login(String host, String username, String password) throws Exception {
          URLName url = new URLName(protocol, host, 993, file, username, password);
          if (session == null) {
               Properties props = null;
               try {
                    props = System.getProperties();
               } catch (SecurityException sex) {
                    props = new Properties();
               }
               session = Session.getInstance(props, null);
          }
          store = session.getStore(url);
          store.connect();
          folder = store.getFolder("inbox"); //inbox´Â ¹ÞÀº ¸ÞÀÏÇÔÀ» ÀǹÌ
          //folder.open(Folder.READ_WRITE);
          folder.open(Folder.READ_ONLY); //Àбâ Àü¿ë
     }
     /**
      * to logout from the mail host server
      */
     public void logout() throws MessagingException {
          folder.close(false);
          store.close();
          store = null;
          session = null;
     }
     public int getMessageCount() {
          //TODO: ¾È ÀÐÀº ¸ÞÀÏÀÇ °Ç¼ö¸¸ Á¶È¸ÇÏ´Â ±â´É Ãß°¡
          int messageCount = 0;
          try {
               messageCount = folder.getMessageCount();
          } catch (MessagingException me) {
               me.printStackTrace();
          }
          return messageCount;
     }
     /**
      * À̸ÞÀÏ ¸®½ºÆ®¸¦ °¡Á®¿È
      *
      * @param onlyNotRead ¾ÈÀÐÀº ¸ÞÀÏ ¸®½ºÆ®¸¸ °¡Á®¿ÃÁö ¿©ºÎ
      * @return
      * @throws MessagingException
      */
     public Message[] getMessages(boolean onlyNotRead) throws MessagingException {
          if (onlyNotRead) {
               return folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
          } else {
               return folder.getMessages();
          }
     }
}

Ãâó: https://blog.eomsh.com/86 [°³¹ßÀÚÀÇ ÀÏ»ó:Ƽ½ºÅ丮]