简体   繁体   中英

How to constantly check for incoming mail?

I'm busy developing an application that would have to constantly check for incoming mail on a specific email address. Once this email is read the program will reply.

I've been searching the net but haven't found something constructive as I haven't programmed/worked much with POP3 mails etc and just need a nudge in the right direction.

What would be the best way to constantly check for incoming mails?

Some email servers have a pushing system.

POP uses by definition a pull mechanism, so that won't work what so ever.

Your options:

  1. Implement a pulling mechanism and check every minute or so;
  2. Use another way to integrate with your mail server, maybe you can use EWS when using Exchange (I am not sure whether it supports push, but I thought to).

If you must stick to POP3 to retrieve your mails, you won't have any other options than polling. POP3 is an old mail protocol which doesn't offer any mechanism to let the mail server notify its clients when new messages are received.

If you can use another protocol, you could switch to IMAP4, which is supported by most email servers nowadays. The IMAP protocol offers an IDLE command which allows a client to keep his socket open, waiting for notifications from the mail server. The client doesn't have to poll the server anymore to find out if there are any new messages, it will get a notification as soon as a new message is received (along with notifications for message deletion, folders creation, etc.)

Unfortunately :

  • there's currently no built-in support for IMAP in the .Net framework. But there are many third party alternatives (check this SO thread for examples)
  • IMAP is way more complex than POP3. If you want a quick and simple solution, stick to POP3 polling.

As mentionned by Patrick Hofman, Exchange Web Services (EWS) would also offer you a way to get notifications when a new message is received. There's also a .Net managed API provided by Microsoft, sparing you the hassle of working directly with the EWS SOAP API. However, this would work only with Exchange servers, and the EWS feature would have to be enabled on Exchange.

I use DispatcherTimer to do it every x seconds, like this:

        _timer = new DispatcherTimer();
        _timer.Tick += (s, e) => Sync();
        _timer.Interval = new TimeSpan(0, 0, syncTime);
        _timer.Start();

Where Sync() is function that synchronizes with POP3 server and downloads messages, and syncTime is time in seconds between each synch. Of course You would have to use Your Reply method instead of Sync() if You only wanna reply.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM