Professional Applications Programmers/Consultants برمجة واستشارات تطبيقات الإنترنت
Skip Navigation LinksHome » Code Library » Imap

Public general use code classes and xml files that we've compiled and used over the years:

IMAP support class.

   1:  using System;
   2:  using System.Collections;
   3:  using System.Collections.Generic;
   4:  using System.ComponentModel;
   5:  using System.Data;
   6:  using System.Drawing;
   7:  using System.Text;
   8:  using System.Text.RegularExpressions;
   9:  using System.Configuration;
  10:  using ActiveUp.Net.Imap4;
  11:  using ActiveUp.Net.Mail;
  12:   
  13:  namespace Ia.Cl.Model
  14:  {
  15:      ////////////////////////////////////////////////////////////////////////////
  16:   
  17:      /// <summary publish="true">
  18:      /// IMAP support class.
  19:      /// </summary>
  20:      /// 
  21:      /// <see cref="http://www.skytale.net/blog/archives/23-Manual-IMAP.html"/>
  22:      /// <see cref="http://tools.ietf.org/html/rfc3501#page-51"/>
  23:      /// <see cref="https://www.aspsnippets.com/Articles/Fetch-and-read-email-messages-with-attachments-from-GMAIL-POP3-mail-server-in-ASPNet.aspx"/>
  24:      /// 
  25:      /// <remarks> 
  26:      /// Copyright © 2001-2015 Jasem Y. Al-Shamlan (info@ia.com.kw), Internet Applications - Kuwait. All Rights Reserved.
  27:      ///
  28:      /// This library is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
  29:      /// the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
  30:      ///
  31:      /// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
  32:      /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  33:      /// 
  34:      /// You should have received a copy of the GNU General Public License along with this library. If not, see http://www.gnu.org/licenses.
  35:      /// 
  36:      /// Copyright notice: This notice may not be removed or altered from any source distribution.
  37:      /// </remarks> 
  38:      public class Imap
  39:      {
  40:          private bool serverEnableSsl;
  41:          private string serverHost, serverUser, serverPassword, defaultMailbox;
  42:          private Imap4Client imap;
  43:   
  44:          ////////////////////////////////////////////////////////////////////////////
  45:   
  46:          /// <summary>
  47:          ///
  48:          /// </summary>
  49:          public class Message
  50:          {
  51:              /// <summary/>
  52:              public Message()
  53:              {
  54:                  this.Attachments = new List<Attachment>();
  55:              }
  56:   
  57:              /// <summary/>
  58:              public string MessageId { get; set; }
  59:   
  60:              /// <summary/>
  61:              public string From { get; set; }
  62:   
  63:              /// <summary/>
  64:              public string Subject { get; set; }
  65:              /// <summary/>
  66:              public string BodyText { get; set; }
  67:   
  68:              /// <summary/>
  69:              public DateTime Date { get; set; }
  70:   
  71:              /// <summary/>
  72:              public DateTime ReceivedDate { get; set; }
  73:   
  74:              /// <summary/>
  75:              public List<Attachment> Attachments { get; set; }
  76:   
  77:              /// <summary/>
  78:              public Message(string messageId, string from, string subject, string bodyText)
  79:              {
  80:                  this.MessageId = messageId;
  81:                  this.From = from;
  82:                  this.Subject = subject;
  83:                  this.BodyText = bodyText;
  84:              }
  85:          }
  86:   
  87:          ////////////////////////////////////////////////////////////////////////////
  88:   
  89:          /// <summary>
  90:          ///
  91:          /// </summary>
  92:          public class Header
  93:          {
  94:              /// <summary/>
  95:              public Header()
  96:              {
  97:              }
  98:   
  99:              /// <summary/>
 100:              public string MessageId { get; set; }
 101:              /// <summary/>
 102:              public string From { get; set; }
 103:              /// <summary/>
 104:              public string Subject { get; set; }
 105:              /// <summary/>
 106:              public DateTime Date { get; set; }
 107:              /// <summary/>
 108:              public DateTime ReceivedDate { get; set; }
 109:   
 110:              /// <summary/>
 111:              public Header(string messageId, string from, string subject)
 112:              {
 113:                  this.MessageId = messageId;
 114:                  this.From = from;
 115:                  this.Subject = subject;
 116:              }
 117:          }
 118:   
 119:          ////////////////////////////////////////////////////////////////////////////
 120:   
 121:          /// <summary>
 122:          ///
 123:          /// </summary>
 124:          public class Attachment
 125:          {
 126:              /// <summary/>
 127:              public string FileName { get; set; }
 128:              /// <summary/>
 129:              public string ContentType { get; set; }
 130:              /// <summary/>
 131:              public string Content { get; set; }
 132:          }
 133:   
 134:          ////////////////////////////////////////////////////////////////////////////
 135:   
 136:          /// <summary>
 137:          ///
 138:          /// </summary>
 139:          public Imap()
 140:          {
 141:              bool b;
 142:   
 143:              /*
 144:               * app.config
 145:               * <add key="imapServerHost" value="*" />
 146:               * <add key="imapServerUser" value="*" />
 147:               * <add key="imapServerPassword" value="*" />
 148:               * <add key="imapServerEnableSsl" value="*" /> 
 149:               */
 150:   
 151:              serverHost = ConfigurationManager.AppSettings["imapServerHost"].ToString();
 152:              serverUser = ConfigurationManager.AppSettings["imapServerUser"].ToString();
 153:              serverPassword = ConfigurationManager.AppSettings["imapServerPassword"].ToString();
 154:              serverEnableSsl = bool.TryParse(ConfigurationManager.AppSettings["imapServerEnableSsl"].ToString(), out b) ? b : false;
 155:   
 156:              Initialize();
 157:          }
 158:   
 159:          ////////////////////////////////////////////////////////////////////////////
 160:   
 161:          /// <summary>
 162:          ///
 163:          /// </summary>
 164:          public Imap(string _server, string _user, string _password, bool _useSsl)
 165:          {
 166:              this.serverHost = _server;
 167:              this.serverUser = _user;
 168:              this.serverPassword = _password;
 169:              this.serverEnableSsl = _useSsl;
 170:   
 171:              Initialize();
 172:          }
 173:   
 174:          ////////////////////////////////////////////////////////////////////////////
 175:   
 176:          /// <summary>
 177:          ///
 178:          /// </summary>
 179:          ~Imap()
 180:          {
 181:              Disconnect();
 182:          }
 183:   
 184:          ////////////////////////////////////////////////////////////////////////////
 185:   
 186:          /// <summary>
 187:          ///
 188:          /// </summary>
 189:          private void Initialize()
 190:          {
 191:              defaultMailbox = "Inbox";
 192:   
 193:              imap = new Imap4Client();
 194:   
 195:              this.Log("Initialize(): Imap object created");
 196:          }
 197:   
 198:          ////////////////////////////////////////////////////////////////////////////
 199:   
 200:          /// <summary>
 201:          ///
 202:          /// </summary>
 203:          public void Connect()
 204:          {
 205:              if (serverEnableSsl) imap.ConnectSsl(serverHost);
 206:              else imap.Connect(serverHost);
 207:   
 208:              this.Log("Connect(): Connection opened to " + serverHost);
 209:   
 210:              imap.Login(serverUser, serverPassword);
 211:   
 212:              this.Log(string.Format("Connect(): Login to '{0}' by user '{1}' successful", serverHost, serverUser));
 213:          }
 214:   
 215:          ////////////////////////////////////////////////////////////////////////////
 216:   
 217:          /// <summary>
 218:          ///
 219:          /// </summary>
 220:          public bool IsConnected
 221:          {
 222:              get
 223:              {
 224:                  this.Log("IsConnected: " + imap.IsConnected.ToString());
 225:   
 226:                  return imap.IsConnected;
 227:              }
 228:          }
 229:   
 230:          ////////////////////////////////////////////////////////////////////////////
 231:   
 232:          /// <summary>
 233:          ///
 234:          /// </summary>
 235:          public void Disconnect()
 236:          {
 237:              if (imap.IsConnected)
 238:              {
 239:                  try
 240:                  {
 241:                      imap.Disconnect();
 242:   
 243:                      this.Log("Disconnect(): Disconnected");
 244:                  }
 245:                  catch (Exception ex)
 246:                  {
 247:                      this.Log("Disconnect(): Exception: " + ex.ToString());
 248:                  }
 249:              }
 250:              else
 251:              {
 252:                  this.Log("Disconnect(): Already disconnected");
 253:              }
 254:          }
 255:   
 256:          ////////////////////////////////////////////////////////////////////////////
 257:   
 258:          /// <summary>
 259:          ///
 260:          /// </summary>
 261:          public List<string> MailboxList()
 262:          {
 263:              List<string> mailboxList;
 264:   
 265:              mailboxList = new List<string>(imap.Mailboxes.Count);
 266:   
 267:              foreach (Mailbox mailbox in imap.Mailboxes) mailboxList.Add(mailbox.Name);
 268:   
 269:              return mailboxList;
 270:          }
 271:   
 272:          ////////////////////////////////////////////////////////////////////////////
 273:   
 274:          /// <summary>
 275:          ///
 276:          /// </summary>
 277:          public void CreateMailbox(string mailboxName)
 278:          {
 279:              imap.CreateMailbox(mailboxName);
 280:          }
 281:   
 282:          ////////////////////////////////////////////////////////////////////////////
 283:   
 284:          /// <summary>
 285:          ///
 286:          /// </summary>
 287:          public string DeleteMailbox(string mailboxName)
 288:          {
 289:              return imap.DeleteMailbox(mailboxName);
 290:          }
 291:   
 292:          ////////////////////////////////////////////////////////////////////////////
 293:   
 294:          /// <summary>
 295:          ///
 296:          /// </summary>
 297:          public Header ReadHeader(Mailbox mailbox, int i)
 298:          {
 299:              Header header;
 300:              ActiveUp.Net.Mail.Header aHeader;
 301:   
 302:              header = new Header();
 303:   
 304:              try
 305:              {
 306:                  aHeader = mailbox.Fetch.HeaderObject(i);
 307:   
 308:                  header.MessageId = aHeader.MessageId;
 309:                  header.From = aHeader.From.Email;
 310:                  header.Subject = aHeader.Subject;
 311:   
 312:                  this.Log(string.Format("Success: Header read: {0},{1},{2}", header.MessageId, header.From, header.Subject));
 313:              }
 314:              catch (Imap4Exception iex)
 315:              {
 316:                  this.Log(string.Format("Imap4 Error: {0}", iex.Message));
 317:              }
 318:              catch (Exception ex)
 319:              {
 320:                  this.Log(string.Format("Failed: {0}", ex.Message));
 321:              }
 322:              finally
 323:              {
 324:              }
 325:   
 326:              return header;
 327:          }
 328:   
 329:          ////////////////////////////////////////////////////////////////////////////
 330:   
 331:          /// <summary>
 332:          ///
 333:          /// </summary>
 334:          public int MoveMessagesFromEmailToMailbox(string email, string destinationMailboxName)
 335:          {
 336:              int numberOfMessagesMoved;
 337:              int[] messageOrdinalList;
 338:              string searchPhrase;
 339:              Mailbox mailbox;
 340:   
 341:              numberOfMessagesMoved = 0;
 342:   
 343:              mailbox = imap.SelectMailbox(defaultMailbox);
 344:   
 345:              searchPhrase = @"FROM """ + email + @"""";
 346:   
 347:              messageOrdinalList = mailbox.Search(searchPhrase);
 348:   
 349:              if (messageOrdinalList != null && messageOrdinalList.Length > 0)
 350:              {
 351:                  // read message and check that from-email value before moving
 352:                  for (int i = messageOrdinalList.Length - 1; i >= 0; i--)
 353:                  {
 354:                      MoveMessage(mailbox, messageOrdinalList[i], destinationMailboxName);
 355:                      numberOfMessagesMoved++;
 356:                  }
 357:              }
 358:   
 359:              return numberOfMessagesMoved;
 360:          }
 361:   
 362:          ////////////////////////////////////////////////////////////////////////////
 363:   
 364:          /// <summary>
 365:          ///
 366:          /// </summary>
 367:          public void MoveMessage(string messageId, string destinationMailboxName)
 368:          {
 369:              int[] messageOrdinalList;
 370:              string searchPhrase;
 371:              Mailbox mailbox;
 372:              ActiveUp.Net.Mail.Header header;
 373:   
 374:              mailbox = imap.SelectMailbox(defaultMailbox);
 375:   
 376:              searchPhrase = @"ALL";
 377:   
 378:              messageOrdinalList = mailbox.Search(searchPhrase);
 379:   
 380:              if (messageOrdinalList != null && messageOrdinalList.Length > 0)
 381:              {
 382:                  for (int i = messageOrdinalList.Length - 1; i >= 0; i--)
 383:                  {
 384:                      header = mailbox.Fetch.HeaderObject(messageOrdinalList[i]);
 385:   
 386:                      if (header.MessageId == messageId)
 387:                      {
 388:                          MoveMessage(mailbox, messageOrdinalList[i], destinationMailboxName);
 389:   
 390:                          break;
 391:                      }
 392:                  }
 393:              }
 394:          }
 395:   
 396:          ////////////////////////////////////////////////////////////////////////////
 397:   
 398:          /// <summary>
 399:          ///
 400:          /// </summary>
 401:          public void MoveMessage(Mailbox mailbox, int messageOrdinal, string destinationMailboxName)
 402:          {
 403:              mailbox.MoveMessage(messageOrdinal, destinationMailboxName);
 404:   
 405:              this.Log("Move message: " + messageOrdinal + " to mailbox '" + destinationMailboxName + "'");
 406:          }
 407:   
 408:          ////////////////////////////////////////////////////////////////////////////
 409:   
 410:          /// <summary>
 411:          /// Message list from Inbox
 412:          /// </summary>
 413:          public void MessageList(out List<Message> messageList)
 414:          {
 415:              string searchPhrase;
 416:   
 417:              searchPhrase = "ALL";
 418:   
 419:              SearchPhraseMessageList(searchPhrase, out messageList);
 420:          }
 421:   
 422:          ////////////////////////////////////////////////////////////////////////////
 423:   
 424:          /// <summary>
 425:          /// List of messages from Inbox that were sent from email
 426:          /// </summary>
 427:          public void MessageList(string email, out List<Message> messageList)
 428:          {
 429:              string searchPhrase;
 430:   
 431:              searchPhrase = @"FROM """ + email + @"""";
 432:   
 433:              SearchPhraseMessageList(searchPhrase, out messageList);
 434:          }
 435:   
 436:          ////////////////////////////////////////////////////////////////////////////
 437:   
 438:          /// <summary>
 439:          ///
 440:          /// </summary>
 441:          private void SearchPhraseMessageList(string searchPhrase, out List<Message> messageList)
 442:          {
 443:              Message message;
 444:              Mailbox mailbox;
 445:              MessageCollection messageCollection;
 446:   
 447:              messageList = new List<Message>();
 448:   
 449:              mailbox = imap.SelectMailbox(defaultMailbox);
 450:   
 451:              try
 452:              {
 453:                  messageCollection = mailbox.SearchParse(searchPhrase);
 454:   
 455:                  foreach (ActiveUp.Net.Mail.Message m in messageCollection)
 456:                  {
 457:                      message = new Message();
 458:   
 459:                      message.MessageId = m.MessageId;
 460:                      message.From = m.From.Email;
 461:                      message.Subject = m.Subject;
 462:                      message.BodyText = m.BodyText.TextStripped;
 463:                      message.Date = m.Date;
 464:                      message.ReceivedDate = m.ReceivedDate;
 465:   
 466:                      foreach (ActiveUp.Net.Mail.MimePart mp in m.Attachments)
 467:                      {
 468:                          //if (mp.IsText)
 469:                          //{
 470:                              message.Attachments.Add(new Attachment
 471:                              {
 472:                                  FileName = mp.Filename,
 473:                                  ContentType = mp.ContentType.MimeType,
 474:                                  Content = mp.TextContent
 475:                              });
 476:                          //}
 477:                      }
 478:   
 479:                      messageList.Add(message);
 480:   
 481:                      this.Log(string.Format("Success: Message read: {0},{1},{2}", m.MessageId, m.From, m.Subject));
 482:                  }
 483:              }
 484:              catch (Imap4Exception iex)
 485:              {
 486:                  this.Log(string.Format("Imap4 Error: {0}", iex.Message));
 487:              }
 488:              catch (Exception ex)
 489:              {
 490:                  this.Log(string.Format("Failed: {0}", ex.Message));
 491:              }
 492:              finally
 493:              {
 494:              }
 495:          }
 496:   
 497:          ////////////////////////////////////////////////////////////////////////////
 498:   
 499:          /// <summary>
 500:          ///
 501:          /// </summary>
 502:          public List<Header> HeaderList(Mailbox mailbox)
 503:          {
 504:              Header header;
 505:              List<Header> headerList;
 506:              ActiveUp.Net.Mail.Header aHeader;
 507:   
 508:              headerList = new List<Header>(mailbox.MessageCount);
 509:   
 510:              try
 511:              {
 512:                  for (int i = 1; i <= mailbox.MessageCount; i++)
 513:                  {
 514:                      header = new Header();
 515:   
 516:                      aHeader = mailbox.Fetch.MessageObject(i);
 517:   
 518:                      header.MessageId = aHeader.MessageId;
 519:                      header.From = aHeader.From.Email;
 520:                      header.Subject = aHeader.Subject;
 521:   
 522:                      this.Log(string.Format("Success: Header read: {0},{1},{2}", header.MessageId, header.From, header.Subject));
 523:                  }
 524:              }
 525:              catch (Imap4Exception iex)
 526:              {
 527:                  this.Log(string.Format("Imap4 Error: {0}", iex.Message));
 528:              }
 529:              catch (Exception ex)
 530:              {
 531:                  this.Log(string.Format("Failed: {0}", ex.Message));
 532:              }
 533:              finally
 534:              {
 535:              }
 536:   
 537:              return headerList;
 538:          }
 539:   
 540:          ////////////////////////////////////////////////////////////////////////////
 541:   
 542:          /// <summary>
 543:          ///
 544:          /// </summary>
 545:          public void DeleteMessage(string messageId)
 546:          {
 547:              int[] messageOrdinalList;
 548:              string searchPhrase;
 549:              Mailbox mailbox;
 550:              ActiveUp.Net.Mail.Header header;
 551:   
 552:              mailbox = imap.SelectMailbox(defaultMailbox);
 553:   
 554:              searchPhrase = @"ALL";
 555:   
 556:              messageOrdinalList = mailbox.Search(searchPhrase);
 557:   
 558:              if (messageOrdinalList != null && messageOrdinalList.Length > 0)
 559:              {
 560:                  for (int i = messageOrdinalList.Length - 1; i >= 0; i--)
 561:                  {
 562:                      header = mailbox.Fetch.HeaderObject(messageOrdinalList[i]);
 563:   
 564:                      if (header.MessageId == messageId)
 565:                      {
 566:                          DeleteMessage(mailbox, messageOrdinalList[i]);
 567:                      }
 568:                  }
 569:              }
 570:          }
 571:   
 572:          ////////////////////////////////////////////////////////////////////////////
 573:   
 574:          /// <summary>
 575:          ///
 576:          /// </summary>
 577:          private void DeleteMessage(Mailbox mailbox, int messageOrdinal)
 578:          {
 579:              mailbox.DeleteMessage(messageOrdinal, true);
 580:   
 581:              this.Log("Delete message: " + messageOrdinal);
 582:          }
 583:   
 584:          ////////////////////////////////////////////////////////////////////////////
 585:   
 586:          /// <summary>
 587:          ///
 588:          /// </summary>
 589:          private void Log(string text)
 590:          {
 591:              string line;
 592:              DateTime now;
 593:   
 594:              now = DateTime.UtcNow.AddHours(3);
 595:   
 596:              line = now.ToString("yyyy-MM-dd HH:mm:ss: ") + text;
 597:   
 598:              Console.WriteLine(line);
 599:          }
 600:   
 601:          ////////////////////////////////////////////////////////////////////////////
 602:          ////////////////////////////////////////////////////////////////////////////
 603:      }
 604:  }