2011-05-04 2 views
0

최근에 저는 javamail API를 사용하여 Exchange 서버에서 이메일을 검색하는 작업을 시작했습니다. 그러나 Outlook 클라이언트가 메일 서버와 동기화되고 따라서 해당 전자 메일이 서버에서 제거되므로 가끔 메일을 가져올 수 없습니다. Outlook 동기화 전후에 관계없이 모든 새 전자 메일을 가져올 수있는 방법이 있습니까? 아니면 Outlook에 연결해야합니까? 그렇다면 사용 가능한 무료 API가 있습니까? 고맙습니다.Outlook에서 이메일을 읽는 법

답변

1

Outlook에서 메시지 사본을 서버에 남겨 둘 수 없습니까? 나는 전망에의 연결이 갈 길이라는 것을 정말로 생각하지 않는다.

+0

덕분에 매일 오는 큰 첨부 파일이있는 많은 메일이있다, 나는 그것이 서버에 chanllenge 될 것입니다 두렵다. – user737570

+0

방법 : outlook에서 메일 규칙을 구성하여 다른 폴더로 이동 시키지만 (서버에서 계속 유지), 해당 폴더의 모든 메일을 처리하고 처리 한 후 서버에서 삭제할 수 있습니까? – Pleun

+0

@Pleun, Outlook 폴더를 의미합니까? Outlook받은 편지함 폴더에서 읽는 방법? –

0

Outlook에서 이메일을 읽을 수있는 해결책이 있습니다. 사용자 이름, 비밀번호, 도메인 및 교환 주소를 제공해야합니다 : https://webmail.**companynameXYZ**.com/ews/exchange.asmx.

다음은 코드입니다. 나는 이것을 읽지 않은 메일에서 첨부 파일을 다운로드하고 다운로드 한 후 읽는 용도로 사용했습니다. 참고 : 우리가 필요로하는 DLL Microsoft.Exchange.WebServices.dll는 C#으로

코드를 다운로드 할 :

string _username = string.Empty; 
      string _password = string.Empty; 
      string _domain = "us"; 
      string _exchange = string.Empty; 

      _username = ConfigurationSettings.AppSettings["Username"].ToString(); 
      _password = ConfigurationSettings.AppSettings["Pasword"].ToString(); 
      _exchange = ConfigurationSettings.AppSettings["MailServer"].ToString(); 

      ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); 
      // service.AutodiscoverUrl("[email protected]");    
      service.Url = new Uri(_exchange); 
      service.Credentials = new WebCredentials(_username, _password, _domain); 

      FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10)); 
      int attachmentCount = 0; 
      foreach (Item item in findResults.Items) 
      { 
       // Bind to an existing message item, requesting its Id property plus its attachments collection. 
       EmailMessage message = EmailMessage.Bind(service, item.Id); 

       //read only unread mails and has attachemnts to it. 
       if ((!message.IsRead) && message.HasAttachments) 
       {     
        Console.WriteLine(item.Subject); 

        #region Iterate through the attachments collection and load each attachment. 
        foreach (Microsoft.Exchange.WebServices.Data.Attachment attachment in message.Attachments) 
        {  
         if (attachment is FileAttachment) 
         { 
          FileAttachment fileAttachment = attachment as FileAttachment; 
          attachmentCount++; 
          // Load the file attachment into memory and print out its file name. 
          fileAttachment.Load(); 
          Console.WriteLine("Attachment name: " + fileAttachment.Name); 

          //create Attachments-folder if not exists. 
          if (!Directory.Exists(@"C:\Attachments\")) 
          { 
           Directory.CreateDirectory(@"C:\Attachments\"); 
          } 
          // Load attachment contents into a file. 
          fileAttachment.Load("C:\\attachments\\" + fileAttachment.Name); 

         } 
         else // Attachment is an item attachment. 
         { 
          // Load attachment into memory and write out the subject. 
          ItemAttachment itemAttachment = attachment as ItemAttachment; 
          itemAttachment.Load(); 
          Console.WriteLine("Subject: " + itemAttachment.Item.Subject); 
         } 

        }//for inner 
        #endregion 

        //mark as READ 
        message.IsRead = true; 
        message.Update(ConflictResolutionMode.AlwaysOverwrite); 
        Console.WriteLine("------------------------"); 
       }//if 



      }//for outer 
0

자바 코드 : 답장을 보내

package EWSGetDetailsOffice365; 

import java.text.SimpleDateFormat; 
import java.util.ArrayList; 
import java.util.Calendar; 
import java.util.Date; 
import java.util.HashMap; 
import java.util.List; 

import java.util.Map; 

import java.util.logging.Level; 
import java.util.logging.Logger; 

import microsoft.exchange.webservices.data.Appointment; 
import microsoft.exchange.webservices.data.AppointmentSchema; 
import microsoft.exchange.webservices.data.CalendarFolder; 
import microsoft.exchange.webservices.data.CalendarView; 
import microsoft.exchange.webservices.data.EmailMessage; 
import microsoft.exchange.webservices.data.ExchangeService; 
import microsoft.exchange.webservices.data.ExchangeVersion; 
import microsoft.exchange.webservices.data.FindItemsResults; 
import microsoft.exchange.webservices.data.Folder; 
import microsoft.exchange.webservices.data.IAutodiscoverRedirectionUrl; 
import microsoft.exchange.webservices.data.Item; 
import microsoft.exchange.webservices.data.ItemId; 
import microsoft.exchange.webservices.data.ItemSchema; 
import microsoft.exchange.webservices.data.ItemView; 
import microsoft.exchange.webservices.data.PropertySet; 
import microsoft.exchange.webservices.data.SearchFilter; 
import microsoft.exchange.webservices.data.ServiceLocalException; 
import microsoft.exchange.webservices.data.WebCredentials; 
import microsoft.exchange.webservices.data.WellKnownFolderName; 

public class MSExchangeEmailService { 

    public static class RedirectionUrlCallback implements IAutodiscoverRedirectionUrl { 
     public boolean autodiscoverRedirectionUrlValidationCallback(String redirectionUrl) { 
      return redirectionUrl.toLowerCase().startsWith("https://"); 
     } 
    } 

    private static ExchangeService service; 
    private static Integer NUMBER_EMAILS_FETCH =5; // only latest 5 emails/appointments are fetched. 
    /** 
    * Firstly check, whether "https://webmail.xxxx.com/ews/Services.wsdl" and "https://webmail.xxxx.com/ews/Exchange.asmx" 
    * is accessible, if yes that means the Exchange Webservice is enabled on your MS Exchange. 
    */ 
    static{ 
     try{ 
      service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); 
      //service.setUrl(new URI("https://webmail.xxxx.com/ews/Exchange.asmx")); 


     }catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
    /** 
    * Initialize the Exchange Credentials. 
    * Don't forget to replace the "USRNAME","PWD","DOMAIN_NAME" variables. 
    */ 
    public MSExchangeEmailService() { 
     service.setCredentials(new WebCredentials("[email protected]", "1234")); 
     try { 
      service.autodiscoverUrl("[email protected]", new RedirectionUrlCallback()); 
     } catch (Exception ex) { 
      Logger.getLogger(MSExchangeEmailService.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     service.setTraceEnabled(true); 
    } 
    /** 
    * Reading one email at a time. Using Item ID of the email. 
    * Creating a message data map as a return value. 
    */ 
    public Map readEmailItem(ItemId itemId){ 
     Map messageData = new HashMap(); 
     try{ 
      Item itm = Item.bind(service, itemId, PropertySet.FirstClassProperties); 
      EmailMessage emailMessage = EmailMessage.bind(service, itm.getId()); 
      messageData.put("emailItemId", emailMessage.getId().toString()); 
      messageData.put("subject", emailMessage.getSubject().toString()); 
      messageData.put("fromAddress",emailMessage.getFrom().getAddress().toString()); 
      messageData.put("senderName",emailMessage.getSender().getName().toString()); 
      Date dateTimeCreated = emailMessage.getDateTimeCreated(); 
      messageData.put("SendDate",dateTimeCreated.toString()); 
      Date dateTimeRecieved = emailMessage.getDateTimeReceived(); 
      messageData.put("RecievedDate",dateTimeRecieved.toString()); 
      messageData.put("Size",emailMessage.getSize()+""); 
      messageData.put("emailBody",emailMessage.getBody().toString()); 
     }catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return messageData; 
    } 
    /** 
    * Number of email we want to read is defined as NUMBER_EMAILS_FETCH, 
    */ 
    public List readEmails(){ 
     List msgDataList = new ArrayList(); 
     try{ 
      Folder folder = Folder.bind(service, WellKnownFolderName.Inbox); 
      FindItemsResults<Item> results = service.findItems(folder.getId(), new ItemView(NUMBER_EMAILS_FETCH)); 
      int i =1; 
      for (Item item : results){ 
       Map messageData = new HashMap(); 
       messageData = readEmailItem(item.getId()); 
       System.out.println("\nEmails #" + (i++) + ":"); 
       System.out.println("subject : " + messageData.get("subject").toString()); 
       System.out.println("Sender : " + messageData.get("senderName").toString()); 
       msgDataList.add(messageData); 
      } 
     }catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return msgDataList; 
    } 
    /** 
    * Reading one appointment at a time. Using Appointment ID of the email. 
    * Creating a message data map as a return value. 
    */ 
    public Map readAppointment(Appointment appointment){ 
     Map appointmentData = new HashMap(); 
     try { 
      appointmentData.put("appointmentItemId", appointment.getId().toString()); 
      appointmentData.put("appointmentSubject", appointment.getSubject()); 
      appointmentData.put("appointmentStartTime", appointment.getStart()+""); 
      appointmentData.put("appointmentEndTime", appointment.getEnd()+""); 
      //appointmentData.put("appointmentBody", appointment.getBody().toString()); 
     } catch (ServiceLocalException e) { 
      e.printStackTrace(); 
     } 
     return appointmentData; 
    } 
    /** 
     *Number of Appointments we want to read is defined as NUMBER_EMAILS_FETCH, 
     * Here I also considered the start data and end date which is a 30 day span. 
     * We need to set the CalendarView property depending upon the need of ours. 
    */ 
    public List readAppointments(){ 
     List apntmtDataList = new ArrayList(); 
     Calendar now = Calendar.getInstance(); 
     Date startDate = Calendar.getInstance().getTime(); 
     now.add(Calendar.DATE, 30); 
       Date endDate = now.getTime(); 
     try{ 
      CalendarFolder calendarFolder = CalendarFolder.bind(service, WellKnownFolderName.Calendar, new PropertySet()); 
      CalendarView cView = new CalendarView(startDate, endDate, 5); 
      cView.setPropertySet(new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End));// we can set other properties as well depending upon our need. 

      //FindItemsResults appointments = calendarFolder.findAppointments(cView); 
      FindItemsResults<Appointment> appointments = calendarFolder.findAppointments(cView); 
      System.out.println("|------------------> Appointment count = " + appointments.getTotalCount()); 
      int i =1; 
      //List appList = appointments.getItems(); 
      for (Appointment appointment : appointments.getItems()) { 
       System.out.println("\nAPPOINTMENT #" + (i++) + ":"); 
       Map appointmentData = new HashMap(); 
       appointmentData = readAppointment(appointment); 
       System.out.println("subject : " + appointmentData.get("appointmentSubject").toString()); 
       System.out.println("On : " + appointmentData.get("appointmentStartTime").toString()); 
       apntmtDataList.add(appointmentData); 
      } 
     }catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return apntmtDataList; 
    } 

    public static void getAllMeetings() throws Exception { 

    try { 

     SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");  
     Date startDate = formatter.parse("2016-01-01 00:00:00"); 

     SearchFilter filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.LastModifiedTime,startDate); 

     FindItemsResults<Item> findResults = service.findItems(WellKnownFolderName.Calendar, filter, new ItemView(1000)); 
     System.out.println("|------------------> meetings count = " + findResults.getTotalCount()); 

     for (Item item : findResults.getItems()) 
     { 
      Appointment appt = (Appointment)item; 
      //appt.setStartTimeZone(); 
      System.out.println("TimeZone====="+appt.getTimeZone()); 
      System.out.println("SUBJECT====="+appt.getSubject()); 
      System.out.println("Location========"+appt.getLocation()); 
      System.out.println("Start Time========"+appt.getStart()); 
      System.out.println("End Time========"+appt.getEnd()); 
      System.out.println("Email Address========"+ appt.getOrganizer().getAddress()); 
      System.out.println("Last Modified Time========"+appt.getLastModifiedTime()); 
      System.out.println("Last Modified Time========"+appt.getLastModifiedName()); 
      System.out.println("*************************************************\n"); 
     } 
    } catch (Exception exp) { 
     exp.printStackTrace(); 
    } 
    } 

    public static void main(String[] args) { 
     MSExchangeEmailService msees = new MSExchangeEmailService(); 
     //msees.readEmails(); 
     //msees.readAppointments(); 
     try { 
      msees.getAllMeetings(); 
     } catch (Exception ex) { 
      Logger.getLogger(MSExchangeEmailService.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 
}