Search The ForumSearch   RegisterRegister  LoginLogin

MailBee.NET Objects

 AfterLogic Forum : MailBee.NET Objects
Subject Topic: Work with multi thread Post ReplyPost New Topic
Author
Message << Prev Topic | Next Topic >>
kobita
Newbie
Newbie
Avatar

Joined: 12 September 2011
Location: Israel
Online Status: Offline
Posts: 2
Posted: 12 September 2011 at 5:05am | IP Logged Quote kobita

Hi all,
I am beginner developer in c#,
i try to build windows service which connect to my client email and download all the messages, after that ther service need to check if there are new emails in my Inbox folder.
if yes
check if it from specific address and send it to other email address.

how do i built it in a multi thread ?

this is my code


class Program
    {
        private static Imap imp = new Imap();

        private static Smtp forward = new Smtp();

        private static int countStop = 0;

        private static UidCollection uids = getEmailsUniqId();

        private static int count = (uids.Count);

        private static MailMessageCollection msgCollection = new MailMessageCollection();

        static System.Timers.Timer timer = new System.Timers.Timer();

        private static Thread t1 = new Thread(downloadMessages);

        private static void connectToServer()
        {
            Imap.LicenseKey = "license key here";
            if (!imp.IsConnected)
            {
               imp.Connect("imap.gmail.com");
               imp.Login("userName", "Password");
               imp.SelectFolder("Inbox");
            }
            
            Console.WriteLine("days Left :::" + imp.TrialDaysLeft);
            Console.WriteLine("Flag " + imp.Flags);
            Console.WriteLine("Connected? " + imp.IsConnected);
            Console.WriteLine(imp.Log.Enabled = true);
            Console.WriteLine(imp.Log.Filename = "\\Domains\\EmailService\\GetSendEmail\\Log\\imapLog.txt");
            
        }

        private static string changeFileName(string msgFileName)
        {
            if (msgFileName.Length == 0 || msgFileName == null)
            {
               msgFileName = "";
            }
            string fileName = msgFileName;
            char[] delimiter = { '.' };
            string[] xName = fileName.Split(delimiter);

            string newFileName;

            string lengthName = "";

            for (int y = 1; y < xName.Length; y++)
            {
               lengthName += xName[y];
            }
            newFileName = xName[0] + "__2010__." + lengthName;
            return newFileName;
        }

        private static string getNameFromEmail(string msgFrom)
        {
            char[] at = { '@' };
            string[] userName = msgFrom.Split(at);
            return userName[0];
        }

        private static string getDomainFromEmail(string msgFrom)
        {
            char[] at = { '@' };
            string[] domainName = msgFrom.Split(at);
            return domainName[1];
        }

        private static UidCollection getEmailsUniqId()
        {
            connectToServer();
            UidCollection uids = (UidCollection)imp.Search(true, "UNSEEN", null);
            return uids;
        }

        private static void downloadMessages()
        {
            Console.WriteLine("Total " + uids.Count + " Emails Found");
            Console.WriteLine("ThreadID:::::::: " + t1.ManagedThreadId);

            

            foreach (var item in uids)
            {
               var db = new EmailUsersModelContainer();
               var user = new EmailUsers();

               while (count > 0 && countStop < 10)
               {
                    countStop += 1;
                    count -=1;

                    imp.Timeout = 60000;
                    msgCollection = imp.DownloadEntireMessages(uids[count].ToString(), true);

                    var newFileName = "";

                    foreach (MailMessage newMsg in msgCollection)
                    {
                        Console.WriteLine("Message #" + newMsg.IndexOnServer.ToString() + " has " + newMsg.Attachments.Count + " attachment(s)");

                        foreach (Attachment file in newMsg.Attachments)
                        {
                            if (!file.IsInline)
                            {
                                user = new EmailUsers();
                                 us er.Use r = getNameFromEmail(newMsg.From.Email.ToString());
                                 us er.Ema ilFrom = newMsg.From.ToString();
                                 us er.Ema ilTo = newMsg.To.ToString();
                                 ne wFileN ame = changeFileName(file.Filename);
                                 im p.Log. WriteLine("" + newFileName);
                                 fi le.Sav e("\\Domains\\EmailService\\GetSendEmail\\files\\" + newFileName, true);
                            }
                        }

                        if (newMsg.From.Email.Contains("seo-now.co.il"))
                        {
                            switch (newMsg.HasAttachments)
                            {
                                case true:
                                 us er.Dat eTime = DateTime.Now;
                                 us er.New UserID = getNameFromEmail(newMsg.From.Email.ToString()) + user.Id;
                                 us er.Use rDomain = getDomainFromEmail(newMsg.From.Email.ToString());
                                 us er.JTo Add = "J";

                                 im p.Log. WriteLine("" + user.DateTime + "," + user.NewUserID + "," + user.UserDomain + "," + user.JToAdd);

                                 fo rward. SmtpServers.Add("smtp.gmail.com", "UserName", "Password");
                                 fo rward. Message.To.AsString = "mafil-idc-main@printspots.com";
                                 fo rward. Message.From.AsString = newMsg.From.Email;
                                 fo rward. ReplyTo.AsString = newMsg.From.Email;
                                 fo rward. Message.Subject = newMsg.From.Email;

                                foreach (Attachment file in newMsg.Attachments)
                                {
                                 &n bsp;&n bsp;  if (!file.IsInline)
                                 &n bsp;&n bsp;  {
                                          ne wFileN ame = changeFileName(file.Filename);
                                 &n bsp;&n bsp;      forward.Message.Attachments.Add("\\Domains\\EmailService\\GetSendEmail\\files\\" + newFileName);
                                 &n bsp;&n bsp;  }
                                }

                                 db .Email UsersSet.AddObject(user);
                                 db .SaveC hanges();
                                 fo rward. Send();

                                 &n bsp;&n bsp;  break;
                                 de fault:
                            //Do Nothing
                                 &n bsp;&n bsp;  break;
                            }
                        }
                        else if (newMsg.From.Email.Contains("printspots.com"))
                        {
                            string txt = newMsg.BodyParts.Html.Text;
                            Regex emailRegex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",
                            RegexOptions.IgnoreCase);
                            //find items that matches with our pattern
                            MatchCollection emailMatches = emailRegex.Matches(txt);
                            StringBuilder sb = new StringBuilder();

                            foreach (Match emailMatch in emailMatches)
                            {
                                 sb .Appen dLine(emailMatch.Value);
                            }
                            //store to file
                            var emailToSend = sb.ToString();

                             forward.SmtpServers.Add("smtp.gm ail.com", "userName", "password");
                            forward.Message.To.AsString = emailToSend;
                            forward.Message.From.AsString = "user@gmail.com";
                            forward.ReplyTo.AsString = newMsg.From.Email;
                            forward.Message.Subject = "Your print job";
                            forward.Message.BodyHtmlText = newMsg.BodyHtmlText;
                            forward.Send();
                        }
                    }
               }

               if (countStop == 10 && imp.IsConnected)
               {
                    imp.Disconnect();
               }

               if (uids.Count == 0)
               {
                    Console.WriteLine("No new messages");
               }
            }
            Console.WriteLine("Finish");
        }

        public static void Main(string[] args)
        {
            Smtp.LicenseKey = "license key here";

            t1.Start();

            timer.Interval = 10000;
            timer.Enabled = true;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            callTimer();

            Thread.Sleep(3000);
            Console.Read();
        }

        static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            while (t1.ThreadState.ToString() != "Running")
            {
               imp = new Imap();
               uids = getEmailsUniqId();
               count = uids.Count;
               countStop = 0;
               msgCollection = new MailMessageCollection();
               t1 = new Thread(downloadMessages);
               t1.Start();
            }

        }

        static void callTimer()
        {
            timer.Start();
        }
    }

Back to Top View kobita's Profile Search for other posts by kobita
 
Alex
AfterLogic Support
AfterLogic Support
Avatar

Joined: 19 November 2003
Online Status: Offline
Posts: 2206
Posted: 12 September 2011 at 8:58am | IP Logged Quote Alex

Although it's not possible for us to inspect all your code, I can provide some general guidelines.

1. It's perfectly OK for MailBee.NET classes to be used multi-threaded provided that each instance runs in its own thread (i.e. you can't use the same instance in two threads simultaneously).

2. It's NOT OK at all for mail servers to support multi-threading. MailBee.NET has no problems with creating two connections with the same mail server (as stated before). But mail servers often say "get off!" when the client (single IP address) wants to make multiple connections. So, be prepared. I recommend to make simultaneous connections to different servers only (or, at least, only to the servers which are known to allow multiple concurrent connections from a single IP address).

3. If you're using logging into a file in your app and all your threads are writing into a single file, do this:

private static object syncObj = new object; // class member

then, every time you create Imap or Smtp object:
Code:

Imap imp = new Imap();
imp.Log.SyncRoot = syncObj;
imp.Log.Format = LogFormatOptions.AddContextInfo;


The same for Smtp. If you want IMAP and SMTP logs different, use different two different objects as SyncRoot (one for IMAP, another for SMTP).

Sync objects allow multiple concurrent threads properly access shared resource (log file). This is important only if all threads are writing into the same file. If each thread is using its own file, no syncing is needed.

AddContextInfo log formatting option is just for the ease of reading the log file. In case if multiple threads are writing into the same log, context info adds thread number, so it makes it easier to track each individual thread in the log file.

Regards,
Alex
Back to Top View Alex's Profile Search for other posts by Alex
 
kobita
Newbie
Newbie
Avatar

Joined: 12 September 2011
Location: Israel
Online Status: Offline
Posts: 2
Posted: 12 September 2011 at 12:58pm | IP Logged Quote kobita

Thank you very much it's working grate with 2 threads because of Gmail limit.

Back to Top View kobita's Profile Search for other posts by kobita
 

If you wish to post a reply to this topic you must first login
If you are not already registered you must first register

  Post ReplyPost New Topic
Printable version Printable version

Forum Jump

Powered by Web Wiz Forums version 7.9
Copyright ©2001-2004 Web Wiz Guide