Esempio n. 1
1
        /// <summary>
        /// Searches using an S22 Imap client
        /// </summary>
        /// <param name="searchCriteria"></param>
        /// <param name="processMessages"></param>
        /// <returns></returns>
        public IEnumerable<IEmail> Search(EmailSearchCriteria searchCriteria, bool processMessages = true)
        {
            // create client
            var imapClient = new ImapClient(_host, _port, _useSsl);

            // log in
            imapClient.Login(_userName, _password, AuthMethod.Auto);

            // search for messages
            var messageIds = imapClient.Search(GetSearchCondition(searchCriteria), searchCriteria.Folder);

            // no messages found - return empty collection
            if (messageIds == null || messageIds.Length == 0) return new List<IEmail>();

            // get messages
            var messages = imapClient.GetMessages(messageIds, FetchOptions.TextOnly, true, searchCriteria.Folder);

            // check if messages downloaded properly
            if (messages == null || messages.Length == 0)
                throw new ImapMessageDownloadException(_host, _port, _userName, searchCriteria.Folder, messageIds);

            // create as S22ImapMessages
            return messages.Select(m => new S22ImapMessage(m));
        }
Esempio n. 2
1
        static int Main(string[] args)
        {
            try
            {
                var cmdArgs = new Args();
                CommandLine.Parser.Default.ParseArgumentsStrict(args, cmdArgs);
                string password = cmdArgs.Password;
                if (password == "*")
                {
                    Console.Write("Password: "******"Password: "******"*", Math.Max(20, password.Length))));
                    }
                }
                if (cmdArgs.Verbose)
                {
                    Console.WriteLine("Connecting to server");
                }
                using (ImapClient cli = new ImapClient(cmdArgs.Host, cmdArgs.Port == 0 ? (cmdArgs.Ssl ? 993 : 143) : cmdArgs.Port, cmdArgs.Ssl))
                {
                    if (cmdArgs.Verbose)
                    {
                        Console.WriteLine("Logging in");
                    }
                    cli.Login(cmdArgs.UserName, password, AuthMethod.Auto);
                    if (cmdArgs.Verbose)
                    {
                        Console.WriteLine();
                    }

                    string mb = cmdArgs.DraftsFolder;

                    var ids = cli.Search(SearchCondition.All(), mb);
                    foreach (var id in ids)
                    {
                        var fs = cli.GetMessageFlags(id, mb);
                        if (fs.Contains(MessageFlag.Draft))
                        {
                            continue;
                        }

                        if (cmdArgs.Verbose)
                        {
                            Console.WriteLine(id);
                            Console.WriteLine("\t{0}: {1}", "Flags", string.Join(" ", fs.Select(f => f.ToString())));
                            var m = cli.GetMessage(id, FetchOptions.HeadersOnly, false, mb);
                            Console.WriteLine("\tHeaders:");
                            foreach (string h in m.Headers)
                            {
                                Console.WriteLine("\t\t{0}: {1}", h, m.Headers[h]);
                            }
                        }

                        Console.WriteLine("Setting Draft flag on message {0}", id);
                        cli.SetMessageFlags(id, mb, MessageFlag.Draft, MessageFlag.Seen);
                        var fs2 = cli.GetMessageFlags(id, mb);
                        if (cmdArgs.Verbose)
                        {
                            Console.WriteLine("Message flags: {0}", string.Join(" ", fs2.Select(f => f.ToString())));
                            Console.WriteLine();
                        }
                    }

                    if (cmdArgs.Verbose)
                    {
                        Console.WriteLine("Logging out");
                    }
                    cli.Logout();
                }

                return 0;
            }
            catch (Exception x)
            {
                Console.WriteLine("{0}: {1}", x.GetType().FullName, x.Message);
                return 1;
            }
        }
Esempio n. 3
1
 private void CheckImapMail(ImapClient client)
 {
     const int maxtrys = 10;
     for (int i = 0; i < maxtrys; i++)
     {
         try
         {
             uint[] uids = client.Search(SearchCondition.Unseen());
             foreach (MailMessage msg in uids.Select(uid => client.GetMessage(uid)))
             {
                 Logger.Instance.LogFormat(LogType.Debug, this, "NEUE MAIL " + msg.Subject);
                 MailOperation(msg);
             }
             break;
         }
         catch (NotAuthenticatedException)
         {
             client.Login(_configuration.UserName, _configuration.Password, AuthMethod.Login);
         }
         catch (Exception ex)
         {
             Logger.Instance.LogFormat(LogType.Error, this, ex.ToString());
         }
     }
 }
Esempio n. 4
1
        static void Main(string[] args)
        {
            try
            {
                var cmdArgs = new Args();
                CommandLine.Parser.Default.ParseArgumentsStrict(args, cmdArgs);
                string password = cmdArgs.Password;
                if (password == "*")
                {
                    Console.Write("Password: "******"Password: "******"*", Math.Max(20, password.Length))));
                    }
                }
                Console.WriteLine("Connecting to server");
                using (ImapClient cli = new ImapClient(cmdArgs.Host, cmdArgs.Port == 0 ? (cmdArgs.Ssl ? 993 : 143) : cmdArgs.Port, cmdArgs.Ssl))
                {
                    Console.WriteLine("Logging in");
                    cli.Login(cmdArgs.UserName, password, AuthMethod.Auto);
                    Console.WriteLine();

                    Dump(() => cli.ListMailboxes(), "Mailboxes");

                    //Dump(() => cli.Capabilities(), "Capabilities");

                    //Dump(cli.GetMailboxInfo("INBOX"));
                    //Dump(cli.GetMailboxInfo("Elementy wysłane"));

                    string mb = cmdArgs.DraftsFolder;
                    //Dump(cli.GetMailboxInfo(mb));

                    var ids = cli.Search(SearchCondition.All(), mb);
                    Console.WriteLine("{0} message(s)");
                    foreach (var id in ids)
                    {
                        Console.WriteLine(id);
                        var fs = cli.GetMessageFlags(id, mb);
                        Console.WriteLine("\t{0}: {1}", "Flags", string.Join(" ", fs.Select(f => f.ToString())));
                        var m = cli.GetMessage(id, FetchOptions.Normal, false, mb);
                        Console.WriteLine("\tHeaders:");
                        foreach (string h in m.Headers)
                        {
                            Console.WriteLine("\t\t{0}: {1}", h, m.Headers[h]);
                        }
                        if (m.Subject.StartsWith("[PATCH"))
                        {
                            var fileName = string.Format("{0}.patch", id);
                            Console.WriteLine("Saving message to {0}", fileName);
                            Func<string, string> adjustHeaderValue = k =>
                                {
                                    var v = m.Headers[k];
                                    if (k == "Content-Type")
                                    {
                                        if (v != null)
                                        {
                                            var i = v.IndexOf("charset=");
                                            if (0 <= i)
                                            {
                                                return v.Substring(0, i) + "charset=\"UTF-8\"";
                                            }
                                        }
                                    }
                                    else if (k == "Content-Transfer-Encoding")
                                    {
                                        return "8bit";
                                    }
                                    return v;
                                };
                            File.WriteAllBytes(
                                fileName,
                                Encoding.UTF8.GetBytes(
                                    string.Join(
                                        Environment.NewLine,
                                        m.Headers.Cast<string>().Select(k => k + ": " + adjustHeaderValue(k))
                                        .Concat(
                                            new[]
                                    {
                                        string.Empty,
                                        m.Body
                                    }))));
                        }
                        Console.WriteLine();
                    }

                    Console.WriteLine("Logging out");
                    cli.Logout();
                }
            }
            catch (Exception x)
            {
                Console.WriteLine(x);
            }
        }
Esempio n. 5
0
		private void InitializeClient ()
		{
			// Dispose of existing instance, if any.
			if (Client != null)
				Client.Dispose ();
			
			Client = new ImapClient (Server, Port, User, Pass, AuthMethod.Auto);
			if (Client.Authed) {
				Console.ForegroundColor = ConsoleColor.Red;
				Console.WriteLine ("IMAP:: Connected to {0} via Port {1}", Server, Port);
				Console.ForegroundColor = ConsoleColor.White;

				if (Client.Supports ("IDLE") == false) {
					Console.ForegroundColor = ConsoleColor.Red;
					Console.WriteLine ("IMAP:: Server does not support IMAP IDLE");
					Console.ForegroundColor = ConsoleColor.White;
					return;
				}

				// Setup event handlers.
				Client.NewMessage += new EventHandler<IdleMessageEventArgs> (OnNewMessage);

				Client.IdleError += client_IdleError;
			}
		}
Esempio n. 6
0
        //autentiseringsmetode som sjekker om mailaddresse og mailpassord
        //satt inn ved ny instance av objected mailSender er valid og kan brukes
        //til å sende og motta e-post
        public bool connect()
        {
            if (mailAddress == null)
            {
                throw new Exception("Mail address is not set");
            }
            if (this.mailPassword == null)
                throw new Exception("Password is not set");

            //setter host til gmail som default
            //dette kan endres til å følge etter hvilken
            //e-post addresse brukeren har logget inn med, men det
            //krever mye arbeid
            string hostname = "imap.gmail.com",

                //her settes imap-innloggingen til mailaddressen og 
                //mailpassordet som ble brukt ved første autentisering.

               username = mailAddress, password = mailPassword;

            // The default port for IMAP over SSL is 993.
            using (ImapClient client = new ImapClient(hostname, 993, username, password, AuthMethod.Login, true))
            {
                Console.WriteLine("Connected");

                return isConnected = true;


            }
        }
Esempio n. 7
0
        public async Task sendMail(IdentityMessage message)
        {
            #region formatter
            string text = string.Format("Please click on this link to {0}: {1}", message.Subject, message.Body);
            string html = message.Body + "<br/>";

            html += HttpUtility.HtmlEncode(@"Or click on the copy the following link on the browser:" + message.Body);
            #endregion

            MailMessage msg = new MailMessage();
            msg.From = new MailAddress("*****@*****.**","Microbrew.it");
            msg.To.Add(new MailAddress(message.Destination));
            msg.Subject = message.Subject;
            msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
            msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));

            SmtpClient smtpClient = new SmtpClient("mail.gandi.net", Convert.ToInt32(587));
            System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("*****@*****.**", MailPassword);
            smtpClient.Credentials = credentials;
            smtpClient.EnableSsl = true;
            smtpClient.Send(msg);
            using (ImapClient Client = new ImapClient("access.mail.gandi.net", 993,
             "*****@*****.**", MailPassword, AuthMethod.Login, true))
            {
                Client.StoreMessage(msg, true, "Sent");
            }
        }
Esempio n. 8
0
        public static void SaveMail2SentFolder(string subject, string body, EmailSettings settings)
        {
            using (ImapClient imap = new ImapClient(settings.SentHost, settings.SentPort, settings.SentLogin, settings.SentPassword, AuthMethod.Auto, settings.SentEnableSsl))
            {
                MailMessage message = new MailMessage();

                if (!String.IsNullOrEmpty(settings.SentLogin))
                {
                    message.From = new MailAddress(settings.SentLogin);
                }
                else
                {
                    message.From = settings.MailFrom;
                }

                message.To.Add(settings.MailTo);

                message.Subject = subject;
                message.Body = body;

                string mailbox = null;

                foreach (var mb in imap.ListMailboxes())
                {
                    if (mb.ToLower().Equals("sent") || mb.ToLower().Equals("отправленные") || mb.ToLower().Contains("sent"))
                    {
                        mailbox = mb;
                        break;
                    }
                }

                uint uid = imap.StoreMessage(message, false, mailbox);
                //imap.SetMessageFlags(uid, null, );
            }
        }
Esempio n. 9
0
        public List <Email> ReadEmails()
        {
            List <Email> emails = new List <Email>();

            S22.Imap.IImapClient imapClient = new S22.Imap.ImapClient("imap.gmail.com", 993, "*****@*****.**", "Demo1234!", AuthMethod.Login, true);
            IEnumerable <String> mailboxes  = imapClient.ListMailboxes();

            foreach (String mailbox in mailboxes)
            {
                Debug.WriteLine(mailbox);
            }

            IEnumerable <uint>        uids     = imapClient.Search(SearchCondition.All(), "INBOX");
            IEnumerable <MailMessage> messages = imapClient.GetMessages(uids);

            foreach (MailMessage message in messages)
            {
                Debug.WriteLine(message.Subject);
                emails.Add(new Email {
                    Subject = message.Subject, Body = message.Body, From = message.From.ToString(), To = message.To.ToString(), Date = message.Date().Value
                });
            }

            return(emails);
        }
Esempio n. 10
0
        public static void GetEmails()
        {
            string ImapServer  = "mail.ldddns.com";
            string ImapUserame = "song";
            string ImapPwd     = "20191104";

            var t = new S22.Imap.ImapClient(ImapServer, 110, ImapUserame, ImapPwd);

            using (S22.Imap.ImapClient client = new S22.Imap.ImapClient(ImapServer, 110, ImapUserame, ImapPwd))
            {
                var unseen = client.Search(SearchCondition.Unseen());

                if (unseen == null || unseen.Count() == 0)
                {
                    Console.WriteLine(string.Format("==============>没有新邮件!"));
                    return;
                }
                Console.WriteLine(string.Format("==============>开始检测"));
                foreach (uint uid in unseen)
                {
                    var    msg        = client.GetMessage(uid, true);
                    var    dataStream = msg.AlternateViews[0].ContentStream;
                    byte[] byteBuffer = new byte[dataStream.Length];
                    string altbody    = msg.BodyEncoding.GetString(byteBuffer, 0, dataStream.Read(byteBuffer, 0, byteBuffer.Length));
                    try
                    {
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }
Esempio n. 11
0
 void IAlarmSource.RunThread()
 {
     switch (_configuration.POPIMAP.ToLower())
     {
         case "imap":
             using (
                 _ImapClient =
                 new ImapClient(_configuration.ServerName, _configuration.Port, _configuration.UserName,
                                _configuration.Password, AuthMethod.Login, _configuration.SSL))
             {
                 if (_ImapClient.Supports("IDLE"))
                 {
                     _ImapClient.NewMessage += ImapClientNewMessage;
                 }
                 else
                 {
                     Logger.Instance.LogFormat(LogType.Info, this,
                                               "IMAP IDLE wird vom Server nicht unterstützt!!!");
                 }
                 while (true)
                 {
                     CheckImapMail(_ImapClient);
                     Thread.Sleep(1000);
                 }
             }
     }
 }
Esempio n. 12
0
        public static void Start()
        {
            bool Gmail = Properties.Settings.Default.UseGmail;
            string Host = Gmail ? Properties.Settings.Default.GmailImapServer :
                Properties.Settings.Default.ImapServer;
            int Port = Gmail ? Int32.Parse(Properties.Settings.Default.GmailServerPort) :
                Int32.Parse(Properties.Settings.Default.ServerPort);
            string Username = Properties.Settings.Default.Username;
            string Password = Encryption.DecryptString(Properties.Settings.Default.Password);
            bool SSL = Gmail ? true : Properties.Settings.Default.UseSSL;

            IC = new ImapClient(Host, Port, Username, Password, AuthMethod.Login, SSL);
            IsRunning = true;

            /* Does NOT run in the context of the "UI thread" but in its _own_ thread */
            IC.NewMessage += (sender, e) => {
                MailMessage m = null;
                int messageCount;
                lock (IC) {
                    m = IC.GetMessage(e.MessageUID, FetchOptions.TextOnly, false);
                    messageCount = IC.Search(SearchCondition.Unseen()).Length;
                };
                NewMessageEventArgs args = new NewMessageEventArgs(m, messageCount);
                NewMessageEvent(sender, args);
            };
        }
Esempio n. 13
0
        public void Initialize(String serverURL, int port, bool useSSL)
        {
            _serviceManager = new ServiceManager<ImapClientWrapper>("Imap Service: " + serverURL, "Email Services");

            _internalClient = new ImapClient(serverURL, port, useSSL);
            
            _serviceManager.LogEvent("Installed event listener for new messages.");
        }
Esempio n. 14
0
 private GetEmailResponse GetImapEmail(GetEmailRequest getEmailRequest)
 {
     using (var client = new ImapClient(getEmailRequest.HostName, getEmailRequest.Port, getEmailRequest.UserName, getEmailRequest.Password, AuthMethod.Login, getEmailRequest.UseSSL))
     {
         var uids = client.Search(SearchCondition.Unseen());
         var messages = client.GetMessages(uids);
         return new GetEmailResponse
         {
             Messages = messages
         };
     }
 }
Esempio n. 15
0
        //#######################
        //#Receive email methods#
        //#######################
        /// <summary>
        /// Retrieves all the unseen messages from the server
        /// </summary>
        /// <param name="FromAddress">User's email address</param>
        /// <param name="FromPass">User's password</param>
        /// <returns>All the retrieved messages</returns>
        public static List<MailMessage> GetAllMessages(string FromAddress, string FromPass)
        {
            // Check the host
            if (CheckEmailHostIMAP(FromAddress) == true && !(string.IsNullOrEmpty(FromPass)))
            {
                try
                {
                    // Create a new ImapClient
                    ImapClient client = new ImapClient(Host, Port, FromAddress, FromPass, AuthMethod.Login, true);

                    // Get the uids
                    IEnumerable<uint> uids = client.Search(SearchCondition.All());

                    // Get the messages
                    IEnumerable<MailMessage> Messages = client.GetMessages(uids);

                    // Convert to list
                    List<MailMessage> MessagesList = Messages.ToList<MailMessage>();

                    // Return them
                    return MessagesList;
                }
                catch (Exception exception)
                {
                    // Create the error message
                    string ErrorMessage = "ERROR 60002" + "\n" + exception.ToString();

                    // Show the error message
                    Program.ErrorPopupCall(ErrorMessage);

                    // Make an empty list to return
                    List<MailMessage> Stop = new List<MailMessage>();

                    // Stop executing this method
                    return Stop;
                }
            }
            else
            {
                // Create the error message
                string ErrorMessage = "ERROR 60003" + "\n" + "EmailHostIMAP(FromAddress) returned false";

                // Show the error message
                Program.ErrorPopupCall(ErrorMessage);

                // Make an empty list to return
                List<MailMessage> Stop = new List<MailMessage>();

                // Stop executing this method
                return Stop;
            }
        }
Esempio n. 16
0
        public void Run()
        {
            if (this.Options.ImapPort == 0)
                this.Options.ImapPort = this.Options.ImapSsl ? 993 : 143;

            if (this.Options.Password == null)
            {
                Console.WriteLine("Enter password:"******"Opening imap connection to {this.Options.ImapServer}:{this.Options.ImapPort} using {this.Options.AuthMethod}.");
            // The default port for IMAP over SSL is 993.
            using (
                var client = new ImapClient(
                    this.Options.ImapServer,
                    this.Options.ImapPort,
                    this.Options.UserName,
                    this.Options.Password,
                    this.Options.AuthMethod,
                    this.Options.ImapSsl))
            {
                Log.Info($"Retrieving mailboxes.");
                var mailboxes = client.ListMailboxes();

                var targetDirectory = Directory.CreateDirectory(this.Options.Target);

                // delete obsolete folders
                foreach (var dir in
                    targetDirectory.GetDirectories("*.*", SearchOption.AllDirectories).OrderByDescending(d => d.FullName) // Descending to ensure child folders are first
                                   .Where(dir => !mailboxes.Any(m => IsSameDirectory(Path.Combine(targetDirectory.FullName, m), dir.FullName))))
                {
                    if (this.Options.Delete)
                    {
                        Log.Verbose($"Deleting depricated mailbox {dir}.");
                        dir.Delete(true);
                    }
                    else
                        Log.Verbose($"Mailbox {dir} is depricated.");
                }

                foreach (var mailbox in mailboxes)
                    this.SynchronizeMailbox(client, mailbox, Directory.CreateDirectory(Path.Combine(targetDirectory.FullName, mailbox)));

                //IEnumerable<uint> uids = client.Search(SearchCondition.All());
                Log.Verbose("Disconnecting.");
            }
            Log.Info("Disconnected.");
        }
Esempio n. 17
0
        public void DeleteMessage(EmailMessage email)
        {
            using (ImapClient client = new ImapClient(imapHost, 993, username, password, AuthMethod.Login, true))
            {

                try { client.MoveMessage(email.getUID(), "[Gmail]/Trash"); }
                catch (BadServerResponseException e)
                {
                    //be really sad
                }catch(Exception e)
                {
                    ALSMessageBox mb = new ALSMessageBox("Unknown error occurred");
                    mb.Show();
                }

            }
        }
Esempio n. 18
0
        //Starts a session with the authenticated user credentials
        public void logIn()
        {
            this.Client = new ImapClient("imap.gmail.com", 993, true);

            try
            {
                this.Client.Login(mailAddress, mailPassword, AuthMethod.Auto);
            }
            catch(InvalidCredentialsException)
            {
                Console.WriteLine("The server rejected the supplied credentials");
            }

            isConnected = true;
            //this.Client.Dispose();

        }
Esempio n. 19
0
        public IEnumerable <MailDto> ReceiveAsync(params string[] identifiers)
        {
            using (var client = new S22.Imap.ImapClient(this.Host, this.Port, this.EnableSsl))
            {
                client.Login(this.Email, this.Password.Decrypt(), AuthMethod.Login);

                var uids             = client.Search(SearchCondition.All());
                var identifiersAsUid = identifiers.Select(x => Convert.ToUInt32(x));

                foreach (var uid in uids.Where(x => !identifiersAsUid.Contains(x)))
                {
                    var message = client.GetMessage(uid);
                    yield return(this.CreateMail(message, uid.ToString()));
                }

                client.Logout();
            }
        }
        private void frmUpdateEmailTest_Load(object sender, EventArgs e)
        {
            {
                using (ImapClient client = new ImapClient("imap.gmail.com", 993, "*****@*****.**", "DeMonfortUniversity2015", AuthMethod.Auto, true))
                {
                    var uids = client.Search(SearchCondition.All());
                    var messages = client.GetMessages(uids);

                    foreach (var mail in messages)
                    {
                        var header = mail.Headers["Subject"];
                        string body = mail.Body;
                        string from = Convert.ToString(mail.From);
                        string output = from.Substring(from.IndexOf("<") + 1, from.IndexOf(">") - from.IndexOf("<") - 1);
                        textBox1.Text = output;
                    }
                }
            }
        }
        public IMAPPlugin(string host, string port)
            : base(host, port)
        {
            _sessions = new Dictionary<string, ImapClient>();

            LoggedIn += (sender, login) =>
            {
                var address = new MailAddress(login.LoginPayload.legacyName);
                var service = DnsClient.Default.Resolve(string.Format("_imaps._tcp.{0}", address.Host), RecordType.Srv)
                    .AnswerRecords.OfType<SrvRecord>().First();
                var newClient = new ImapClient(service.Target, service.Port,
                    login.LoginPayload.legacyName, login.LoginPayload.password, AuthMethod.Auto, true);
                SendMessage(WrapperMessage.Type.TYPE_CONNECTED, new Connected {user = login.LoginPayload.user});
                SendMessage(WrapperMessage.Type.TYPE_BUDDY_CHANGED, new Buddy
                {
                    userName = login.LoginPayload.user,
                    buddyName = address.Host,
                    status = StatusType.STATUS_ONLINE
                });
                newClient.NewMessage += (o, args) =>
                {
                    var msg = args.Client.GetMessage(args.MessageUID, FetchOptions.HeadersOnly).Subject;
                    args.Client.RemoveMessageFlags(args.MessageUID, null, MessageFlag.Seen);
                    SendMessage(WrapperMessage.Type.TYPE_CONV_MESSAGE, new ConversationMessage
                    {
                        userName = login.LoginPayload.user,
                        buddyName = address.Host,
                        headline = true,
                        message = msg
                    });
                };
                _sessions.Add(login.LoginPayload.user, newClient);
            };

            LoggedOut += (sender, args) =>
            {
                var user = args.LogoutPayload.user;
                if (!_sessions.ContainsKey(user)) return;
                _sessions[user].Logout();
                _sessions.Remove(user);
            };
        }
Esempio n. 22
0
        private void SynchronizeMailbox(ImapClient client, string mailbox, DirectoryInfo target)
        {
            var info = client.GetMailboxInfo(mailbox);

            Log.Info($"Synchronizing mailbox {info.Name} ({mailbox}).");

            // Fetch online data
            var onlineUids = client.Search(SearchCondition.All(), mailbox).ToList();
            Log.Verbose($"Found {onlineUids.Count()} messages online.");

            // Match offline data
            foreach (var file in target.GetFiles("*.eml"))
            {
                var fileName = Path.GetFileNameWithoutExtension(file.Name);
                uint fileUid;
                if (!uint.TryParse(fileName.PadLeft(8, '0').Substring(0, 8), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out fileUid))
                {
                    Log.Warn($"Unexpected file '{file.Name}' found in mailbox {mailbox}.");
                    continue;
                }

                if (this.Options.Delete && !onlineUids.Contains(fileUid))
                {
                    Log.Verbose($"Deleting obsolete message '{file.Name}'...");
                    file.Delete();
                }

                onlineUids.Remove(fileUid);
            }

            // Fetch new files
            Log.Info($"Fetching {onlineUids.Count} messages...");
            foreach (var onlineUid in onlineUids)
            {
                var message = client.GetMessage(onlineUid, FetchOptions.Normal, false, mailbox);
                if (message.From == null)
                    message.From = new MailAddress(Options.UserName);
                var fileName = $"{onlineUid:x8} {CleanSubject(message.Subject)}.eml";
                message.Save(Path.Combine(target.FullName, fileName));
                Log.Verbose($"Fetched message '{fileName}'");
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Get mails from server IMAP
        /// </summary>
        /// <param name="username">Username to connect to server(usually your email)</param>
        /// <param name="password">Password to connect</param>
        /// <param name="hostIn">host server</param>
        /// <param name="portIn">port</param>
        /// <param name="secure">Secure receiving</param>
        /// <returns>List of mails [from, date, subject, body]</returns>
        public static List<string[]> getMails(string username, string password, string hostIn, int portIn, bool secure)
        {
            List<string[]> messagesList = new List<string[]>();

            using (ImapClient Client = new ImapClient(hostIn, portIn, username, password, AuthMethod.Login, secure))
            {
                //IEnumerable<uint> uids = Client.Search(SearchCondition.Unseen());
                IEnumerable<uint> uids = Client.Search(SearchCondition.All());
                IEnumerable<MailMessage> messages = Client.GetMessages(uids);

                foreach (var message in messages)
                {
                    string from = message.From.Address.ToString().Trim();
                    string date = message.Date().ToString().Trim();
                    string subject = message.Subject.ToString().Trim();
                    string body = message.Body.ToString().Trim();

                    messagesList.Add(new string[] { from, subject, date, body });
                }
            }
            return messagesList;
        }
Esempio n. 24
0
 private void CargarNoLeidos()
 {
     var imap = new ImapClient(
            config.imap, config.puerto, config.correo, config.pwd, AuthMethod.Auto, true);
       IEnumerable<uint> uids = imap.Search(SearchCondition.Unseen());
       IEnumerable<MailMessage> mensajes = imap.GetMessages(uids);
       foreach (var m in mensajes) {
     DateTime d = Convert.ToDateTime(m.Headers.Get("Date"));
     int indice = dataGridView1.Rows.Add(m.From, m.Subject, d);
     dataGridView1.Rows[indice].Tag = m;
     dataGridView1.Sort(dataGridView1.Columns[2], System.ComponentModel.ListSortDirection.Descending);
       }
 }
Esempio n. 25
0
 public MailFetcher()
 {
     var credProvider = new MailCredentialsProvider();
     _client = new ImapClient("imap.gmail.com", 993, credProvider.GetLogin(), credProvider.GetPassword(), AuthMethod.Login, true);
     _repo = new MailRepository();
 }
Esempio n. 26
0
 public void ReceiveMail()
 {
     try
     {
         string username = AppState.Config.Get("ReceiveMailPlugin.Username", "*****@*****.**");
         string password = AppState.Config.Get("ReceiveMailPlugin.Password", "tnopresenter");
         string server = AppState.Config.Get("ReceiveMailPlugin.Server", "imap.gmail.com");
         int port = AppState.Config.GetInt("ReceiveMailPlugin.Port", 993);
         if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) return;
         Client = new ImapClient(server, port, username, password, AuthMethod.Login, true);
         
         // Should ensure IDLE is actually supported by the server
         if (Client.Supports("IDLE") == false)
         {
             Logger.Log("ReceiveMailPlugin", "Server does not support IMAP IDLE", "", Logger.Level.Info);
         }
         else
         {
             // We want to be informed when new messages arrive
             Client.NewMessage += OnNewMessage;
         }
     }
     catch (Exception exception)
     {
         Logger.Log("ReceiveMailPlugin", "Error initializing imap server, check settings", exception.Message,
             Logger.Level.Error);
     }
 }
Esempio n. 27
0
        public void retrieveMail(String mailbox = "INBOX")
        {
            currentMailBox = mailbox;
            MailList.Clear();

            if (imapHost.Equals(null) || imapHost.Equals(null) || password.Equals(null))
            {
                ALSMessageBox mb = new ALSMessageBox("Not logged in");
                mb.Show();
                return;
            }

            try {
                // The default port for IMAP over SSL is 993.
                using (ImapClient client = new ImapClient(imapHost, 993, username, password, AuthMethod.Login, true))
                {
                    folders = client.ListMailboxes();
                    Console.WriteLine("We are connected!");
                    // Returns a collection of identifiers of all mails matching the specified search criteria.
                    IEnumerable<uint> uids = null;
                    uids = client.Search(SearchCondition.All(), mailbox);
                    // Download mail messages from the default mailbox.
                    uint[] uidArray = uids.ToArray();
                    Array.Reverse(uidArray);

                    uids = uids.Reverse();

                    if (uidArray.Length > DOWNLOAD_COUNT)
                        Array.Resize(ref uidArray, DOWNLOAD_COUNT);

                    IEnumerable<MailMessage> messages = client.GetMessages(uidArray, FetchOptions.NoAttachments, true, mailbox);
                    IEnumerator<MailMessage> messageList = messages.GetEnumerator();
                    IEnumerator<uint> uidList = uids.GetEnumerator();

                    while (messageList.MoveNext())
                    {
                        uidList.MoveNext();

                        string toAddress;

                        try
                        {
                            toAddress = messageList.Current.To[0].Address;
                        }
                        catch
                        {
                            toAddress = "None";
                        }

                        EmailMessage temp = new EmailMessage(messageList.Current.Subject, messageList.Current.Body,
                            toAddress, messageList.Current.From.Address, EmailClient.Date(messageList.Current),
                            uidList.Current);

                        int hash = temp.GetHashCode();

                        bool contains = false;

                        foreach (EmailMessage m in MailList)
                        {
                            if (m.GetHashCode().Equals(hash))
                                contains = true;
                        }

                        if (!contains)
                        {
                            bool added = false;
                            int index = 0;
                            if (MailList.Count == 0)
                            {
                                MailList.Add(temp);
                            }
                            else
                            {

                                while (!added && index < MailList.Count)
                                {
                                    switch (MailList[index].CompareTo(temp))
                                    {
                                        case -1:
                                            MailList.Insert(index, temp);
                                            added = true;
                                            break;
                                        case 0:
                                            MailList.Insert(index, temp);
                                            added = true;
                                            break;
                                        case 1:
                                            index++;
                                            break;
                                        case -99: //error code
                                            break;
                                    }
                                }
                                if (!added)
                                    MailList.Add(temp);
                            }

                        }

                    }

                }

                MailList.Reverse();
            }
            catch (InvalidCredentialsException)
            {

            }catch(System.Net.Sockets.SocketException e)
            {
                ALSMessageBox mb = new ALSMessageBox("Not connected to internet");
                mb.Show();
            }catch(Exception e)
            {
                ALSMessageBox mb = new ALSMessageBox("Unknown error occurred");
                mb.Show();
            }
        }
Esempio n. 28
0
   //ReadEmail is the handler for email based detectors. It is designed
   //to retrieve email from a configured email service and parse the alerts
   public static void ReadEmail(string sVendor, string sFolderName, string sFolderNameTest, string sDetectorEmail, bool isParamTest)
    {
      switch (sVendor)
      {
        //Outlook based email plugin which requires the Outlook client to be installed.
        case "outlook":
        #region Microsoft Outlook Plugin
          //try
          //{
          //  //Setup connection information to mailstore
          //  //If logon information is null then mailstore must be open already
          //  //var oApp = new Microsoft.Office.Interop.Outlook.Application();
          //  //var sFolder = new Microsoft.Office.Interop.Outlook.Folder(sFolderName);
          //  //var oNameSpace = oApp.GetNamespace("MAPI");
          //  //oNameSpace.Logon(null, null, true, true);
          //  //var oInboxFolder = oNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
          //  //Outlook.Folder oFolder = oInboxFolder.Folder[sFolderName];

          //  //logging
          //  //Logging_Fido.Main.RunLogging("Running FIDO on file " + sFolderName);

          //  ////attach to folder and for each item in the folder then loop. During loop assign subject, body and detect malware type
          //  //foreach (var item in sFolder.Items)
          //  //{
          //  //  var oMailItem = item as Microsoft.Office.Interop.Outlook._MailItem;
          //  //  if (oMailItem != null)
          //  //  {
          //  //    var sMessageBody = oMailItem.Body;
          //  //  }
          //  //  if (oMailItem != null)
          //  //  {
          //  //    var sSubject = oMailItem.Subject;
          //  //  }
          //    //List<string> sERet = scan_email(sSubject, sMessageBody, sFolderName);
          //  //  if (sERet.First() == "Test Email")
          //  //  {
          //  //    oMailItem.Delete();
          //  //  }
          //  //  else
          //  //  {
          //  //    fido.Form1.Run_FIDO(sMessageBody, sERet, "fubar", false, false, true, sVendor);//MalwareType
          //  //    oMailItem.Delete();
          //  //  }
          //  }
            #endregion

          //}
          //catch (Exception e)
          //{
          //  Fido_Modules.Fido.Fido_EventHandler.SendEmail("Fido Error", "Fido Failed: {0} Exception caught in Outlook emailreceive area:" + e);
          //}
          break;

        case "exchange":
        #region Microsoft Exchange Plugin
          //still need to build out direct Exchange access
          #endregion
          break;
        
        //IMAP based email plugin which has been verified to work with Gmail
        case "imap":
        #region IMAP Plugin
          try
          {
            //get encrypted password and decrypt
            //then login
            var sfidoemail = Object_Fido_Configs.GetAsString("fido.email.fidoemail", null);
            var sfidopwd = Object_Fido_Configs.GetAsString("fido.email.fidopwd", null);
            var sfidoacek = Object_Fido_Configs.GetAsString("fido.email.fidoacek", null);
            var sImapServer = Object_Fido_Configs.GetAsString("fido.email.imapserver", null);
            var iImapPort = Object_Fido_Configs.GetAsInt("fido.email.imapport", 0);
            sfidoacek = Aes_Crypto.DecryptStringAES(sfidoacek, "1");
            sfidopwd = Aes_Crypto.DecryptStringAES(sfidopwd, sfidoacek);
            IImapClient gLogin = new ImapClient(sImapServer, iImapPort, sfidoemail, sfidopwd, AuthMethod.Login, true);

            var sSeperator = new[] { "," };
            gLogin.DefaultMailbox = isParamTest ? sFolderNameTest : sFolderName;
            var listUids = new List<uint>();

            //seperate out list of email addresses handed to emailreceive
            //then run query based on each email from the specified folder
            //and finally convert to array
            string[] aryInboxSearch = sDetectorEmail.Split(sSeperator, StringSplitOptions.RemoveEmptyEntries);
            foreach (var search in aryInboxSearch)
            {
              listUids.AddRange(gLogin.Search(SearchCondition.From(search)).ToList());
            }
            var uids = listUids.ToArray();
            uids = uids.Take(50).ToArray();
            var msg = gLogin.GetMessages(uids);
            var mailMessages = msg as MailMessage[] ?? msg.ToArray();
            for (var i = 0; i < mailMessages.Count(); i++)
            {
              var sMessageBody = mailMessages[i].Body;
              var sSubject = mailMessages[i].Subject;
              var sERet = ScanEmail(sSubject, sMessageBody, sFolderName, isParamTest);
              if (sERet == "Test Email")
              {
                Console.WriteLine(@"Test email found, putting in processed folder.");
                gLogin.MoveMessage(uids[i], "Processed");
              }
              else
              {
                Console.WriteLine(@"Finished processing email alert, puttig in processed folder.");
                gLogin.MoveMessage(uids[i], "Processed");
              }
            }
            #endregion
          }
          catch (Exception e)
          {
            Fido_EventHandler.SendEmail("Fido Error", "Fido Failed: {0} Exception caught in IMAP emailreceive area:" + e);
          }
          Console.WriteLine(@"Finished processing email alerts.");
          break;
      }
    }
Esempio n. 29
0
 public void Dispose()
 {
     _context.Dispose();
     _context = null;
 }
Esempio n. 30
0
        public string[] ListFolders()
        {
            if (folders == null)
            {
                using (ImapClient client = new ImapClient(imapHost, 993, username, password, AuthMethod.Login, true))
                {
                    folders = client.ListMailboxes();
                }
            }

            return folders;
        }
Esempio n. 31
0
 public MailBox(ClientParameters clientParameters)
 {
     _clientParameters = clientParameters;
     _client = new ImapClient(_clientParameters.Host, _clientParameters.Port, _clientParameters.Username,
             _clientParameters.Password, AuthMethod.Auto, true);
 }
Esempio n. 32
0
        private void CargarTodos()
        {
            var imap = new ImapClient(
                   config.imap, config.puerto, config.correo, config.pwd, AuthMethod.Auto, true);
              IEnumerable<uint> uids = imap.Search(
                                 SearchCondition.SentSince(DateTime.Now.AddDays(-7)), "inbox"
                               );
              foreach (uint uid in uids) {
            Application.DoEvents();
            Text = uid + "" + uids.Count();
            if (!dataGridView1.IsDisposed) {
              MailMessage m = imap.GetMessage(uid,false);
              DateTime d = Convert.ToDateTime(m.Headers.Get("Date"));
              int indice = dataGridView1.Rows.Add(m.From, m.Subject, d);
              dataGridView1.Rows[indice].Tag = m;
              dataGridView1.Sort(dataGridView1.Columns[2], System.ComponentModel.ListSortDirection.Descending);
            } else {
              break;
            }
              }

              if (imap.Supports("IDLE")) {
            imap.NewMessage += OnNewMessage;
              }
        }
Esempio n. 33
0
		/// <summary>
		/// Initializes a new instance of the IdleMessageEventArgs class and sets the
		/// MessageCount attribute to the value of the <paramref name="MessageCount"/>
		/// parameter.
		/// </summary>
		/// <param name="MessageCount">The number of messages in the selected mailbox.</param>
		/// <param name="MessageUID"> The unique identifier (UID) of the newest message in the
		/// mailbox.</param>
		/// <param name="Client">The instance of the ImapClient class that raised the event.</param>
		internal IdleMessageEventArgs(uint MessageCount, uint MessageUID,
			ImapClient Client) {
			this.MessageCount = MessageCount;
			this.MessageUID = MessageUID;
			this.Client = Client;
		}