Ejemplo n.º 1
0
        private Pop3 CreateMailClient()
        {
            var client = new Pop3();

            if (Pars.UseSsl)
            {
                client.SSLConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
                if (Pars.Port == 0)
                {
                    client.ConnectSSL(Pars.IncomingServer);
                }
                else
                {
                    client.ConnectSSL(Pars.IncomingServer, Pars.Port);
                }
            }
            else
            {
                if (Pars.Port == 0)
                {
                    client.Connect(Pars.IncomingServer);
                }
                else
                {
                    client.Connect(Pars.IncomingServer, Pars.Port);
                }
            }

            client.Login(Pars.Username, Pars.Password);
            client.ServerCertificateValidate += OnCertificateValidate;
            return(client);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Connects to POP3 server.
        /// </summary>
        /// <param name="host">Host name or IP address.</param>
        /// <param name="serverEncryption">Server encryption (SslTls, Unencrypted, StartTls)</param>
        /// <seealso cref="M:Limilabs.Client.ClientBase.Connect(System.String,System.Int32,System.Boolean)" />
        /// <exception cref="T:Limilabs.Client.ServerException">DNS resolving error, connection error.</exception>
        /// <exception cref="T:Limilabs.Client.POP3.Pop3ResponseException">Initial error response.</exception>
        public void Connect(MailServerEncryption serverEncryption, string host)
        {
            switch (serverEncryption)
            {
            case MailServerEncryption.SslTls:
            {
                _pop3.ConnectSSL(host);
                break;
            }

            case MailServerEncryption.Unencrypted:
            {
                _pop3.Connect(host);
                break;
            }

            case MailServerEncryption.StartTls:
            {
                _pop3.Connect(host);
                _pop3.StartTLS();
                break;
            }

            default:
            {
                _pop3.Connect(host);
                break;
            }
            }
        }
        public void Connect(string server, string port, string encryption)
        {
            int portInt;

            if (int.TryParse(port, out portInt))
            {
                if ((string)encryption == "STARTTLS")
                {
                    pop.Connect(server, portInt);
                    pop.StartTLS();
                }
                else
                {
                    pop.ConnectSSL(server, portInt);
                }
            }
            else
            {
                if ((string)encryption == "STARTTLS")
                {
                    pop.Connect(server);
                    pop.StartTLS();
                }
                else
                {
                    pop.ConnectSSL(server);
                }
            }
        }
Ejemplo n.º 4
0
        // Connect to POP3
        public async Task <Pop3> ConnectPop3(Model.UserInfo userInfo)
        {
            var serverconnTask = Task.Run(() =>
            {
                Pop3 pop3 = new Pop3();

                if (userInfo.EncryptionType == Model.Enum.EncryptionType.Unencrypted)
                {
                    pop3.Connect(userInfo.Server, userInfo.Port);
                }
                else if (userInfo.EncryptionType == Model.Enum.EncryptionType.SSLTLS)
                {
                    pop3.ConnectSSL(userInfo.Server, userInfo.Port);
                }
                else
                {
                    pop3.Connect(userInfo.Server, userInfo.Port);
                    pop3.StartTLS();
                }
                pop3.UseBestLogin(userInfo.UserName, userInfo.Password);
                return(pop3);
            });
            var completedTask = await Task.WhenAny(serverconnTask);

            if (completedTask == serverconnTask)
            {
                return(await serverconnTask);
            }
            else
            {
                throw new TimeoutException("server Connection timed out");
            }
        }
Ejemplo n.º 5
0
        private void buttonClientPop_Click(object sender, EventArgs e)
        {
            using (Pop3 pop3 = new Pop3())
            {
                pop3.Connect("mail.invoicedigital.cl");       // or ConnectSSL for SSL
                pop3.UseBestLogin("*****@*****.**", "sctgermany2016");

                foreach (string uid in pop3.GetAll())
                {
                    // verifico si existe el uid en la base
                    Console.WriteLine("Message unique-id: {0};", uid);
                    string nomArchivo = string.Empty;
                    if (descargaModel.exist(uid) == "False")
                    {
                        IMail email = new MailBuilder()
                                      .CreateFromEml(pop3.GetMessageByUID(uid));

                        Console.WriteLine("===================================================");
                        Console.WriteLine(email.Subject);
                        Console.WriteLine(email.Text);

                        foreach (MimeData mime in email.Attachments)
                        {
                            mime.Save(@"C:\AdmToSii\file\xml\proveedores\" + mime.SafeFileName);
                            nomArchivo = mime.SafeFileName;
                        }
                        Console.WriteLine("===================================================");
                        descargaModel.uid        = uid;
                        descargaModel.nomArchivo = nomArchivo;
                        descargaModel.save(descargaModel);
                    }
                }
                pop3.Close();
            }
        }
Ejemplo n.º 6
0
        private void DeleteEmails()
        {
            foreach (var account in LoadAccounts())
            {
                _logger.InfoFormat("Deleting emails from account: {0}", account.User);
                using (var client = new Pop3())
                {
                    client.Connect(_popHost, _popPort, _popUseSsl);
                    client.UseBestLogin(account.User, account.Password);

                    var stats = client.GetAccountStat();

                    long loopLimit = _batchSizePerAccount;
                    if (stats.MessageCount < loopLimit)
                        loopLimit = stats.MessageCount;

                    for (var i = 1; i <= loopLimit; i++)
                    {
                        var email = new MailBuilder().CreateFromEml(client.GetMessageByNumber(i));

                        if(email.Date.HasValue && 
                            DateTime.Now.Subtract(email.Date.Value).TotalDays > _deleteEmailsOlderThanDays)
                        {
                            client.DeleteMessageByNumber(i);
                        }
                    }
                }
            }
        }
 private void ConnectAndLogin(Pop3 imap)
 {
     if (Encryption == Constants.Encryptions.SSL_TLS)
     {
         imap.ConnectSSL(Host, PortNumber);
     }
     else if (Encryption == Constants.Encryptions.START_TLS)
     {
         imap.Connect(Host, PortNumber);
         imap.StartTLS();
     }
     else
     {
         imap.Connect(Host, PortNumber);
     }
     imap.UseBestLogin(Username, Password);
 }
Ejemplo n.º 8
0
        public void FetchMessages(NameValueCollection param)
        {
            Pop3 client = new Pop3();
            bool connected = false;
            try
            {
                string outdir = RequireParam("outdir", param);
                if (!Directory.Exists(outdir)) Directory.CreateDirectory(outdir);

                string server = RequireParam("server", param);
                int port = Convert.ToInt32(RequireParam("port", param));
                string ssl = param["ssl"];
                if (ssl.Length == 0)
                    ssl = port == 995 ? "1" : "0";

                TlsParameters par = new TlsParameters();
                par.CommonName = server;
                par.CertificateVerifier = CertificateVerifier.AcceptAll;
                Pop3Security sec = (Pop3Security)Enum.Parse(typeof(Pop3Security), RequireParam("security", param));
                log.Info("Connecting to {0}:{1}. SSL: {2}", server, port, ssl);

                string sess = client.Connect(server, port, par, sec);

                connected = true;
                log.Info("Connected: {0}", sess);
                Pop3Authentication auth = (Pop3Authentication)Enum.Parse(typeof(Pop3Authentication), RequireParam("auth", param));
                log.Info("Logging in: {0}", RequireParam("user", param));
                client.Login(RequireParam("user", param), RequireParam("pwd", param), auth);
                log.Info("Logged in.");

                Pop3MessageCollection messages = client.GetMessageList();
                log.Info("There are {0} messages", messages.Count);
                int maxcount = Convert.ToInt32(RequireParam("maxcount", param));
                if (maxcount <= 0 || maxcount > messages.Count) maxcount = messages.Count;
                for (int i = 0; i < maxcount; i++)
                {
                    Pop3MessageInfo mi = messages[i];
                    log.Info("Downloading message {0}", mi.SequenceNumber);
                    MailMessage mm = client.GetMailMessage(mi.SequenceNumber);
                    log.Info("Message from: {0}, to: {1}, subject: {2}", mm.From, mm.To, mm.Subject);
                    string g = Guid.NewGuid().ToString();
                    string file = Path.Combine(outdir, g + ".eml");
                    log.Info("Saving message to {0}", file);
                    mm.Save(file);
                    client.Delete(mi.SequenceNumber);
                }

                bool rollback = !"0".Equals(RequireParam("noremove", param));
                client.Disconnect(rollback);
            }
            catch (Exception ex)
            {
                if (connected)
                    client.Disconnect(true);
                throw;
            }
        }
Ejemplo n.º 9
0
 public void Connect(string serverAddress, int port)
 {
     try
     {
         _pop3.Connect(serverAddress, port);
     }
     catch (MailBeeException ex)
     {
         EmailClientExceptionHandler.HandleConnectException(ex);
     }
 }
Ejemplo n.º 10
0
        private async Task <Pop3> Connect(UserInfo userInfo)
        {
            var  timeout     = _settings.ConnectionTimeOutMilliseconds;
            Task timeoutTask = Task.Delay(timeout);

            var connectionTask = Task.Run(() =>
            {
                Pop3 pop3 = _pop3Factory.GetInstance();

                if (userInfo.EncryptionType == Model.Enum.EncryptionType.Unencrypted)
                {
                    pop3.Connect(userInfo.Server, userInfo.Port);
                }
                else if (userInfo.EncryptionType == Model.Enum.EncryptionType.SslTls)
                {
                    pop3.ConnectSSL(userInfo.Server, userInfo.Port);
                }
                else
                {
                    pop3.Connect(userInfo.Server, userInfo.Port);
                    pop3.StartTLS();
                }

                pop3.UseBestLogin(userInfo.UserName, userInfo.Password);

                return(pop3);
            });

            var completedTask = await Task.WhenAny(connectionTask, timeoutTask);

            if (completedTask == connectionTask)
            {
                return(await connectionTask);
            }
            else
            {
                throw new TimeoutException("Connection with the server timed out");
            }
        }
Ejemplo n.º 11
0
        public void POPListMailDownLoad(string account, string password, string serverName, int serverPort = 995)
        {
            MailBee.Global.LicenseKey = LicenseKey.Key;

            Pop3 pop = new Pop3();

            try {
                pop.Connect(serverName, serverPort);
                pop.Login(account, password);
            }
            catch {
                throw new Exception("登陆失败");
            }
            var ss = pop.DownloadEntireMessages();
        }
        private static Pop3 GetPopClient(string server, int port, bool useSSL, string login, string password)
        {
            var client = new Pop3();

            client.ServerCertificateValidate +=
                new Limilabs.Client.ServerCertificateValidateEventHandler(
                    delegate(object sender, Limilabs.Client.ServerCertificateValidateEventArgs e)
            {
                e.IsValid = true;
            });

            client.Connect(server, port, useSSL);
            client.Login(login, password);
            return(client);
        }
Ejemplo n.º 13
0
        private bool TryConnect()
        {
            if (_client.IsConnected)
            {
                return(true);
            }

            if (_settings.UseSSL)
            {
                _client.SslMode = _settings.Port == 110 ? SslStartupMode.UseStartTls : SslStartupMode.OnConnect;
            }

            _client.Connect(_settings.MailServer, _settings.Port);

            return(_client.IsConnected);
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            Pop3 pop3 = new Pop3();

            pop3.host     = "10.1.1.123";
            pop3.userName = "******";
            pop3.password = "******";

            pop3.Connect();
            pop3.Login();
            pop3.GetAccountStat();

            for (int i = 1; i <= pop3.messageCount; i++)
            {
                Pop3Message message = pop3.GetMessageHeader(i);

                Console.WriteLine("--mail header #" + i.ToString());
                Console.WriteLine(message.from);
                Console.WriteLine(message.subject);
                Console.WriteLine(message.replyTo);
                Console.WriteLine(message.date);
                Console.WriteLine(message.contentType);
                Console.WriteLine(message.charset);
            }

            for (int j = 1; j <= pop3.messageCount; j++)
            {
                Console.WriteLine("-----first mail all:------");
                Pop3Message message = pop3.GetMessage(j);

                Console.WriteLine(message.from);
                Console.WriteLine(message.subject);

                if (message.hasAttachments == true)
                {
                    DumpAttachments(message.attachments);
                }
                else
                {
                    Console.WriteLine("body:" + message.body);
                }
            }
            pop3.Close();
            Console.WriteLine("END.");
            Console.ReadLine();
        }
Ejemplo n.º 15
0
        private void Connect(Func <Pop3, bool> onConnectFunction)
        {
            Debug.WriteLine("GetAll");

            Pop3.LicenseKey = "MN200-539BA4259BD99BD69B32E3AB96B2-6863";
            var pop = new Pop3();


            if (_ssl)
            {
                pop.SslProtocol = SecurityProtocol.Auto;
                pop.SslMode     = SslStartupMode.OnConnect;
            }

            try
            {
                if (pop.Connect(_server, _port, true))
                {
                    Debug.WriteLine("Connected");

                    if (pop.Login(_login,
                                  _password,
                                  AuthenticationMethods.Auto,
                                  AuthenticationOptions.PreferSimpleMethods,
                                  null))
                    {
                        Debug.WriteLine("Logged in " + pop.InboxMessageCount);
                        onConnectFunction(pop);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("GetAll");
                Debug.WriteLine(ex);
                _lastError = ex.Message;
            }
            finally
            {
                if (pop.IsConnected)
                {
                    pop.Disconnect();
                }
                pop.Dispose();
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// IMAP
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static List <IMail> GetByPop3(ServerItem item)
        {
            var mails = new List <IMail>();

            using (Pop3 pop3 = new Pop3())
            {
                pop3.Connect(item.Server, item.Port);  // or ConnectSSL for SSL
                pop3.UseBestLogin(item.User, item.Password);

                List <string> uids = pop3.GetAll();
                foreach (string uid in uids)
                {
                    mails.Add(new MailBuilder()
                              .CreateFromEml(pop3.GetMessageByUID(uid)));
                }
            }
            return(mails);
        }
Ejemplo n.º 17
0
        private void ReadMessages_Load(object sender, EventArgs e)
        {
            UserEmailLabel.Text = LoginForm.UserNameValue + " Mail List:";
            using (Pop3 pop3 = new Pop3())
            {
                pop3.Connect("pop.gmail.com", 995, true);
                pop3.UseBestLogin("recent:" + LoginForm.LoginValue, LoginForm.PasswordValue);
                List <string> UidList = pop3.GetAll();

                foreach (string uid in UidList)
                {
                    IMail email = new MailBuilder().CreateFromEml(pop3.GetMessageByUID(uid));
                    MailListBox.Items.Add(email.From);
                    MailListBox.Items.Add(email.GetBodyAsText());
                    MailListBox.Items.Add(" ");
                }
                pop3.Close();
            }
        }
Ejemplo n.º 18
0
        static void Main()
        {
            using (Pop3 pop3 = new Pop3())
            {
                pop3.Connect(_server);                      // Use overloads or ConnectSSL if you need to specify different port or SSL.
                pop3.Login(_user, _password);               // You can also use: LoginAPOP, LoginPLAIN, LoginCRAM, LoginDIGEST methods,
                                                            // or use UseBestLogin method if you want Mail.dll to choose for you.

                List<string> uidList = pop3.GetAll();       // Get unique-ids of all messages.

                foreach (string uid in uidList)
                {
                    IMail email = new MailBuilder().CreateFromEml(  // Download and parse each message.
                        pop3.GetMessageByUID(uid));

                    ProcessMessage(email);                          // Display email data, save attachments.
                }
                pop3.Close();
            }
        }
Ejemplo n.º 19
0
        static void Main()
        {
            using (Pop3 pop3 = new Pop3())
            {
                pop3.Connect(_server);                      // Use overloads or ConnectSSL if you need to specify different port or SSL.
                pop3.Login(_user, _password);               // You can also use: LoginAPOP, LoginPLAIN, LoginCRAM, LoginDIGEST methods,
                                                            // or use UseBestLogin method if you want Mail.dll to choose for you.

                List <string> uidList = pop3.GetAll();      // Get unique-ids of all messages.

                foreach (string uid in uidList)
                {
                    IMail email = new MailBuilder().CreateFromEml(  // Download and parse each message.
                        pop3.GetMessageByUID(uid));

                    ProcessMessage(email);                          // Display email data, save attachments.
                }
                pop3.Close();
            }
        }
Ejemplo n.º 20
0
            internal int Pop3Check()
            {
                try
                {
                    var pop3Settings = new Pop3Settings();
                    var obj          = new Pop3();
                    obj.Connect(pop3Settings.Host, pop3Settings.Username, pop3Settings.Password, pop3Settings.Port);
                    string KeyWord = Helpers.Xml.AppConfigQuery("jaNET/System/Comm/MailKeyword").Item(0).InnerText;

                    foreach (Pop3Message msg in obj.List())
                    {
                        Pop3Message msg2 = obj.Retrieve(msg);

                        /*Console.WriteLine("Message {0}: {1}",
                         *  msg2.number, msg2.message);*/
                        if (msg2.Message.Contains("<" + KeyWord + ">"))
                        {
                            //If a command found to mail subject
                            Match Command = Regex.Match(msg2.Message.Replace("\r\n", " "), @"(<" + KeyWord + ">)(.*?)(?=</" + KeyWord + ">)");
                            Command.ToString().ToLower().Replace("<" + KeyWord + ">", string.Empty).Parse();
                            obj.Delete(msg2);
                        }
                        else
                        {
                            //For Future Use

                            /*Match From = Regex.Match(msg2.message, @"(?<=From: )(.*?)(?= <)");
                             * Match Subject = Regex.Match(msg2.message, @"(?<=Subject: )(.*?)(?=\\r\\nDate: )"); //(?<=Subject:</B> )(.*?)(?=</)");
                             * MailList.Add("From " + From.ToString() + ", Subject " + Subject.ToString());*/
                            //From pattern (?<=From: \\\")(.*?)(?=\\\")
                            //Subject pattern (?<=Subject: )(.*?)(?=\\r)
                        }
                    }
                    obj.Disconnect();
                    return(obj.List().Count);
                }
                catch
                {
                    return(0);
                }
            }
Ejemplo n.º 21
0
        public Pop3Client(string username, string password, string server, int port, EncryptionType encryptionType)
            : base(username, encryptionType)
        {
            _pop3 = new Pop3();

            if (encryptionType == EncryptionType.SSLTLS)
            {
                _pop3.ConnectSSL(server, port);
            }
            else
            {
                _pop3.Connect(server, port);

                if (encryptionType == EncryptionType.StartTLS)
                {
                    _pop3.StartTLS();
                }
            }

            _pop3.Login(username, password);
        }
Ejemplo n.º 22
0
        public override void Connect()
        {
            System.Threading.Thread.Sleep(50);
            WebmailResourceManager resMan = (new WebmailResourceManagerCreator()).CreateResourceManager();

            try
            {
                _pop3Obj.InboxPreloadOptions = Pop3InboxPreloadOptions.Uidl;
                if (_account.MailIncomingPort == 995)
                {
                    _pop3Obj.SslMode     = SslStartupMode.OnConnect;
                    _pop3Obj.SslProtocol = SecurityProtocol.Auto;
                    _pop3Obj.SslCertificates.AutoValidation = CertificateValidationFlags.None;
                }
                Log.WriteLine("POP3 Connect", string.Format(@"'{0}' - '{1}'", _account.MailIncomingHost, _account.MailIncomingPort));
                Log.WriteLine("POP3 Connect", string.Format(@"IsConnected - '{0}'", _pop3Obj.IsConnected));
                _pop3Obj.Connect(_account.MailIncomingHost, _account.MailIncomingPort, true);
                Log.WriteLine("POP3 Connect", string.Format(@"IsConnected - '{0}'", _pop3Obj.IsConnected));
                Log.WriteLine("POP3 Login", string.Format(@"'{0}' - '{1}'", _account.MailIncomingLogin, _account.MailIncomingPassword));
                Log.WriteLine("POP3 Login", string.Format(@"IsLogined - '{0}'", _pop3Obj.IsLoggedIn));
                _pop3Obj.Login(_account.MailIncomingLogin, _account.MailIncomingPassword, AuthenticationMethods.Auto, AuthenticationOptions.PreferSimpleMethods, null);
                Log.WriteLine("POP3 Login", string.Format(@"IsLogined - '{0}'", _pop3Obj.IsLoggedIn));
            }
            catch (MailBeeConnectionException ex)
            {
                Log.WriteException(ex);
                throw new WebMailException(resMan.GetString("ErrorPOP3Connect"));
            }
            catch (MailBeePop3LoginBadCredentialsException ex)
            {
                Log.WriteException(ex);
                throw new WebMailException(resMan.GetString("ErrorPOP3IMAP4Auth"));
            }
            catch (MailBeeException ex)
            {
                Log.WriteException(ex);
                throw new WebMailMailBeeException(ex);
            }
        }
Ejemplo n.º 23
0
        private void button1_Click(object sender, EventArgs e)
        {
            using (Pop3 pop3 = new Pop3())
            {
                pop3.Connect("mail.invoicedigital.cl");       // or ConnectSSL for SSL
                pop3.UseBestLogin("*****@*****.**", "sopabru2011");

                foreach (string uid in pop3.GetAll())
                {
                    IMail email = new MailBuilder()
                                  .CreateFromEml(pop3.GetMessageByUID(uid));
                    Console.WriteLine("===================================================");
                    Console.WriteLine(email.Subject);
                    Console.WriteLine(email.Text);
                    foreach (MimeData mime in email.Attachments)
                    {
                        mime.Save(@"C:\AdmToSii\file\libroCompra\proveedores\" + mime.SafeFileName);
                    }
                    Console.WriteLine("===================================================");
                }
                pop3.Close();
            }
        }
Ejemplo n.º 24
0
        private void CheckEmail(object sender, System.Timers.ElapsedEventArgs args)
        {
            try
            {
                m_pop3 = new Pop3();
                m_pop3.Connect(m_strServer, m_strLogin, m_strPassword);
                ArrayList list = m_pop3.List();

                foreach (Pop3Message msg in list)
                {
                    Pop3Message msg2 = m_pop3.Retrieve(msg);
                    m_pop3.Delete(msg);

                    _OnMessageReceived(msg2.From, msg2.Subject, false);
                }

                m_pop3.Disconnect();
            }
            catch (Pop3Exception e)
            {
                _OnError(this, e.Message);
                return;
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Opens connection with email server based on UserAccount user settings
        /// </summary>
        /// <param name="ua"></param>
        /// <returns></returns>
        protected int ConnectToServer(UserAccount ua)
        {
            _ua = ua;
            try
            {
                if (ua.InUserProtocol == "POP3")
                {
                    // Connect to Server
                    if (ua.InUserSSL == "SSL")
                    {
                        _pop3.ConnectSSL(ua.InUserServer, Int32.Parse(ua.InUserPort));
                    }
                    else
                    {
                        _pop3.Connect(ua.InUserServer, Int32.Parse(ua.InUserPort));
                    }

                    // Use credentials
                    _pop3.UseBestLogin(ua.UserUsername, ua.UserPassword);
                    ua.SettingsVerified = true;
                    return(1);
                }
                else
                {
                    _imap.ConnectSSL(ua.InUserServer);
                    _imap.Login(ua.UserUsername, ua.UserPassword);
                    ua.SettingsVerified = true;
                    return(1);
                }
            }
            catch (Exception ex)
            {
                ua.SettingsVerified = false;
                return(0);
            }
        }
Ejemplo n.º 26
0
            //Receives messages from the Mailbox. Note that the state parameter is ignored; we're already
            //carrying our state in the AsyncState property of the base class. However, Receive() has to
            //take a single parameter of type Object in order to be a valid WaitCallback delegate.
            private void doReceive( object state )
            {
                Pop3 pop3 = null;
                bool bCaughtException = false;

                //This part does the work of connecting to the POP3 account, logging in, and
                //checking for new messages. If any messages were found, they will be downloaded
                //and stored in this.Messages
                try
                {
                    Mailbox box = this.AsyncState as Mailbox;

                    string server = box.Options.MailServer;
                    string username = box.Address;
                    string password = box.Options.MailServerPassword;

                    pop3 = new Pop3( );
                    pop3.User = username;
                    pop3.Password = password;

                    pop3.Connect( server );

                    if ( pop3.HasTimeStamp )
                        pop3.APOPLogin( );
                    else
                        pop3.Login( );

                    pop3.GetAccountStat( );
                    this.Messages = new SimpleMailMessage[ pop3.MessageCount ];

                    log.Debug(string.Format("pop3 check -- {0} - mail count:{1}", username, pop3.MessageCount));

                    //If we don't have any messages, go to sleep for a little while and try again.
                    //We'll keep doing this sleep/retry loop until a message shows up. That way, SoapTransport
                    //never has to pay any attention to us until we actually have work for it to do.
                    if ( pop3.MessageCount == 0 )
                    {
                        pop3.Close( );
                        pop3 = null;
                        SleepAndRetry( box.Options.RetrySeconds );
                        return;
                    }

                    for ( int i = 1; i <= pop3.MessageCount; i++ )
                    {
                        try
                        {
                            string message = pop3.GetMessage( i );
                            this.Messages[ i - 1 ] = SimpleMailMessage.Parse( message );
                        }
                        finally
                        {
                            pop3.DeleteMessage( i );
                        }

                    }

                }
                catch ( Exception e )
                {
                    //This part's very important. Since we're running on a ThreadPool thread right now, any exceptions
                    //thrown on this thread will be swallowed by the ThreadPool. If an exception happens, we need to
                    //somehow marshal it back to the thread that initiated the async operation and rethrow it there.
                    //Forutnately, the AsyncResult base class lets us do that. We'll catch the exception here and
                    //pass it to Complete(). When the originating thread calls AsyncResult.End() on us, the AsyncResult base
                    //class will rethrow the exception on the right thread so it can be handled by the application.

                    bCaughtException = true;
                    base.Complete( false, e );
                }
                finally
                {
                    if ( pop3 != null )
                        pop3.Close( true );
                }

                if ( !bCaughtException )
                    base.Complete( false );
            }
Ejemplo n.º 27
0
            internal int Pop3Check()
            {
                try {
                    var pop3Settings = new Pop3Settings();
                    var obj = new Pop3();
                    obj.Connect(pop3Settings.Host, pop3Settings.Username, pop3Settings.Password, pop3Settings.Port);
                    string KeyWord = Helpers.Xml.AppConfigQuery("jaNET/System/Comm/MailKeyword").Item(0).InnerText;

                    foreach (Pop3Message msg in obj.List()) {
                        Pop3Message msg2 = obj.Retrieve(msg);
                        /*Console.WriteLine("Message {0}: {1}",
                            msg2.number, msg2.message);*/
                        if (msg2.Message.Contains("<" + KeyWord + ">")) {
                            //If a command found to mail subject
                            Match Command = Regex.Match(msg2.Message.Replace("\r\n", " "), @"(<" + KeyWord + ">)(.*?)(?=</" + KeyWord + ">)");
                            Command.ToString().ToLower().Replace("<" + KeyWord + ">", string.Empty).Parse();
                            obj.Delete(msg2);
                        }
                        else {
                            //For Future Use
                            /*Match From = Regex.Match(msg2.message, @"(?<=From: )(.*?)(?= <)");
                            Match Subject = Regex.Match(msg2.message, @"(?<=Subject: )(.*?)(?=\\r\\nDate: )"); //(?<=Subject:</B> )(.*?)(?=</)");
                            MailList.Add("From " + From.ToString() + ", Subject " + Subject.ToString());*/
                            //From pattern (?<=From: \\\")(.*?)(?=\\\")
                            //Subject pattern (?<=Subject: )(.*?)(?=\\r)
                        }
                    }
                    obj.Disconnect();
                    return obj.List().Count;
                }
                catch {
                    return 0;
                }
            }
Ejemplo n.º 28
0
        /// <summary>
        /// Mail-To-Weblog runs in background thread and this is the thread function.
        /// </summary>
        public void Run()
        {
            IBlogDataService    dataService    = null;
            ILoggingDataService loggingService = null;

            SiteConfig siteConfig = SiteConfig.GetSiteConfig(configPath);

            loggingService = LoggingDataServiceFactory.GetService(logPath);
            dataService    = BlogDataServiceFactory.GetService(contentPath, loggingService);


            ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, "MailToWeblog thread spinning up");

            loggingService.AddEvent(new EventDataItem(EventCodes.Pop3ServiceStart, "", ""));

            do
            {
                try
                {
                    // reload on every cycle to get the current settings
                    siteConfig     = SiteConfig.GetSiteConfig(configPath);
                    loggingService = LoggingDataServiceFactory.GetService(logPath);
                    dataService    = BlogDataServiceFactory.GetService(contentPath, loggingService);


                    if (siteConfig.EnablePop3 &&
                        siteConfig.Pop3Server != null && siteConfig.Pop3Server.Length > 0 &&
                        siteConfig.Pop3Username != null && siteConfig.Pop3Username.Length > 0)
                    {
                        Pop3 pop3 = new Pop3();


                        try
                        {
                            pop3.host     = siteConfig.Pop3Server;
                            pop3.userName = siteConfig.Pop3Username;
                            pop3.password = siteConfig.Pop3Password;

                            pop3.Connect();
                            pop3.Login();
                            pop3.GetAccountStat();

                            for (int j = pop3.messageCount; j >= 1; j--)
                            {
                                Pop3Message message = pop3.GetMessage(j);

                                string messageFrom;
                                // [email protected] 1-MAR-04
                                // only delete those messages that are processed
                                bool messageWasProcessed = false;

                                // E-Mail addresses look usually like this:
                                // My Name <*****@*****.**> or simply
                                // [email protected]. This block handles
                                // both variants.
                                Regex getEmail   = new Regex(".*\\<(?<email>.*?)\\>.*");
                                Match matchEmail = getEmail.Match(message.from);
                                if (matchEmail.Success)
                                {
                                    messageFrom = matchEmail.Groups["email"].Value;
                                }
                                else
                                {
                                    messageFrom = message.from;
                                }

                                // Only if the subject of the message is prefixed (case-sensitive) with
                                // the configured subject prefix, we accept the message
                                if (message.subject.StartsWith(siteConfig.Pop3SubjectPrefix))
                                {
                                    Entry entry = new Entry();
                                    entry.Initialize();
                                    entry.Title      = message.subject.Substring(siteConfig.Pop3SubjectPrefix.Length);
                                    entry.Categories = "";
                                    entry.Content    = "";
                                    entry.Author     = messageFrom;                                 //store the email, what we have for now...

                                    // Grab the categories. Categories are defined in square brackets
                                    // in the subject line.
                                    Regex categoriesRegex = new Regex("(?<exp>\\[(?<cat>.*?)\\])");
                                    foreach (Match match in categoriesRegex.Matches(entry.Title))
                                    {
                                        entry.Title       = entry.Title.Replace(match.Groups["exp"].Value, "");
                                        entry.Categories += match.Groups["cat"].Value + ";";
                                    }
                                    entry.Title = entry.Title.Trim();

                                    string   categories = "";
                                    string[] splitted   = entry.Categories.Split(';');
                                    for (int i = 0; i < splitted.Length; i++)
                                    {
                                        categories += splitted[i].Trim() + ";";
                                    }
                                    entry.Categories = categories.TrimEnd(';');


                                    entry.CreatedUtc = RFC2822Date.Parse(message.date);

                                    #region PLain Text
                                    // plain text?
                                    if (message.contentType.StartsWith("text/plain"))
                                    {
                                        entry.Content += message.body;
                                    }
                                    #endregion

                                    #region Just HTML
                                    // Luke Latimer 16-FEB-2004 ([email protected])
                                    // HTML only emails were not appearing
                                    else if (message.contentType.StartsWith("text/html"))
                                    {
                                        string messageText = "";

                                        // Note the email may still be encoded
                                        //messageText = QuotedCoding.DecodeOne(message.charset, "Q", message.body);
                                        messageText = message.body;

                                        // Strip the <body> out of the message (using code from below)
                                        Regex bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                        Match match         = bodyExtractor.Match(messageText);
                                        if (match != null && match.Success && match.Groups["content"] != null)
                                        {
                                            entry.Content += match.Groups["content"].Value;
                                        }
                                        else
                                        {
                                            entry.Content += messageText;
                                        }
                                    }
                                    #endregion

                                    // HTML/Text with attachments ?
                                    else if (
                                        message.contentType.StartsWith("multipart/alternative") ||
                                        message.contentType.StartsWith("multipart/related") ||
                                        message.contentType.StartsWith("multipart/mixed"))
                                    {
                                        Hashtable embeddedFiles = new Hashtable();
                                        ArrayList attachedFiles = new ArrayList();

                                        foreach (Attachment attachment in message.attachments)
                                        {
                                            // just plain text?
                                            if (attachment.contentType.StartsWith("text/plain"))
                                            {
                                                entry.Content += StringOperations.GetString(attachment.data);
                                            }

                                            // Luke Latimer 16-FEB-2004 ([email protected])
                                            // Allow for html-only attachments
                                            else if (attachment.contentType.StartsWith("text/html"))
                                            {
                                                // Strip the <body> out of the message (using code from below)
                                                Regex  bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                                string htmlString    = StringOperations.GetString(attachment.data);
                                                Match  match         = bodyExtractor.Match(htmlString);

                                                //NOTE: We will BLOW AWAY any previous content in this case.
                                                // This is because most mail clients like Outlook include
                                                // plain, then HTML. We will grab plain, then blow it away if
                                                // HTML is included later.
                                                if (match != null && match.Success && match.Groups["content"] != null)
                                                {
                                                    entry.Content = match.Groups["content"].Value;
                                                }
                                                else
                                                {
                                                    entry.Content = htmlString;
                                                }
                                            }

                                            // or alternative text ?
                                            else if (attachment.contentType.StartsWith("multipart/alternative"))
                                            {
                                                bool   contentSet  = false;
                                                string textContent = null;
                                                foreach (Attachment inner_attachment in attachment.attachments)
                                                {
                                                    // we prefer HTML
                                                    if (inner_attachment.contentType.StartsWith("text/plain"))
                                                    {
                                                        textContent = StringOperations.GetString(inner_attachment.data);
                                                    }
                                                    else if (inner_attachment.contentType.StartsWith("text/html"))
                                                    {
                                                        Regex  bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                                        string htmlString    = StringOperations.GetString(inner_attachment.data);
                                                        Match  match         = bodyExtractor.Match(htmlString);
                                                        if (match != null && match.Success && match.Groups["content"] != null)
                                                        {
                                                            entry.Content += match.Groups["content"].Value;
                                                        }
                                                        else
                                                        {
                                                            entry.Content += htmlString;
                                                        }
                                                        contentSet = true;
                                                    }
                                                }
                                                if (!contentSet)
                                                {
                                                    entry.Content += textContent;
                                                }
                                            }
                                            // or text with embeddedFiles (in a mixed message only)
                                            else if ((message.contentType.StartsWith("multipart/mixed") || message.contentType.StartsWith("multipart/alternative")) &&
                                                     attachment.contentType.StartsWith("multipart/related"))
                                            {
                                                foreach (Attachment inner_attachment in attachment.attachments)
                                                {
                                                    // just plain text?
                                                    if (inner_attachment.contentType.StartsWith("text/plain"))
                                                    {
                                                        entry.Content += StringOperations.GetString(inner_attachment.data);
                                                    }

                                                    else if (inner_attachment.contentType.StartsWith("text/html"))
                                                    {
                                                        Regex  bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                                        string htmlString    = StringOperations.GetString(inner_attachment.data);
                                                        Match  match         = bodyExtractor.Match(htmlString);
                                                        if (match != null && match.Success && match.Groups["content"] != null)
                                                        {
                                                            entry.Content += match.Groups["content"].Value;
                                                        }
                                                        else
                                                        {
                                                            entry.Content += htmlString;
                                                        }
                                                    }

                                                    // or alternative text ?
                                                    else if (inner_attachment.contentType.StartsWith("multipart/alternative"))
                                                    {
                                                        bool   contentSet  = false;
                                                        string textContent = null;
                                                        foreach (Attachment inner_inner_attachment in inner_attachment.attachments)
                                                        {
                                                            // we prefer HTML
                                                            if (inner_inner_attachment.contentType.StartsWith("text/plain"))
                                                            {
                                                                textContent = StringOperations.GetString(inner_inner_attachment.data);
                                                            }
                                                            else if (inner_inner_attachment.contentType.StartsWith("text/html"))
                                                            {
                                                                Regex  bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                                                string htmlString    = StringOperations.GetString(inner_inner_attachment.data);
                                                                Match  match         = bodyExtractor.Match(htmlString);
                                                                if (match != null && match.Success && match.Groups["content"] != null)
                                                                {
                                                                    entry.Content += match.Groups["content"].Value;
                                                                }
                                                                else
                                                                {
                                                                    entry.Content += htmlString;
                                                                }
                                                                contentSet = true;
                                                            }
                                                        }
                                                        if (!contentSet)
                                                        {
                                                            entry.Content += textContent;
                                                        }
                                                    }
                                                    // any other inner_attachment
                                                    else if (inner_attachment.data != null &&
                                                             inner_attachment.fileName != null &&
                                                             inner_attachment.fileName.Length > 0)
                                                    {
                                                        if (inner_attachment.contentID.Length > 0)
                                                        {
                                                            embeddedFiles.Add(inner_attachment.contentID, StoreAttachment(inner_attachment, binariesPath));
                                                        }
                                                        else
                                                        {
                                                            attachedFiles.Add(StoreAttachment(inner_attachment, binariesPath));
                                                        }
                                                    }
                                                }
                                            }
                                            // any other attachment
                                            else if (attachment.data != null &&
                                                     attachment.fileName != null &&
                                                     attachment.fileName.Length > 0)
                                            {
                                                if (attachment.contentID.Length > 0 && message.contentType.StartsWith("multipart/related"))
                                                {
                                                    embeddedFiles.Add(attachment.contentID, StoreAttachment(attachment, binariesPath));
                                                }
                                                else
                                                {
                                                    attachedFiles.Add(StoreAttachment(attachment, binariesPath));
                                                }
                                            }
                                        }


                                        // check for orphaned embeddings
                                        string[] embeddedKeys = new string[embeddedFiles.Keys.Count];
                                        embeddedFiles.Keys.CopyTo(embeddedKeys, 0);
                                        foreach (string key in embeddedKeys)
                                        {
                                            if (entry.Content.IndexOf("cid:" + key.Trim('<', '>')) == -1)
                                            {
                                                object file = embeddedFiles[key];
                                                embeddedFiles.Remove(key);
                                                attachedFiles.Add(file);
                                            }
                                        }


                                        // now fix up the URIs

                                        if (siteConfig.Pop3InlineAttachedPictures)
                                        {
                                            foreach (string fileName in attachedFiles)
                                            {
                                                string fileNameU = fileName.ToUpper();
                                                if (fileNameU.EndsWith(".JPG") || fileNameU.EndsWith(".JPEG") ||
                                                    fileNameU.EndsWith(".GIF") || fileNameU.EndsWith(".PNG") ||
                                                    fileNameU.EndsWith(".BMP"))
                                                {
                                                    bool scalingSucceeded = false;

                                                    if (siteConfig.Pop3InlinedAttachedPicturesThumbHeight > 0)
                                                    {
                                                        try
                                                        {
                                                            string absoluteFileName  = Path.Combine(binariesPath, fileName);
                                                            string thumbBaseFileName = Path.GetFileNameWithoutExtension(fileName) + "-thumb.dasblog.JPG";
                                                            string thumbFileName     = Path.Combine(binariesPath, thumbBaseFileName);
                                                            Bitmap sourceBmp         = new Bitmap(absoluteFileName);
                                                            if (sourceBmp.Height > siteConfig.Pop3InlinedAttachedPicturesThumbHeight)
                                                            {
                                                                Bitmap targetBmp = new Bitmap(sourceBmp, new Size(
                                                                                                  Convert.ToInt32(Math.Round((((double)sourceBmp.Width) * (((double)siteConfig.Pop3InlinedAttachedPicturesThumbHeight) / ((double)sourceBmp.Height))), 0)),
                                                                                                  siteConfig.Pop3InlinedAttachedPicturesThumbHeight));

                                                                ImageCodecInfo    codecInfo     = GetEncoderInfo("image/jpeg");
                                                                Encoder           encoder       = Encoder.Quality;
                                                                EncoderParameters encoderParams = new EncoderParameters(1);
                                                                long             compression    = 75;
                                                                EncoderParameter encoderParam   = new EncoderParameter(encoder, compression);
                                                                encoderParams.Param[0] = encoderParam;
                                                                targetBmp.Save(thumbFileName, codecInfo, encoderParams);

                                                                string absoluteUri      = new Uri(binariesBaseUri, fileName).AbsoluteUri;
                                                                string absoluteThumbUri = new Uri(binariesBaseUri, thumbBaseFileName).AbsoluteUri;
                                                                entry.Content   += String.Format("<div class=\"inlinedMailPictureBox\"><a href=\"{0}\"><img border=\"0\" class=\"inlinedMailPicture\" src=\"{2}\"></a><br /><a class=\"inlinedMailPictureLink\" href=\"{0}\">{1}</a></div>", absoluteUri, fileName, absoluteThumbUri);
                                                                scalingSucceeded = true;
                                                            }
                                                        }
                                                        catch
                                                        {
                                                        }
                                                    }
                                                    if (!scalingSucceeded)
                                                    {
                                                        string absoluteUri = new Uri(binariesBaseUri, fileName).AbsoluteUri;
                                                        entry.Content += String.Format("<div class=\"inlinedMailPictureBox\"><img class=\"inlinedMailPicture\" src=\"{0}\"><br /><a class=\"inlinedMailPictureLink\" href=\"{0}\">{1}</a></div>", absoluteUri, fileName);
                                                    }
                                                }
                                            }
                                        }

                                        if (attachedFiles.Count > 0)
                                        {
                                            entry.Content += "<p>";
                                        }

                                        foreach (string fileName in attachedFiles)
                                        {
                                            string fileNameU = fileName.ToUpper();
                                            if (!siteConfig.Pop3InlineAttachedPictures ||
                                                (!fileNameU.EndsWith(".JPG") && !fileNameU.EndsWith(".JPEG") &&
                                                 !fileNameU.EndsWith(".GIF") && !fileNameU.EndsWith(".PNG") &&
                                                 !fileNameU.EndsWith(".BMP")))
                                            {
                                                string absoluteUri = new Uri(binariesBaseUri, fileName).AbsoluteUri;
                                                entry.Content += String.Format("Download: <a href=\"{0}\">{1}</a><br />", absoluteUri, fileName);
                                            }
                                        }
                                        if (attachedFiles.Count > 0)
                                        {
                                            entry.Content += "</p>";
                                        }

                                        foreach (string key in embeddedFiles.Keys)
                                        {
                                            entry.Content = entry.Content.Replace("cid:" + key.Trim('<', '>'), new Uri(binariesBaseUri, (string)embeddedFiles[key]).AbsoluteUri);
                                        }
                                    }

                                    loggingService.AddEvent(
                                        new EventDataItem(
                                            EventCodes.Pop3EntryReceived, entry.Title,
                                            SiteUtilities.GetPermaLinkUrl(siteConfig, entry.EntryId), messageFrom));

                                    SiteUtilities.SaveEntry(entry, siteConfig, loggingService, dataService);

                                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info,
                                                     String.Format("Message stored. From: {0}, Title: {1} as entry {2}",
                                                                   messageFrom, entry.Title, entry.EntryId));

                                    // give the XSS upstreamer a hint that things have changed
//                                    XSSUpstreamer.TriggerUpstreaming();

                                    // [email protected] (01-MAR-04)
                                    messageWasProcessed = true;
                                }
                                else
                                {
                                    // [email protected] (01-MAR-04)
                                    // logging every ignored email is apt
                                    // to fill up the event page very quickly
                                    // especially if only processed emails are
                                    // being deleted
                                    if (siteConfig.Pop3LogIgnoredEmails)
                                    {
                                        loggingService.AddEvent(
                                            new EventDataItem(
                                                EventCodes.Pop3EntryIgnored, message.subject,
                                                null, messageFrom));
                                    }
                                }
                                // [email protected] (01-MAR-04)
                                if (siteConfig.Pop3DeleteAllMessages || messageWasProcessed)
                                {
                                    if (!messageWasProcessed)
                                    {
                                        loggingService.AddEvent(
                                            new EventDataItem(
                                                EventCodes.Pop3EntryDiscarded, message.subject,
                                                null, messageFrom));
                                    }
                                    pop3.DeleteMessage(j);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e);
                            loggingService.AddEvent(
                                new EventDataItem(
                                    EventCodes.Pop3ServerError, e.ToString().Replace("\n", "<br />"), null, null));
                        }
                        finally
                        {
                            pop3.Close();
                        }
                    }

                    Thread.Sleep(TimeSpan.FromSeconds(siteConfig.Pop3Interval));
                }
                catch (ThreadAbortException abortException)
                {
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, abortException);
                    loggingService.AddEvent(new EventDataItem(EventCodes.Pop3ServiceShutdown, "", ""));
                    break;
                }
                catch (Exception e)
                {
                    // if the siteConfig can't be read, stay running regardless
                    // default wait time is 4 minutes in that case
                    Thread.Sleep(TimeSpan.FromSeconds(240));
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e);
                }
            }while (true);
            ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, "MailToWeblog thread terminating");
            loggingService.AddEvent(new EventDataItem(EventCodes.Pop3ServiceShutdown, "", ""));
        }
Ejemplo n.º 29
0
        /// <summary>
        /// ReadMail reads the pop3 mailbox
        /// </summary>
        public void ReadMail()
        {
            Pop3 pop3 = new Pop3();

            try
            {
                try
                {
                    pop3.User = Pop3Username;
                    pop3.Password = Pop3Password;

                    pop3.Connect(Pop3Server);

                    if (pop3.HasTimeStamp == true)
                        pop3.Login();//APOPLogin();
                    else
                        pop3.Login();

                    pop3.GetAccountStat();

                    int j = 1;

                    bool messageWasProcessed = false;

                    // Read each message to find out the recipient. This is for the project.
                    for (; j <= pop3.MessageCount; j++)
                    {
                        SimpleMailMessage message = SimpleMailMessage.Parse(pop3.GetMessage(j));

                        string messageFrom = "";

                        if (message.From.Count > 0)
                        {
                            MailBox from = message.From[0];
                            messageFrom = from.Address;
                        }

                        // E-Mail addresses look usually like this:
                        // My Name <*****@*****.**> or simply
                        // [email protected]. This block handles
                        // both variants.

                        // Need to check the TO, CC and BCC message fields for the bugnet email address
                        List<MailBox[]> recipients = new List<MailBox[]>();
                        recipients.Add((MailBox[])message.To.ToArray());
                        recipients.Add((MailBox[])message.Cc.ToArray());
                        recipients.Add((MailBox[])message.Bcc.ToArray());

                        foreach (MailBox[] toAr in recipients)
                        {
                            foreach (MailBox to in toAr)
                            {
                                string mailbox = to.Address;

                                ProjectMailbox pmbox = ProjectMailbox.GetProjectByMailbox(mailbox);

                                // Only if the mailbox appears in project's mailbox aliases
                                // we accept the message
                                if (pmbox != null)
                                {
                                    string binariesBaseUri;
                                    string binariesPath;

                                    string uploadPath = Project.GetProjectById(pmbox.ProjectId).UploadPath.TrimEnd('/');

                                    //string appPath = HostSetting.GetHostSetting("DefaultUrl");
                                    string appPath = HttpContext.Current.Request.PhysicalApplicationPath;
                                    if (!System.IO.Directory.Exists(appPath))
                                        throw new Exception("Upload path does not exist.");

                                    if (uploadPath.StartsWith("~"))
                                    {
                                        binariesPath = uploadPath.Replace("~", appPath.TrimEnd('\\'));

                                        if (!System.IO.Directory.Exists(appPath))
                                            throw new Exception("Upload path does not exist.");

                                        binariesBaseUri = uploadPath.Replace("~\\", Globals.DefaultUrl).Replace("\\", "/");
                                    }
                                    else
                                    {
                                        binariesPath = string.Concat(appPath, "Uploads\\");

                                        if (!System.IO.Directory.Exists(appPath))
                                            throw new Exception("Upload path does not exist.");

                                        binariesBaseUri = string.Concat(Globals.DefaultUrl, "Uploads/");
                                    }

                                    Entry entry = new Entry();

                                    entry.Title = message.Subject.Trim();
                                    entry.From = messageFrom;
                                    entry.ProjectMailbox = pmbox;

                                    entry.Date = message.Date;

                                    // plain text?
                                    if (message.HtmlDataString.Length == 0)
                                    {
                                        entry.Content.Append(message.TextDataString);
                                    }
                                    else
                                    {
                                        // Strip the <body> out of the message (using code from below)
                                        Regex bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                        Match match = bodyExtractor.Match(message.HtmlDataString);
                                        if (match != null && match.Success && match.Groups["content"] != null)
                                        {
                                            entry.Content.Append(match.Groups["content"].Value);
                                        }
                                        else
                                        {
                                            entry.Content.Append(message.HtmlDataString);
                                        }
                                    }

                                    Hashtable embeddedFiles = new Hashtable();
                                    ArrayList attachedFiles = new ArrayList();

                                    foreach (MailAttachment attachment in message.Attachments)
                                    {
                                        if (attachment.Data != null && attachment.FileName != null && attachment.FileName.Length > 0)
                                        {
                                            string fn = StoreAttachment(attachment, binariesPath);

                                            entry.MailAttachments.Add(attachment);
                                            entry.AttachmentFileNames.Add(fn);

                                            attachedFiles.Add(fn);
                                        }
                                    }

                                    // TODO Should use XSLT templates BGN-1591

                                    if (entry.MailAttachments.Count > 0)
                                    {
                                        entry.Content.Append("<p>");

                                        for (int i = 0; i < entry.MailAttachments.Count; i++)
                                        {
                                            MailAttachment attachment = (MailAttachment)entry.MailAttachments[i];

                                            string absoluteUri = string.Concat(binariesBaseUri, entry.AttachmentFileNames[i]);
                                            if (Pop3InlineAttachedPictures && attachment.ContentType.MimeType == MimeType.Image)
                                            {
                                                entry.Content.Append(String.Format("<br><img src=\"{0}\" />", absoluteUri));
                                            }
                                            else
                                            {
                                                entry.Content.Append(String.Format("<br><a href=\"{0}\" />{1}</a>", absoluteUri, attachment.FileName));
                                            }
                                        }

                                        entry.Content.Append("</p>");
                                    }

                                    messageWasProcessed = true;

                                    SaveEntry(entry);
                                }
                                else
                                {
                                    if (Log.IsWarnEnabled)
                                        Log.WarnFormat("Project Mailbox Not Found: {0}", message.To.ToString());
                                }
                            }
                        }
                        // [email protected] (01-MAR-04)
                        if (Pop3DeleteAllMessages || messageWasProcessed)
                            pop3.DeleteMessage(j);
                    }
                }
                catch (Exception ex)
                {
                    throw ProcessException(ex);
                }
            }
            catch (Exception ex)
            {
                throw ProcessException(ex);
            }
            finally
            {
                try
                {
                    pop3.Close();
                }
                catch
                {
                }
            }
        }
Ejemplo n.º 30
0
        static public string getmsgemail(string Steamlogin)
        {
            using (Pop3 pop3 = new Pop3())
            {
                if (Config.emailssl == true)
                {
                    try
                    {
                        pop3.ConnectSSL(Config.emailserver);
                    }
                    catch (Exception e)
                    {
                        errorlog(e.Message);
                        return(null);
                    }
                }
                else
                {
                    try
                    {
                        pop3.Connect(Config.emailserver);
                    }
                    catch (Exception e)
                    {
                        errorlog(e.Message);
                        return(null);
                    }
                }
                try
                {
                    pop3.UseBestLogin(Config.emaillogin, Config.emailpassword);
                }
                catch (Exception e)
                {
                    errorlog(e.Message);
                    return(null);
                }
                MailBuilder builder = new MailBuilder();
                foreach (string uid in pop3.GetAll())
                {
                    IMail email = builder.CreateFromEml(
                        pop3.GetMessageByUID(uid));
                    long unixTime   = (long)(email.Date.Value - new DateTime(1970, 1, 1)).TotalSeconds;
                    long epochTicks = new DateTime(1970, 1, 1).Ticks;
                    long unixfTime  = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond) + 10800;

                    long unixffTime = unixfTime - unixTime;
                    if (unixffTime <= 300)
                    {
                        string text1 = getBetween(email.Text, Steamlogin.ToLower() + ":", "This email was generated because");
                        if (text1 != null)
                        {
                            return(text1.Replace("\r\n", string.Empty)
                                   .Replace("\n", string.Empty)
                                   .Replace("\r", string.Empty));
                        }
                    }
                }
                errorlog("Не могу найти письмо!");
                return(null);
            }
        }
Ejemplo n.º 31
0
        protected override void Poll()
        {
            bool      emailDownloaded = false;
            Exception error           = null;

            try
            {
                PollBegin();

                using (Pop3 pop3 = new Pop3())
                {
                    switch (_sslType)
                    {
                    case SSLType.None:
                        pop3.Connect(_host, _port);
                        break;

                    case SSLType.SSL:
                        pop3.ConnectSSL(_host, _port);
                        break;

                    case SSLType.TLS:
                        pop3.Connect(_host, _port);
                        pop3.STLS();
                        break;
                    }

                    pop3.UseBestLogin(_username, _password);

                    List <string> serverUids = pop3.GetAll();

                    MessageStoreCollection localMessageStore = MessageStoreManager.LoadLocalMessageStore(_username, _host);

                    if (localMessageStore != null)
                    {
                        MessageStoreManager.RemoveMessagesNoLongerOnServer(ref localMessageStore, serverUids);

                        List <string> uidsToCheck = MessageStoreManager.GetMessagesToCheck(localMessageStore, serverUids);

                        foreach (string uid in uidsToCheck)
                        {
                            //string fileName;

                            byte[] eml   = pop3.GetMessageByUID(uid);
                            IMail  email = new MailBuilder().CreateFromEml(eml); //SpoolEmlViaDisk(pop3.GetMessageByUID(uid), out fileName);

                            MessageStoreMessage theMessage = new MessageStoreMessage(uid);

                            if (ProcessEmailAttachments(email) > 0)
                            {
                                emailDownloaded = true;

                                //Only populate the extra data for game emails
                                if (email.From.Count > 0)
                                {
                                    theMessage.From = email.From[0].Address;
                                }

                                theMessage.Subject = email.Subject;

                                if (email.Date.HasValue)
                                {
                                    theMessage.Date      = email.Date.Value.ToString();
                                    theMessage.DateTicks = email.Date.Value.Ticks.ToString();
                                }
                                //In case the email doesn't come down with a good date
                                if (string.IsNullOrEmpty(theMessage.Date))
                                {
                                    DateTime stamp = DateTime.Now;
                                    theMessage.Date      = stamp.ToString();
                                    theMessage.DateTicks = stamp.Ticks.ToString();
                                }

                                theMessage.FileName = GetAttachmentsString(email);
                            }

                            localMessageStore.Messages.Add(theMessage);

                            //ClearSpooledEml(fileName);
                        }
                    }
                    else
                    {
                        //New message store, add all currently on server
                        localMessageStore = new MessageStoreCollection(serverUids);
                    }

                    MessageStoreManager.SaveLocalMessageStore(_username, _host, localMessageStore);

                    localMessageStore.Dispose();
                    localMessageStore = null;

                    pop3.Close();
                }
            }
            catch (Exception ex)
            {
                error = ex;
                Trace.TraceError(ex.ToString());
                Trace.Flush();
            }
            finally
            {
                PollEnd(emailDownloaded, error);
            }
        }
Ejemplo n.º 32
0
        static void Main(string[] args)
        {
            string[] arg;
            int      flag = 0;

            arg = System.Environment.GetCommandLineArgs();
            string path = @"e:\!email-mikrotik\";

            for (int i = 0; i < arg.Length; i++)
            {
                if (arg[i] == "/dir")
                {
                    if (!String.IsNullOrEmpty(arg[i + 1]))
                    {
                        path = arg[i + 1];
                    }
                }
                if (arg[i] == "-debug")
                {
                    flag = 1;
                }

                if (arg[i] == "/?")
                {
                    Console.WriteLine("");
                    Console.WriteLine("Использование: mail2dirr.exe /dir \"папка для вложений\" [-debug] ");

                    return;
                }
            }

            //string path_base = @"e:\!email-mikrotik\";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            if (path.Substring(path.Length - 1) != @"\")
            {
                path += @"\";
            }
            using (Pop3 pop3 = new Pop3())
            {
                try
                {
                    pop3.Connect("pop.i.ua");       // or ConnectSSL for SSL
                    pop3.UseBestLogin("*****@*****.**", "dtnjxrfcbhtyb500");
                    foreach (string uid in pop3.GetAll())
                    {
                        IMail email = new MailBuilder()
                                      .CreateFromEml(pop3.GetMessageByUID(uid));
                        //бесплатная библиотека мусорит сабжект письма
                        string filenam;
                        filenam = @email.Text.Replace("/", "-");
                        filenam = email.Text.Replace("\r\n", "");
                        // email.Save(@"e:\1111qa");
                        foreach (MimeData mime in email.Attachments)
                        {
                            mime.Save(path + mime.SafeFileName);
                        }
                    }
                    //удаляем сообщения с сервера
                    foreach (string uid in pop3.GetAll())
                    {
                        pop3.DeleteMessageByUID(uid);
                    }
                    pop3.Close();
                }
                catch (Exception e) {
                    if (flag != 0)
                    {
                        MessageBox((IntPtr)0, e.ToString(), "mail_UDProgram_message", 0);
                    }
                    //path += "ok.ok"; if (!File.Exists(path)) File.Create(path);
                }
            }
            //ставим знак окончания приема писем
            path += "ok.ok"; if (!File.Exists(path))
            {
                File.Create(path);
            }
        }