شركة التطبيقات المتكاملة لتصميم النظم البرمجية الخاصة

Integrated Applications Programming Company

Skip Navigation LinksHome » Code Library » Gmail

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

Gmail API support class

   1:  using Google.Apis.Auth.OAuth2;
   2:  using Google.Apis.Gmail.v1;
   3:  using Google.Apis.Gmail.v1.Data;
   4:  using Google.Apis.Services;
   5:  using Google.Apis.Util.Store;
   6:  using System;
   7:  using System.Collections.Generic;
   8:  using System.IO;
   9:  using System.Text;
  10:  using System.Threading;
  11:   
  12:  namespace Ia.Cl.Model
  13:  {
  14:      ////////////////////////////////////////////////////////////////////////////
  15:   
  16:      /// <summary publish="true">
  17:      /// Gmail API support class
  18:      /// </summary>
  19:      /// 
  20:      /// </summary>
  21:      /// <remarks> 
  22:      /// Copyright © 2017-2018 Jasem Y. Al-Shamlan (info@ia.com.kw), Integrated Applications - Kuwait. All Rights Reserved.
  23:      ///
  24:      /// 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
  25:      /// the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
  26:      ///
  27:      /// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
  28:      /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  29:      /// 
  30:      /// You should have received a copy of the GNU General Public License along with this library. If not, see http://www.gnu.org/licenses.
  31:      /// 
  32:      /// Copyright notice: This notice may not be removed or altered from any source distribution.
  33:      /// </remarks> 
  34:      public class Gmail
  35:      {
  36:          private string serverUser, defaultMailbox;
  37:   
  38:          // If modifying these scopes, delete your previously saved credentials at ~/.credentials/gmail-dotnet-quickstart.json
  39:          private static string[] scopeList;
  40:          private static string applicationName;
  41:          private GmailService service;
  42:          private UsersResource.LabelsResource.ListRequest request;
  43:          private UsersResource.MessagesResource.SendRequest sendRequest;
  44:   
  45:          public enum MailType { Plain, Html };
  46:   
  47:          ////////////////////////////////////////////////////////////////////////////
  48:   
  49:          /// <summary>
  50:          ///
  51:          /// </summary>
  52:          public Gmail()
  53:          {
  54:              /*
  55:               * app.config
  56:               * <add key="imapServerUser" value="*" />
  57:               */
  58:   
  59:              // serverUser = ConfigurationManager.AppSettings["imapServerUser"].ToString();
  60:   
  61:              UserCredential credential;
  62:   
  63:              defaultMailbox = "Inbox";
  64:   
  65:              scopeList = new string[] { GmailService.Scope.GmailReadonly, GmailService.Scope.GmailSend };
  66:   
  67:              applicationName = "Gmail API .NET Quickstart";
  68:   
  69:              using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
  70:              {
  71:                  string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
  72:   
  73:                  credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart.json");
  74:   
  75:                  credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, scopeList, "ofn.gov.kw@gmail.com", CancellationToken.None, new FileDataStore(credPath, true)).Result;
  76:   
  77:                  Console.WriteLine("Credential file saved to: " + credPath);
  78:              }
  79:   
  80:              // Create Gmail API service.
  81:              service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = applicationName });
  82:   
  83:              // Define parameters of request.
  84:              request = service.Users.Labels.List("me");
  85:          }
  86:   
  87:          ////////////////////////////////////////////////////////////////////////////
  88:   
  89:          /// <summary>
  90:          ///
  91:          /// </summary>
  92:          public void SendEmail(string name, string email, string subject, string content)
  93:          {
  94:              Message mailMessage = new global::Google.Apis.Gmail.v1.Data.Message();
  95:   
  96:              mailMessage.Payload = new MessagePart();
  97:              mailMessage.Payload.Headers = new List<MessagePartHeader>();
  98:   
  99:              mailMessage.Payload.Headers.Add(new MessagePartHeader() { Name = "From", Value = "ofn.gov.kw@gmail.com" });
 100:              mailMessage.Payload.Headers.Add(new MessagePartHeader() { Name = "Date", Value = DateTime.UtcNow.AddHours(3).ToString() });
 101:              mailMessage.Payload.Headers.Add(new MessagePartHeader() { Name = "Subject", Value = "Testing..." });
 102:              mailMessage.Payload.Headers.Add(new MessagePartHeader() { Name = "To", Value = email });
 103:   
 104:              mailMessage.Payload.Body = new MessagePartBody();
 105:              mailMessage.Payload.Body.Data = content;
 106:              //mailMessage.Payload.Body.Data...IsBodyHtml = (mailType == MailType.Html);
 107:   
 108:              /*
 109:              foreach (System.Net.Mail.Attachment attachment in email.Attachments)
 110:              {
 111:                  mailMessage.Attachments.Add(attachment);
 112:              }
 113:              */
 114:   
 115:              //var mimeMessage = global::Google.Apis.Gmail.v1.Data.MimeMessage.CreateFromMailMessage(mailMessage);
 116:   
 117:              /*
 118:              var gmailMessage = new global::Google.Apis.Gmail.v1.Data.Message
 119:              {
 120:                  Raw = Encode(mimeMessage.ToString())
 121:              };
 122:              */
 123:   
 124:              sendRequest = service.Users.Messages.Send(mailMessage, "ofn.gov.kw@gmail.com");
 125:   
 126:              sendRequest.Execute();
 127:          }
 128:   
 129:          ////////////////////////////////////////////////////////////////////////////
 130:   
 131:          /// <summary>
 132:          ///
 133:          /// </summary>
 134:          public static string Encode(string text)
 135:          {
 136:              byte[] bytes = System.Text.Encoding.UTF8.GetBytes(text);
 137:   
 138:              return System.Convert.ToBase64String(bytes)
 139:                  .Replace('+', '-')
 140:                  .Replace('/', '_')
 141:                  .Replace("=", "");
 142:          }
 143:   
 144:          ////////////////////////////////////////////////////////////////////////////
 145:   
 146:          /// <summary>
 147:          ///
 148:          /// </summary>
 149:          public List<string> LabelList
 150:          {
 151:              get
 152:              {
 153:                  // case sensitive
 154:   
 155:                  List<string> labelList;
 156:                  IList<Label> labelIList;
 157:   
 158:                  labelList = new List<string>();
 159:                  labelIList = request.Execute().Labels;
 160:   
 161:                  Console.WriteLine("Labels:");
 162:   
 163:                  if (labelIList != null && labelIList.Count > 0)
 164:                  {
 165:                      foreach (var labelItem in labelIList)
 166:                      {
 167:                          labelList.Add(labelItem.Name);
 168:                          Console.WriteLine("{0}", labelItem.Name);
 169:                      }
 170:                  }
 171:                  else
 172:                  {
 173:                      Console.WriteLine("No labels found.");
 174:                  }
 175:   
 176:                  return labelList;
 177:              }
 178:          }
 179:   
 180:          ////////////////////////////////////////////////////////////////////////////
 181:   
 182:          /// <summary>
 183:          ///
 184:          /// </summary>
 185:          public void Test()
 186:          {
 187:              string body, from, date, subject;
 188:              UsersResource.MessagesResource.ListRequest listRequest;
 189:              ListMessagesResponse listMessagesResponse;
 190:   
 191:              from = date = string.Empty;
 192:   
 193:              listRequest = service.Users.Messages.List("ofn.gov.kw@gmail.com");
 194:              listRequest.LabelIds = "SENT"; // case sensitive
 195:              listRequest.IncludeSpamTrash = false;
 196:   
 197:              listMessagesResponse = listRequest.Execute();
 198:   
 199:              if (listMessagesResponse != null && listMessagesResponse.Messages != null)
 200:              {
 201:                  //loop through each email and get what fields you want... 
 202:                  foreach (var email in listMessagesResponse.Messages)
 203:                  {
 204:                      var emailInfoRequest = service.Users.Messages.Get("ofn.gov.kw@gmail.com", email.Id);
 205:                      var emailInfoResponse = emailInfoRequest.Execute();
 206:   
 207:                      if (emailInfoResponse != null)
 208:                      {
 209:                          //loop through the headers to get from, date, subject, body  
 210:   
 211:                          foreach (var messagePartHeader in emailInfoResponse.Payload.Headers)
 212:                          {
 213:                              if (messagePartHeader.Name == "Date") date = messagePartHeader.Value;
 214:                              else if (messagePartHeader.Name == "From") from = messagePartHeader.Value;
 215:                              else if (messagePartHeader.Name == "Subject") subject = messagePartHeader.Value;
 216:   
 217:                              if (date != "" && from != "")
 218:                              {
 219:                                  if (emailInfoResponse.Payload.MimeType == "text/html")
 220:                                  {
 221:                                      if (emailInfoResponse.Payload.Parts == null && emailInfoResponse.Payload.Body != null)
 222:                                      {
 223:                                          body = emailInfoResponse.Payload.Body.Data;
 224:                                      }
 225:                                      else
 226:                                      {
 227:                                          body = GetNestedParts(emailInfoResponse.Payload.Parts, "");
 228:                                      }
 229:   
 230:                                      byte[] data = FromBase64ForUrlString(body);
 231:                                      string decodedString = Encoding.UTF8.GetString(data);
 232:                                  }
 233:                              }
 234:                              else
 235:                              {
 236:   
 237:                              }
 238:                          }
 239:                      }
 240:                  }
 241:              }
 242:          }
 243:   
 244:          ////////////////////////////////////////////////////////////////////////////
 245:   
 246:          /// <summary>
 247:          ///
 248:          /// </summary>
 249:          private static String GetNestedParts(IList<MessagePart> part, string curr)
 250:          {
 251:              string s;
 252:   
 253:              s = curr;
 254:   
 255:              if (part == null)
 256:              {
 257:                  return s;
 258:              }
 259:              else
 260:              {
 261:                  foreach (var partList in part)
 262:                  {
 263:                      if (partList.Parts == null)
 264:                      {
 265:                          if (partList.Body != null && partList.Body.Data != null)
 266:                          {
 267:                              s += partList.Body.Data;
 268:                          }
 269:                      }
 270:                      else
 271:                      {
 272:                          return GetNestedParts(partList.Parts, s);
 273:                      }
 274:                  }
 275:   
 276:                  return s;
 277:              }
 278:          }
 279:   
 280:          ////////////////////////////////////////////////////////////////////////////
 281:   
 282:          /// <summary>
 283:          ///
 284:          /// </summary>
 285:          public List<string> MailboxList
 286:          {
 287:              get
 288:              {
 289:                  List<string> mailboxList;
 290:   
 291:                  mailboxList = new List<string>();
 292:   
 293:                  //foreach (Mailbox mailbox in imap.Mailboxes) mailboxList.Add(mailbox.Name);
 294:   
 295:                  return mailboxList;
 296:              }
 297:          }
 298:   
 299:          /*
 300:          ////////////////////////////////////////////////////////////////////////////
 301:  
 302:          /// <summary>
 303:          ///
 304:          /// </summary>
 305:          public void CreateMailbox(string mailboxName)
 306:          {
 307:              imap.CreateMailbox(mailboxName);
 308:          }
 309:  
 310:          ////////////////////////////////////////////////////////////////////////////
 311:  
 312:          /// <summary>
 313:          ///
 314:          /// </summary>
 315:          public string DeleteMailbox(string mailboxName)
 316:          {
 317:              return imap.DeleteMailbox(mailboxName);
 318:          }
 319:  
 320:          ////////////////////////////////////////////////////////////////////////////
 321:  
 322:          /// <summary>
 323:          ///
 324:          /// </summary>
 325:          public Header ReadHeader(Mailbox mailbox, int i)
 326:          {
 327:              Header header;
 328:              ActiveUp.Net.Mail.Header aHeader;
 329:  
 330:              header = new Header();
 331:  
 332:              try
 333:              {
 334:                  aHeader = mailbox.Fetch.HeaderObject(i);
 335:  
 336:                  header.MessageId = aHeader.MessageId;
 337:                  header.From = aHeader.From.Email;
 338:                  header.Subject = aHeader.Subject;
 339:              }
 340:              catch (Imap4Exception iex)
 341:              {
 342:              }
 343:              catch (Exception ex)
 344:              {
 345:              }
 346:              finally
 347:              {
 348:              }
 349:  
 350:              return header;
 351:          }
 352:  
 353:          ////////////////////////////////////////////////////////////////////////////
 354:  
 355:          /// <summary>
 356:          ///
 357:          /// </summary>
 358:          public int MoveMessagesFromEmailToMailbox(string email, string destinationMailboxName)
 359:          {
 360:              int numberOfMessagesMoved;
 361:              int[] messageOrdinalList;
 362:              string searchPhrase;
 363:              Mailbox mailbox;
 364:  
 365:              numberOfMessagesMoved = 0;
 366:  
 367:              mailbox = imap.SelectMailbox(defaultMailbox);
 368:  
 369:              searchPhrase = @"FROM """ + email + @"""";
 370:  
 371:              messageOrdinalList = mailbox.Search(searchPhrase);
 372:  
 373:              if (messageOrdinalList != null && messageOrdinalList.Length > 0)
 374:              {
 375:                  // read message and check that from-email value before moving
 376:                  for (int i = messageOrdinalList.Length - 1; i >= 0; i--)
 377:                  {
 378:                      MoveMessage(mailbox, messageOrdinalList[i], destinationMailboxName);
 379:                      numberOfMessagesMoved++;
 380:                  }
 381:              }
 382:  
 383:              return numberOfMessagesMoved;
 384:          }
 385:  
 386:          ////////////////////////////////////////////////////////////////////////////
 387:  
 388:          /// <summary>
 389:          ///
 390:          /// </summary>
 391:          public void MoveMessage(string messageId, string destinationMailboxName)
 392:          {
 393:              int[] messageOrdinalList;
 394:              string searchPhrase;
 395:              Mailbox mailbox;
 396:              ActiveUp.Net.Mail.Header header;
 397:  
 398:              mailbox = imap.SelectMailbox(defaultMailbox);
 399:  
 400:              searchPhrase = @"ALL";
 401:  
 402:              messageOrdinalList = mailbox.Search(searchPhrase);
 403:  
 404:              if (messageOrdinalList != null && messageOrdinalList.Length > 0)
 405:              {
 406:                  for (int i = messageOrdinalList.Length - 1; i >= 0; i--)
 407:                  {
 408:                      header = mailbox.Fetch.HeaderObject(messageOrdinalList[i]);
 409:  
 410:                      if (header.MessageId == messageId)
 411:                      {
 412:                          MoveMessage(mailbox, messageOrdinalList[i], destinationMailboxName);
 413:  
 414:                          break;
 415:                      }
 416:                  }
 417:              }
 418:          }
 419:  
 420:          ////////////////////////////////////////////////////////////////////////////
 421:  
 422:          /// <summary>
 423:          ///
 424:          /// </summary>
 425:          public void MoveMessage(Mailbox mailbox, int messageOrdinal, string destinationMailboxName)
 426:          {
 427:              mailbox.MoveMessage(messageOrdinal, destinationMailboxName);
 428:          }
 429:  
 430:          ////////////////////////////////////////////////////////////////////////////
 431:  
 432:          /// <summary>
 433:          /// Message list from Inbox
 434:          /// </summary>
 435:          public void MessageList(out List<Message> messageList)
 436:          {
 437:              string searchPhrase;
 438:  
 439:              searchPhrase = "ALL";
 440:  
 441:              SearchPhraseMessageList(searchPhrase, out messageList);
 442:          }
 443:  
 444:          ////////////////////////////////////////////////////////////////////////////
 445:  
 446:          /// <summary>
 447:          /// List of messages from Inbox that were sent from email
 448:          /// </summary>
 449:          public void MessageList(string email, out List<Message> messageList)
 450:          {
 451:              string searchPhrase;
 452:  
 453:              searchPhrase = @"FROM """ + email + @"""";
 454:  
 455:              SearchPhraseMessageList(searchPhrase, out messageList);
 456:          }
 457:  
 458:          ////////////////////////////////////////////////////////////////////////////
 459:  
 460:          /// <summary>
 461:          ///
 462:          /// </summary>
 463:          private void SearchPhraseMessageList(string searchPhrase, out List<Message> messageList)
 464:          {
 465:              Message message;
 466:              Mailbox mailbox;
 467:              MessageCollection messageCollection;
 468:  
 469:              messageList = new List<Message>();
 470:  
 471:              mailbox = imap.SelectMailbox(defaultMailbox);
 472:  
 473:              try
 474:              {
 475:                  messageCollection = mailbox.SearchParse(searchPhrase);
 476:  
 477:                  foreach (ActiveUp.Net.Mail.Message m in messageCollection)
 478:                  {
 479:                      message = new Message();
 480:  
 481:                      message.MessageId = m.MessageId;
 482:                      message.From = m.From.Email;
 483:                      message.Subject = m.Subject;
 484:                      message.BodyText = m.BodyText.TextStripped;
 485:                      message.Date = m.Date;
 486:                      message.ReceivedDate = m.ReceivedDate;
 487:  
 488:                      foreach (ActiveUp.Net.Mail.MimePart mp in m.Attachments)
 489:                      {
 490:                          //if (mp.IsText)
 491:                          //{
 492:                          message.Attachments.Add(new Attachment
 493:                          {
 494:                              FileName = mp.Filename,
 495:                              ContentType = mp.ContentType.MimeType,
 496:                              Content = mp.TextContent
 497:                          });
 498:                          //}
 499:                      }
 500:  
 501:                      messageList.Add(message);
 502:  
 503:                      this.Log(string.Format("Success: Message read: {0},{1},{2}", m.MessageId, m.From, m.Subject));
 504:                  }
 505:              }
 506:              catch (Imap4Exception iex)
 507:              {
 508:                  this.Log(string.Format("Imap4 Error: {0}", iex.Message));
 509:              }
 510:              catch (Exception ex)
 511:              {
 512:                  this.Log(string.Format("Failed: {0}", ex.Message));
 513:              }
 514:              finally
 515:              {
 516:              }
 517:          }
 518:  
 519:          ////////////////////////////////////////////////////////////////////////////
 520:  
 521:          /// <summary>
 522:          ///
 523:          /// </summary>
 524:          public List<Header> HeaderList(Mailbox mailbox)
 525:          {
 526:              Header header;
 527:              List<Header> headerList;
 528:              ActiveUp.Net.Mail.Header aHeader;
 529:  
 530:              headerList = new List<Header>(mailbox.MessageCount);
 531:  
 532:              try
 533:              {
 534:                  for (int i = 1; i <= mailbox.MessageCount; i++)
 535:                  {
 536:                      header = new Header();
 537:  
 538:                      aHeader = mailbox.Fetch.MessageObject(i);
 539:  
 540:                      header.MessageId = aHeader.MessageId;
 541:                      header.From = aHeader.From.Email;
 542:                      header.Subject = aHeader.Subject;
 543:  
 544:                      this.Log(string.Format("Success: Header read: {0},{1},{2}", header.MessageId, header.From, header.Subject));
 545:                  }
 546:              }
 547:              catch (Imap4Exception iex)
 548:              {
 549:              }
 550:              catch (Exception ex)
 551:              {
 552:              }
 553:              finally
 554:              {
 555:              }
 556:  
 557:              return headerList;
 558:          }
 559:  
 560:          ////////////////////////////////////////////////////////////////////////////
 561:  
 562:          /// <summary>
 563:          ///
 564:          /// </summary>
 565:          public void DeleteMessage(string messageId)
 566:          {
 567:              int[] messageOrdinalList;
 568:              string searchPhrase;
 569:              Mailbox mailbox;
 570:              ActiveUp.Net.Mail.Header header;
 571:  
 572:              mailbox = imap.SelectMailbox(defaultMailbox);
 573:  
 574:              searchPhrase = @"ALL";
 575:  
 576:              messageOrdinalList = mailbox.Search(searchPhrase);
 577:  
 578:              if (messageOrdinalList != null && messageOrdinalList.Length > 0)
 579:              {
 580:                  for (int i = messageOrdinalList.Length - 1; i >= 0; i--)
 581:                  {
 582:                      header = mailbox.Fetch.HeaderObject(messageOrdinalList[i]);
 583:  
 584:                      if (header.MessageId == messageId)
 585:                      {
 586:                          DeleteMessage(mailbox, messageOrdinalList[i]);
 587:                      }
 588:                  }
 589:              }
 590:          }
 591:  
 592:          ////////////////////////////////////////////////////////////////////////////
 593:  
 594:          /// <summary>
 595:          ///
 596:          /// </summary>
 597:          private void DeleteMessage(Mailbox mailbox, int messageOrdinal)
 598:          {
 599:              mailbox.DeleteMessage(messageOrdinal, true);
 600:          }
 601:          */
 602:   
 603:          ////////////////////////////////////////////////////////////////////////////
 604:   
 605:          /// <summary>
 606:          ///
 607:          /// </summary>
 608:          public static byte[] FromBase64ForUrlString(string base64ForUrlInput)
 609:          {
 610:              int padChars = (base64ForUrlInput.Length % 4) == 0 ? 0 : (4 - (base64ForUrlInput.Length % 4));
 611:              StringBuilder result = new StringBuilder(base64ForUrlInput, base64ForUrlInput.Length + padChars);
 612:   
 613:              result.Append(String.Empty.PadRight(padChars, '='));
 614:              result.Replace('-', '+');
 615:              result.Replace('_', '/');
 616:   
 617:              return Convert.FromBase64String(result.ToString());
 618:          }
 619:   
 620:          ////////////////////////////////////////////////////////////////////////////
 621:          ////////////////////////////////////////////////////////////////////////////
 622:      }
 623:  }