Esempio n. 1
1
        /// <summary>
        /// Function Name : ParseNewEmail
        /// Input Parameters : none  
        /// Input Parameter Type : none
        /// Description:This method is going to record the event when an email is received to the Test email. It uses ImapClient which is available in AE.Net.Mail Nuget package.
        /// ImapClient has inbuilt properties to extract subject, body, sender information details from a newly received email
        /// </summary>
        /// <returns>
        /// Return Parameter : emailJson 
        /// Return Parameter Type : string
        /// </returns>

        public string ParseNewEmail()
        {
            // Connect to the IMAP server. The 'true' parameter specifies to use SSL, which is important (for Gmail at least)
            ImapClient imapClient = new ImapClient(ConfigurationManager.AppSettings["ImapServer"], ConfigurationManager.AppSettings["UserId"], ConfigurationManager.AppSettings["Password"], AuthMethods.Login, 993, true);
            var userName = ConfigurationManager.AppSettings["UserID"];
          //  ImapClient imapClient = new ImapClient(ConfigurationManager.AppSettings["ImapServer"], "*****@*****.**", "7Ywy7N[S", AuthMethods.Login, 993, true);
            // Select a mailbox. Case-insensitive
            imapClient.SelectMailbox("INBOX");
            string emailJson="";          
            imapClient.NewMessage += (sender, e) =>
            {
                var msg = imapClient.GetMessage(e.MessageCount - 1);
                UpdatePackage up = new UpdatePackage();
                up.Updates = ParseBody(msg.Body);
                up.Subject = msg.Subject;
                up.Body = msg.Body;
                up.ProjectName = ApplicationName;              
               
              emailJson = JsonConvert.SerializeObject(up);                          
              string result = "";
              using (var client = new WebClient())
              {
                  client.Headers[HttpRequestHeader.ContentType] = "application/json";
                 // result = client.UploadString("https://localhost:44300/ProjectUpdate/Update", "Post", emailJson);
                  result = client.UploadString("https://costcodevops.azurewebsites.net/ProjectUpdate/Update", "Post", emailJson);
                  Console.WriteLine(result);
              }
              
               
            };           

           return emailJson;           
        }
Esempio n. 2
0
        public AeEmailClient(IConfiguration configuration)
        {
            configuration = configuration.GetSubsection("EmailClient");
            client = new ImapClient(
                configuration.GetValue("Host"),
                configuration.GetValue("Username"),
                configuration.GetValue("Password"),
                ImapClient.AuthMethods.Login,
                configuration.GetValue<int>("Port"),
                configuration.GetValue<bool>("Secure"),
                configuration.GetValue<bool>("SkipSslValidation"));

            var unreadMessages = client.SearchMessages(SearchCondition.Unseen());
            foreach (var message in unreadMessages)
            {
                client.SetFlags(Flags.Seen, message.Value);
            }

            unread.AddRange(unreadMessages.Select(message => GetInputMailMessage(message.Value)));

            client.NewMessage += (sender, args) =>
                {
                    var message = client.GetMessage(args.MessageCount - 1, false, true);
                    client.SetFlags(Flags.Seen, message);
                    unread.Add(GetInputMailMessage(message));

                    if (null != MailMessageReceived)
                        {
                            MailMessageReceived(this, args);
                        }
                };
        }
        private static string GetEmail(string v1, string v2)
        {
            ImapClient client = new ImapClient("imap.openmailbox.org", v1, v2, AuthMethods.Login, 993, true);

            client.SelectMailbox("INBOX");

            MailMessage[] listemail = client.GetMessages(0,20);
            MailMessage email = listemail[12];
            if(String.IsNullOrEmpty(email.Body))
            {
                string body = client.GetMessage(email.Uid).Subject;
                client.Dispose();
                return body;
            }
            client.Dispose();
            return email.Subject;
        }
Esempio n. 4
0
    public void TestMethod1()
    {
      Pop3Client pc = new Pop3Client("mail.jacobgudbjerg.dk", "*****@*****.**", "jacobgud");

      var pi = pc.GetMessageCount();

//      var mes = pc.GetMessage(0);

      //mes.Attachments.First().Save(@"c:\temp\foto.jpg");

      pc.Dispose();

      ImapClient IC = new ImapClient("imap.gmail.com", "*****@*****.**", "", ImapClient.AuthMethods.Login,993,true);
      var i = IC.GetMessageCount("Inbox");

      var mes = IC.GetMessage(IC.GetMessageCount()-1);

      mes.Attachments.First().Save(@"c:\temp\foto.jpg");
      IC.Dispose();

    }
Esempio n. 5
0
 private static MailMessage GetLastMessageFromInBox(string testAccountName,string testAccountPassword,string folderName="INBOX")
 {
     // Connect to the IMAP server. 
     MailMessage message = null;
     Console.WriteLine(EnvironmentSettings.TestAccountName);
     Console.WriteLine(EnvironmentSettings.TestAccountPassword);
     using (ImapClient ic = new ImapClient(EnvironmentSettings.TestEmailServerHost, EnvironmentSettings.TestAccountName, EnvironmentSettings.TestAccountPassword,
                     ImapClient.AuthMethods.Login, 993, true))
     {
         // Select folder and get the last mail.
         ic.SelectMailbox(folderName);
         message= ic.GetMessage(ic.GetMessageCount() - 1);
                        
     }
     return message;
 }
Esempio n. 6
0
        private static MailMessage GetMessage(string uid)
        {
            MailMessage response = new MailMessage();

            using (var imap = new ImapClient(Host, UserName, Password, ImapClient.AuthMethods.Login, Port, false))
            {
                response = imap.GetMessage(uid, false);
            }

            return response;
        }
Esempio n. 7
0
        public JsonResult GetMail(int? timezoneOffset, bool showUnreadOnly, bool showPreview, string folderName)
        {
            var successful = false;
            var output = new List<GmailThread>();
            var unreadCount = 0;
            var folders = new List<string>();

            if (Request.IsAuthenticated)
            {
                using (var uow = new UnitOfWork(GlobalConfig.ConnectionString))
                {
                    var user = uow.UserRepository.GetUserByUsername(User.Identity.Name);

                    if (DateTime.Compare(DateTime.Now, user.OAuthAccessTokenExpiration) < 0)
                    {
                        using (
                            var imap = new ImapClient("imap.gmail.com", user.EmailAddress,
                                user.CurrentOAuthAccessToken, AuthMethods.SaslOAuth, 993, true,
                                true))
                        {
                            imap.SelectMailbox(folderName);

                            var listMailboxes = imap.ListMailboxes(string.Empty, "*");

                            foreach (var listMailbox in listMailboxes)
                            {
                                if (!listMailbox.Name.StartsWith("[Gmail]") &&
                                    String.Compare(listMailbox.Name, folderName, StringComparison.OrdinalIgnoreCase) != 0)
                                {
                                    folders.Add(listMailbox.Name);
                                }
                            }

                            var searchCondition = SearchCondition.Undeleted();
                            if (showUnreadOnly)
                            {
                                searchCondition = searchCondition.And(SearchCondition.Unseen());
                            }

                            //Get messages and organize into threads

                            var uidCollection = imap.Search(searchCondition);

                            var messages = new List<GmailMessage>();
                            foreach (var uid in uidCollection)
                            {
                                var cacheKey = "gmail_" + uid + (showPreview ? "_WPrev" : "");
                                var mailMessageBytes = HttpContext.Cache.Get(cacheKey) as byte[];
                                if (mailMessageBytes == null)
                                {
                                    var mailMessage = new GmailMessage(imap.GetMessage(uid, !showPreview, false));
                                    var encryptedMessage = GlobalConfig.Encryptor.EncryptString(JsonConvert.SerializeObject(mailMessage));
                                    HttpContext.Cache.Insert(cacheKey, encryptedMessage);
                                    messages.Add(mailMessage);
                                }
                                else
                                {
                                    var decryptedMessage = GlobalConfig.Encryptor.DecryptString(mailMessageBytes);
                                    var mailMessage = JsonConvert.DeserializeObject<GmailMessage>(decryptedMessage);
                                    messages.Add(mailMessage);
                                }
                            }
                            var threads = new Dictionary<long, GmailMessage>();
                            var threadMessages = new Dictionary<long, List<long>>();
                            var threadCounts = new Dictionary<long, int>();
                            foreach (var m in messages.OrderByDescending(m => m.MessageDate))
                            {
                                var headers = m.Headers;
                                var gmailThreadId = long.Parse(headers["X-GM-THRID"]);

                                if (!threads.ContainsKey(gmailThreadId))
                                {
                                    threads.Add(gmailThreadId, m);
                                    threadCounts.Add(gmailThreadId, 1);
                                    threadMessages.Add(gmailThreadId, new List<long> {m.Uid});
                                }
                                else
                                {
                                    threadCounts[gmailThreadId] += 1;
                                    threadMessages[gmailThreadId].Add(m.Uid);
                                }
                            }

                            //Bundle threads
                            foreach (var thread in threads)
                            {
                                var messageDate = (thread.Value.MessageDate.Ticks > 0
                                    ? (timezoneOffset.HasValue
                                        ? thread.Value.MessageDate.ToUniversalTime().AddMinutes(timezoneOffset.Value)
                                        : thread.Value.MessageDate.ToUniversalTime())
                                    : new DateTime(1900, 1, 1));
                                var messageDateString = (DateTime.Compare(messageDate.Date, DateTime.Now.Date) == 0
                                    ? messageDate.ToShortTimeString()
                                    : messageDate.ToShortDateString());
                                var unread = !(thread.Value.MessageFlags.HasFlag(GmailMessage.Flags.Seen));
                                if (unread)
                                {
                                    unreadCount++;
                                }
                                output.Add(new GmailThread
                                {
                                    Subject = thread.Value.Subject,
                                    From =
                                        thread.Value.FromDisplayName +
                                        (threadCounts[thread.Key] > 1 ? " (" + threadCounts[thread.Key] + ")" : ""),
                                    ThreadIdHex = thread.Key.ToString("X").ToLower(),
                                    ThreadId = thread.Key,
                                    ThreadMessageIds = string.Join(",", threadMessages[thread.Key].ToArray()),
                                    Date = messageDateString,
                                    Preview = (showPreview ? getPreview(thread.Value.Body) : ""),
                                    Unread = unread,
                                    Important =
                                        (thread.Value.Headers.ContainsKey("X-GM-LABELS") &&
                                         thread.Value.Headers["X-GM-LABELS"].Equals("\"\\\\Important\""))
                                });
                            }
                            successful = true;
                        }
                    }
                }
            }
            return Json(
                new {Result = successful, Data = output, UnreadCount = unreadCount, Folders = folders.ToArray()},
                JsonRequestBehavior.AllowGet);
        }