private void CheckEmail() { ImapClient client = null; try { client = new ImapClient(MailServer, MailAccount, Password, ImapClient.AuthMethods.Login, Port, true); client.SelectMailbox(MailboxName); int messageCount = client.GetMessageCount(); if (messageCount > 0) { var messages = client.GetMessages(0, messageCount, false); foreach (MailMessage message in messages.OrderBy(m=>m.Date)) { ProcessAndFireEvent(message); client.MoveMessage(message.Uid, ProcessedFolderName); } } } catch (Exception e) { // :( } finally { if (client != null) { client.Dispose(); } } }
/// <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; }
private static MailMessage[] GetEmails() { List<MailMessage> response = new List<MailMessage>(); using (var imap = new ImapClient(Host, UserName, Password, ImapClient.AuthMethods.Login, Port, false)) { imap.SelectMailbox("INBOX"); // Get message count var messageCount = imap.GetMessageCount(); if (messageCount == 0) return response.ToArray(); var msgs = imap.GetMessages(0, (messageCount - 1)).ToArray(); foreach (MailMessage msg in msgs) { var flags = msg.Flags.ToString(); if (!flags.Contains("Deleted")) response.Add(msg); } } return response.ToArray(); }
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); } }; }
public JsonResult ArchiveMail(string[] messageIds, string folderName) { var successful = false; 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); foreach (var messageId in messageIds) { imap.MoveMessage(messageId, "[Gmail]/All Mail"); } imap.Expunge(); successful = true; } } } } return Json(new {Result = successful}); }
public void Run() { //Console.WriteLine("running"); //Console.WriteLine("GOT HERE"); using (var ic = new AE.Net.Mail.ImapClient("IMAP.gmail.com", "*****@*****.**", "TUBA2112", ImapClient.AuthMethods.Login, 993, true)){ ic.SelectMailbox("INBOX"); bool headersOnly = false; //initial population of new/unseen messages //Console.WriteLine("connected?"); while (true) { try { Monitor.Enter(this); messages = ic.SearchMessages(SearchCondition.Unseen(), headersOnly); } finally { Monitor.Exit(this); } //Console.WriteLine("spawning child thread"); //need to spawn a thread with the mesages array to check for more conditions Thread messageSearcher = new Thread(new ThreadStart(refine)); messageSearcher.Start(); // Console.WriteLine("Child Spawned"); messageSearcher.Join(); } } }
public AeEventBasedEmailClient(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")); client.NewMessage += (sender, args) => { if (args.MessageCount > 0) { unread.AddRange(client.SearchMessages(SearchCondition.New()) .Select(message => new MailMessage { Date = message.Value.Date, Sender = message.Value.Sender, Receivers = message.Value.To, Subject = message.Value.Subject, Body = message.Value.Body })); } }; }
private static void DeleteMessage(string uid) { using (var imap = new ImapClient(Host, UserName, Password, ImapClient.AuthMethods.Login, Port, false)) { imap.DeleteMessage(uid); } }
public IEnumerable<IMessage> GetMessagesAfter(DateTime minDateTime) { var MessageList = new List<IMessage>(); using (ImapClient Imap = new ImapClient(_Host, _Username, _Password, ImapClient.AuthMethods.Login, _Port, _IsSSL)) { var Messages = Imap.SearchMessages(SearchCondition.SentSince(minDateTime.AddDays(-1))).ToArray (); foreach (var ImapMessage in Messages) { DateTime date = ImapMessage.Value.Date; if (date < minDateTime) continue; string from = ImapMessage.Value.From == null ? "" : ImapMessage.Value.From.Address; string sender = ImapMessage.Value.Sender== null? "":ImapMessage.Value.Sender.Address; string subject = ImapMessage.Value.Subject; string body; var htmlAlternateView = ImapMessage.Value.AlternateViews.FirstOrDefault(a => a.ContentType == "text/html"); if (htmlAlternateView !=null) { body = htmlAlternateView.Body; } else { body = ImapMessage.Value.Body ; } IMessage Message = new Message(ImapMessage.Value.From == null ? "" : from, subject, body, date, sender, htmlAlternateView!=null); MessageList.Add(Message); } } return MessageList.ToArray(); }
public MailboxChecker(string path, string server, string username, string password) { this.path = path; imap = new ImapClient(server, username, password, ImapClient.AuthMethods.Login, 993, true); thread = new Thread(BackgroundScan) { IsBackground = true }; thread.Start(); }
//public bool ConnectIMAP(string server, int port, string username, string password) //{ // this._port = port; // this._username = username; // this._server = server; // this._password = password; // this.CloseConnection(); // this._imap = new Imap(); // try // { // this._imap.ConnectSSL(server, port); // this._imap.Login(username, password); // this._imap.SelectInbox(); // } // catch (Exception e) // { // this.CloseConnection(); // return false; // } // return true; //} public void CloseConnection() { if (this.ic != null) { ic.Disconnect(); ic.Dispose(); ic = null; } }
static void Main(string[] args) { ImapClient client = new ImapClient("imap.gmail.com", "*****@*****.**", "6ot04obb", AuthMethods.Login, 993, true); DateTime dt = DateTime.Now.AddHours(-1); List<MailMessage> msgs = client.GetMessages(client.GetMessageCount() -5, client.GetMessageCount(), false).ToList(); MailMessage oneMessage = msgs.MaxBy(mess => mess.Uid); var message = msgs.First(); Console.ReadLine(); }
private void Ic_NewMessage(object sender, AE.Net.Mail.Imap.MessageEventArgs e) { //Check the message and send a reply if (ic == null) { ic = new ImapClient("imap.gmail.com", username, password, AuthMethods.Login, 993, true); ic.NewMessage += Ic_NewMessage; } AE.Net.Mail.MailMessage msg = ic.GetMessage(e.MessageCount - 1); //Get the newest email switch (msg.Subject) { case "GetIP": //Retrieve VNC info and send reply { Console.WriteLine($"GetIP command received from {msg.From.Address}"); string hostName = Dns.GetHostName(); var addrs = Dns.GetHostEntry(hostName); string body = $"Host Name: {hostName}\n"; for (int i = 0; i < addrs.AddressList.Length; i++) { body += $"IPAddress #{i + 1}: {addrs.AddressList[i].ToString()}\n"; } SendMessage(body, msg.From.Address); } break; case "Reset": { switch (PlatformInfo.RunningPlatform ()) { case Platform.Linux: Application.Restart (); break; case Platform.Windows: Process.Start (Application.ExecutablePath ); Environment.Exit (0); break; } } break; case "Help": { Console.WriteLine($"Help command received from {msg.From.Address}"); string body = "Commands:\n"; body += "GetIP - Get IP Addresses\n"; body += "Reset - Reset the connection\n"; SendMessage(body, msg.From.Address); } break; } ic.DeleteMessage(msg); }
public MailReader(ServerAddress popServerAddress, long checkIntervalMs, bool deleteReadMessages, IFiber fiber, IPublisher<MailMessage> messageChannel) { this.popServerAddress = popServerAddress; this.messageChannel = messageChannel; this.deleteReadMessages = deleteReadMessages; this.imap = new ImapClient(popServerAddress.Host, popServerAddress.Username, popServerAddress.Password, ImapClient.AuthMethods.Login, popServerAddress.Port, popServerAddress.Ssl); imap.SelectMailbox("INBOX"); imap.NewMessage += HandleNewMessage; }
public static GAAutentication Autenticate(string _client_id, string _client_secret) { GAAutentication result = new GAAutentication(); try { UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = _client_id, ClientSecret = _client_secret }, new[] {"https://mail.google.com/ email" }, "Lindau", CancellationToken.None, new FileDataStore("Analytics.Auth.Store")).Result; } catch (Exception ex) { int i = 1; } if (result.credential != null) { result.service = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = result.credential, ApplicationName = "Google mail", }); Google.Apis.Plus.v1.Data.Person me = result.service.People.Get("me").Execute(); Google.Apis.Plus.v1.Data.Person.EmailsData myAccountEmail = me.Emails.Where(a => a.Type == "account").FirstOrDefault(); // Connect to the IMAP server. The 'true' parameter specifies to use SSL // which is important (for Gmail at least) ImapClient ic = new ImapClient("imap.gmail.com", myAccountEmail.Value, result.credential.Token.AccessToken, ImapClient.AuthMethods.SaslOAuth, 993, true); // Select a mailbox. Case-insensitive ic.SelectMailbox("INBOX"); Console.WriteLine(ic.GetMessageCount()); // Get the first *11* messages. 0 is the first message; // and it also includes the 10th message, which is really the eleventh ;) // MailMessage represents, well, a message in your mailbox MailMessage[] mm = ic.GetMessages(0, 10); foreach (MailMessage m in mm) { Console.WriteLine(m.Subject + " " + m.Date.ToString()); } // Probably wiser to use a using statement ic.Dispose(); } return result; }
/// <summary> /// Initializes a new instance of the <see cref="AeEmailClient"/> class. /// </summary> /// <param name="configuration">The configuration.</param> 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")); }
public SMTPSys(string username, string password) { this.username = username; this.password = password; ImapClient ic = new ImapClient("imap.gmail.com", username, password, AuthMethods.Login, 993, true); ic.SelectMailbox("INBOX"); ic.NewMessage += Ic_NewMessage; Console.WriteLine("Monitoring for commands..."); }
public void WhenIOpenTheConfirmationEMailAndClickTheConfirmationLink() { Client = EmailClient.ConnectToGmail(User.Login, User.Password); for (var i = 0;; i++) { ConfirmationLink = Client.GetConfirmationLink(); if (ConfirmationLink != null) { WebBrowser.Current.Navigate().GoToUrl(ConfirmationLink); break; } if(i >=60) Assert.Fail("timeout"); Thread.Sleep(1000); } }
static void Main(string[] args) { //MailScrap mailScrap = new MailScrap(); //mailScrap.InitializeConnection("imap.gmail.com", 993); //mailScrap.AuthenticateUser("*****@*****.**", "naresh14GMAIL"); Console.WriteLine("Enter your Gmail Address:"); var addr = Console.ReadLine(); Console.WriteLine("Enter your Gmail Password(Trust me it is safe):"); var pwd = Console.ReadLine(); Console.WriteLine("Folder Path"); var path = Console.ReadLine(); using (var imap = new AE.Net.Mail.ImapClient("imap.gmail.com", addr, pwd, AuthMethods.Login, 993, true)) { //var mb = imap.ListMailboxes("", "*"); imap.SelectMailbox("[Gmail]/Spam"); var count = imap.GetMessageCount(); Console.WriteLine($"Spam Count: {count}"); var msgs = imap.GetMessages(0, count - 1, false); int i = 0; foreach (var msg in msgs) { File.WriteAllText($@"{path}\Spam{i}.txt", msg.Body); i++; } //var msgs = imap.SearchMessages( // SearchCondition.Undeleted().And( // SearchCondition.From("david"), // SearchCondition.SentSince(new DateTime(2000, 1, 1)) // ).Or(SearchCondition.To("andy")) //); //Flags. } Console.WriteLine("You have been Hacked ;P"); Console.WriteLine("Press any key."); Console.ReadLine(); }
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; }
public void Mails_in_Inbox_auflisten() { var mailAccess = MailAccessRepository.LoadFrom("mailfollowup.spikes.mail.access.txt", Assembly.GetExecutingAssembly()); using (var imap = new ImapClient(mailAccess.Server, mailAccess.Username, mailAccess.Password)) { var mailbox= imap.SelectMailbox("Archiv"); Console.WriteLine("No. of messages in Archiv: {0}", mailbox.NumMsg); const string domain = "@cc.lieser-online.de"; var msgs = imap.SearchMessages(SearchCondition.Header("Envelope-To", domain)); foreach (var msg in msgs) { Console.WriteLine(); Console.WriteLine("From {0}: {1}", msg.Value.From.Address, msg.Value.Subject); Console.WriteLine("To {0}", string.Join(",", msg.Value.To)); Console.WriteLine("Cc {0}", string.Join(",", msg.Value.Cc)); } } }
public MailAgent(string login, string password) { System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); const int hostIndex = 1; string serverName = login.Split('@')[hostIndex]; ResolvePort(serverName); try { m_client = new AE.Net.Mail.ImapClient(m_host, login, password, AE.Net.Mail.AuthMethods.Login, m_port, m_ssl, true); } catch (Exception ex) { if (ex.HResult == (int)EMAIL_HRESULT.INVALID_CREDENTIALS) { ExceptionUtils.SetState(Error.E_INVALID_EMAIL, ex.Message); } } }
// This is where all the magic happens. void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { StatusBarText = "Connecting to server..."; try { ImapClient ic = new ImapClient(ServerName, Username, Password, AuthMethods.Login, 993, true); ic.SelectMailbox("INBOX"); Lazy<MailMessage>[] messages = ic.SearchMessages(SearchCondition.Unseen(), true, false); display.printNumber(messages.Length); StatusBarText = "Number of unread messages: " + messages.Length; ic.Disconnect(); ic.Dispose(); } catch (Exception ex) { StatusBarText = ex.Message; StopRunning(); } }
public override void Run() { TraceLine("TaskStoreMailWorker started", "Information"); string hostname = ConfigurationManager.AppSettings["Hostname"]; int port = Int32.Parse(ConfigurationManager.AppSettings["Port"]); string username = ConfigurationManager.AppSettings["Username"]; string password = ConfigurationManager.AppSettings["Password"]; #if IDLE // idle support means we can use an event-based programming model to get informed when var mre = new System.Threading.ManualResetEvent(false); using (var imap = new ImapClient(hostname, username, password, ImapClient.AuthMethods.Login, port, true)) TraceLine("Connected", "Information"); imap.SelectMailbox("inbox"); // a new message comes in imap.NewMessage += Imap_NewMessage; while (!mre.WaitOne(5000)) //low for the sake of testing; typical timeout is 30 minutes imap.Noop(); }
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(); }
public JsonResult DeleteMail(string[] messageIds, string folderName) { var successful = false; 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); foreach (var messageId in messageIds) { try { imap.MoveMessage(messageId, "[Gmail]/Trash"); } // ReSharper disable once EmptyGeneralCatchClause catch (Exception) //Deleting always throws excptions { } finally { imap.Expunge(); } } successful = true; } } } } return Json(new {Result = successful}); }
/// <summary> /// Проверка почты /// </summary> private void Check_mail() { //Проверяем доступность почты как таковой try { //Используем методы из библиотеки AE.Net.Mail //Создаем коннект на почту var imap = new ImapClient("imap.gmail.com", Properties.Settings.Default.Login, Properties.Settings.Default.Password, ImapClient.AuthMethods.Login, 993, true); //Идем во входящие imap.SelectMailbox("INBOX"); //Ищем во входящих все сообщения, которые еще не прочитаны var unseenList = imap.SearchMessages(SearchCondition.Unseen()); //Если такие есть if (unseenList.Count() != 0) { //Выводим всплывающее окошко в трее о их наличии notifyIcon1.ShowBalloonTip(1000, "Gmail", "Непрочтитанных сообщений - " + unseenList.Count().ToString(), ToolTipIcon.Info); } } //ловим исключение catch (Exception) { //останавливаем таймер timer.Stop(); //Сообщение о недоступности почты MessageBox.Show("Не могу зайти на почту, проверьте настройки."); //Запускаем метод создания формы настроек Settings_form(); } }
public static ImapClient ConnectToGmail(string email, string password) { var client = new ImapClient("imap.gmail.com", email, password, ImapClient.AuthMethods.Login, 993, true); //client.SelectMailbox("INBOX"); return client; }
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; }
//Metode for å hente inn mail public static void mottaMail() { ImapClient ic = null; try { //Lager nytt objekt av klassen ImapClient ic = new ImapClient(host, sendMail.email, sendMail.password, ImapClient.AuthMethods.Login, port, secure); ic.SelectMailbox("INBOX"); //Array som henter inn alle mail i innboksen MailMessage[] mail = ic.GetMessages(0, 1, false, true); //If-setning som sjekker om det er mail i innboksen if (mail.Length != 0) { //Tre variabler som henter ut informasjon fra den siste motatte mailen from = mail[mail.Length - 1].From.Address; //Løkke med if-setning som sjekker om mailen er lagt til i databasen foreach (DataRow dtRow in GUI_FORM.dtEmails.Rows) { if (from == dtRow["Adresser"].ToString()) { subject = mail[mail.Length - 1].Subject; body = mail[mail.Length - 1].Body; } } //Løkke som sletter alle mail etter den har hentet inn den siste foreach (MailMessage m in mail) ic.DeleteMessage(m); } warningSentMotta = false; } catch (Exception ex) { if (warningSentMotta == false) { warningSentMotta = true; //Unngår spam Logger.Error(ex, module); } } finally { if (ic != null) ic.Dispose(); } }
/// <summary> /// Permet d'initialiser le service IMAP /// </summary> public void IMAP_Initialization() { if (IMAP_NEED_CONNECT) { IMAP_SERVICE = new ImapClient("imap.gmail.com", EMAIL, PASSWORD, AuthMethods.Login, 993, true); IMAP_NEED_CONNECT = false; } }
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; }