Exemplo n.º 1
0
        static void Main(string[] args)
        {
            string[] arRcpt = usercredentials.addEmailArray("[email protected] [email protected]");

            int nRcpt = arRcpt.Length;

            SmtpMail[]              arMail   = new SmtpMail[nRcpt];
            SmtpClient[]            arSmtp   = new SmtpClient[nRcpt];
            SmtpClientAsyncResult[] arResult = new SmtpClientAsyncResult[nRcpt];
            for (int i = 0; i < nRcpt; i++)
            {
                arMail[i] = new SmtpMail("TryIt");
                arSmtp[i] = new SmtpClient();
            }

            for (int i = 0; i < nRcpt; i++)
            {
                SmtpMail oMail = arMail[i];
                // Set sender email address
                oMail.From = "*****@*****.**";

                // Set recipient email address
                oMail.To = arRcpt[i];

                // Set email subject
                oMail.Subject = "mass email test from c#";

                // Set email body
                oMail.TextBody = "test from c#, this email is sent to " + arRcpt[i];
                // Your smtp server address
                SmtpServer oServer = new SmtpServer("smtp.gmail.com");

                oServer.Port = 587;

                // User and password for ESMTP authentication, if your server doesn't require
                // User authentication, please remove the following codes.
                oServer.User     = "******";
                oServer.Password = "******";

                // If your smtp server requires SSL connection, please add this line
                oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
                SmtpClient oSmtp = arSmtp[i];

                // Submit email to BeginSendMail method and return
                // to process another email
                arResult[i] = oSmtp.BeginSendMail(oServer, oMail, null, null);
                Console.WriteLine(String.Format("Start to send email to {0} ...",
                                                arRcpt[i]));
            }
            // All emails were sent by BeginSendMail Method
            // now get result by EndSendMail method
            int nSent = 0;

            while (nSent < nRcpt)
            {
                for (int i = 0; i < nRcpt; i++)
                {
                    // this email has been sent
                    if (arResult[i] == null)
                    {
                        continue;
                    }
                    // wait for specified email ...
                    if (!arResult[i].AsyncWaitHandle.WaitOne(10, false))
                    {
                        continue;
                    }
                    try
                    {
                        // this email is finished, using EndSendMail to get result
                        arSmtp[i].EndSendMail(arResult[i]);
                        Console.WriteLine(String.Format("Send email to {0} successfully",
                                                        arRcpt[i]));
                    }
                    catch (Exception ep)
                    {
                        Console.WriteLine(
                            String.Format("Failed to send email to {0} with error {1}: ",
                                          arRcpt[i], ep.Message));
                    }
                    // Set this email result to null, then it won't be processed again
                    arResult[i] = null;
                    nSent++;
                }
            }
        }
Exemplo n.º 2
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            if( textFrom.Text.Length == 0 )
            {
                MessageBox.Show( "Please input From, the format can be [email protected] or Tester<*****@*****.**>" );
                return;
            }

            int to_count = lstTo.Items.Count;
            if( to_count == 0 )
            {
                MessageBox.Show( "please add a recipient at least!" );
                return;
            }

            btnSend.Enabled = false;
            btnSimple.Enabled = false;
            btnAdd.Enabled = false;
            btnClear.Enabled = false;
            btnAddTo.Enabled = false;
            btnClearTo.Enabled = false;
            chkTestRecipients.Enabled =false;

            btnCancel.Enabled = true;

            m_bcancel = false;
            int maxInstances = 10;
            try
            {
                maxInstances = Int32.Parse(textThreads.Text);
            }
            catch( Exception ep )
            {

            }

            if( maxInstances < 1 )
                maxInstances = 1;

            int curInstances = 0;

            SmtpClient[] arSmtp = new SmtpClient[maxInstances];
            SmtpClientAsyncResult[] arResult = new SmtpClientAsyncResult[maxInstances];

            for( int i = 0; i < maxInstances; i++ )
            {
                arSmtp[i] = null;
            }

            int sent = 0;
            for( sent = 0; sent < to_count; sent++ )
            {
                lstTo.Items[sent].SubItems[2].Text = "Ready";
            }

            m_ntotal = to_count;
            m_nsent = 0;
            m_nsuccess = 0;
            m_nfailure = 0;
            status.Text = String.Format( "Total {0}, Finished {1}, Succeeded {2}, Failed {3}",
                m_ntotal, m_nsent, m_nsuccess, m_nfailure );

            sent = 0;
            while( sent < to_count && !m_bcancel)
            {
                if( curInstances >= maxInstances )
                {
                    if( _WaitInstances( ref arSmtp, ref arResult ))
                    {
                        curInstances--;
                    }
                    else
                    {
                        Application.DoEvents();
                        //System.Threading.Thread.Sleep( 10 );
                    }
                    continue;
                }

                curInstances++;
                _AddInstances( ref arSmtp, ref arResult, sent );
                sent++;
                Application.DoEvents();

            }

            //Wait all message sent.
            _WaitAllInstances( ref arSmtp,  ref arResult );

            if( m_bcancel )
            {
                for( ; sent < to_count; sent++ )
                {
                    lstTo.Items[sent].SubItems[2].Text = "Operation was cancelled";
                }
            }

            btnSend.Enabled = true;
            btnSimple.Enabled = true;
            btnAdd.Enabled = true;
            btnClear.Enabled = true;
            btnAddTo.Enabled = true;
            btnClearTo.Enabled = true;
            chkTestRecipients.Enabled = true;

            btnCancel.Enabled = false;
        }
Exemplo n.º 3
0
        bool _WaitInstances( ref SmtpClient[] arSmtp,
			ref SmtpClientAsyncResult[] arResult )
        {
            bool b = false;
            int count = arSmtp.Length;
            for( int i = 0; i < count; i++ )
            {
                Application.DoEvents();
                SmtpClient oSmtp = arSmtp[i];
                if( oSmtp == null )
                    continue;

                SmtpClientAsyncResult oResult = arResult[i];
                if( oResult.AsyncWaitHandle.WaitOne( 0, false ))
                {
                    //this message was finished, get the result by
                    //_UpdateResult
                    b = true;
                    //Set the object instanct to null.
                    _UpdateResult( ref oSmtp, ref oResult );
                    arSmtp[i] = null;
                    arResult[i] = null;
                    break;
                }

            }
            return b;
        }
Exemplo n.º 4
0
        void _WaitAllInstances( ref SmtpClient[] arSmtp,
			ref SmtpClientAsyncResult[] arResult )
        {
            bool bcontinue = false;
            do
            {
                bcontinue = false;
                int count = arSmtp.Length;
                for( int i = 0; i < count; i++ )
                {
                    Application.DoEvents();
                    SmtpClient oSmtp = arSmtp[i];
                    if( oSmtp == null )
                        continue;

                    // not all object finished.
                    bcontinue = true;
                    SmtpClientAsyncResult oResult = arResult[i];
                    if( oResult.AsyncWaitHandle.WaitOne( 0, false ))
                    {
                        //this message was finished, get the result by
                        //_UpdateResult
                        _UpdateResult( ref oSmtp, ref oResult );
                        //Set the object instanct to null.
                        arSmtp[i] = null;
                        arResult[i] = null;
                    }
                }

            }while( bcontinue );
        }
Exemplo n.º 5
0
        void _UpdateResult( ref SmtpClient oSmtp,
			ref SmtpClientAsyncResult oResult )
        {
            //Get the item index from Tag property
            int index = (int)oSmtp.Tag;
            try
            {
                if( !chkTestRecipients.Checked )
                {
                    oSmtp.EndSendMail( oResult );
                    _CrossThreadSetItemText( "Completed", index );
                }
                else
                {
                    oSmtp.EndTestRecipients( oResult );
                    _CrossThreadSetItemText( "PASS", index );

                }
                m_nsuccess++;
            }
            catch( SmtpTerminatedException exp )
            {
                string err = exp.Message;
                _CrossThreadSetItemText( err, index );
                m_nfailure++;
            }
            catch( SmtpServerException exp )
            {
                string err = String.Format( "Exception: Server Respond: {0}", exp.ErrorMessage );
                 _CrossThreadSetItemText( err, index );
                m_nfailure++;
            }
            catch( System.Net.Sockets.SocketException exp )
            {
                string err = String.Format( "Exception: Networking Error: {0} {1}", exp.ErrorCode, exp.Message );
                _CrossThreadSetItemText( err, index );
                m_nfailure++;
            }
            catch( System.ComponentModel.Win32Exception exp )
            {
                string err = String.Format( "Exception: System Error: {0} {1}", exp.ErrorCode, exp.Message );
                 _CrossThreadSetItemText( err, index );
                m_nfailure++;
            }
            catch( System.Exception exp )
            {
                string err = String.Format( "Exception: Common: {0}", exp.Message );
                 _CrossThreadSetItemText(err, index );
                m_nfailure++;
            }

            m_nsent++;
            status.Text = String.Format( "Total {0}, Finished {1}, Succeeded {2}, Failed {3}",
                m_ntotal,
                m_nsent,
                m_nsuccess,
                m_nfailure);
        }
Exemplo n.º 6
0
        void _AddInstances( ref SmtpClient[] arSmtp,
			ref SmtpClientAsyncResult[] arResult,
			int index )
        {
            int count = arSmtp.Length;
            for( int i = 0; i < count; i++ )
            {
                SmtpClient oSmtp = arSmtp[i];
                if( oSmtp == null )
                {
                    //idle instance found.

                    oSmtp = new SmtpClient();
                    //store current list item index to object instance
                    //and we can retrieve it in EASendMail events.
                    oSmtp.Tag = index;

                    //For evaluation usage, please use "TryIt" as the license code, otherwise the
                    //"invalid license code" exception will be thrown. However, the object will expire in 1-2 months, then
                    //"trial version expired" exception will be thrown.

                    //For licensed uasage, please use your license code instead of "TryIt", then the object
                    //will never expire
                    SmtpMail oMail = new SmtpMail("TryIt");

                    //If you want to specify a reply address
                    //oMail.Headers.ReplaceHeader( "Reply-To: <reply@mydomain>" );

                    //From is a MailAddress object, in c#, it supports implicit converting from string.
                    //The syntax is like this: "*****@*****.**" or "Tester<*****@*****.**>"

                    //The example code without implicit converting
                    // oMail.From = new MailAddress( "Tester", "*****@*****.**" )
                    // oMail.From = new MailAddress( "Tester<*****@*****.**>" )
                    // oMail.From = new MailAddress( "*****@*****.**" )
                    oMail.From = textFrom.Text;

                    string name, address;
                    ListViewItem item = lstTo.Items[index];
                    name = item.Text;
                    address = item.SubItems[1].Text;

                    oMail.To.Add( new MailAddress( name, address ));

                    oMail.Subject = textSubject.Text;
                    oMail.Charset = m_arCharset[lstCharset.SelectedIndex,1];

                    //replace keywords in body text.
                    string body = textBody.Text;
                    body = body.Replace( "[$subject]", oMail.Subject );
                    body = body.Replace( "[$from]", oMail.From.ToString());
                    body = body.Replace( "[$name]", name );
                    body = body.Replace( "[$address]", address );

                    oMail.TextBody = body;

                    int y = m_arAttachment.Count;
                    for( int x = 0; x < y; x++ )
                    {
                        //add attachment
                        oMail.AddAttachment( m_arAttachment[x] as string );
                    }

                    SmtpServer oServer = new SmtpServer( textServer.Text );
                    oServer.Protocol = (ServerProtocol)lstProtocol.SelectedIndex;
                    if( oServer.Server.Length != 0 )
                    {
                        if( chkAuth.Checked )
                        {
                            oServer.User = textUser.Text;
                            oServer.Password = textPassword.Text;
                        }

                        if( chkSSL.Checked )
                            oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                    }
                    else
                    {
                        //To send email to the recipient directly(simulating the smtp server),
                        //please add a Received header,
                        //otherwise, many anti-spam filter will make it as junk email.
                        System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US");
                        string gmtdate = System.DateTime.Now.ToString("ddd, dd MMM yyyy HH:mm:ss zzz", cur);
                        gmtdate.Remove( gmtdate.Length - 3, 1 );
                        string recvheader = String.Format( "from {0} ([127.0.0.1]) by {0} ([127.0.0.1]) with SMTPSVC;\r\n\t {1}",
                            oServer.HeloDomain,
                            gmtdate );

                        oMail.Headers.Insert( 0, new HeaderItem( "Received", recvheader ));
                    }

                     _CrossThreadSetItemText( "Connecting ...", index );

                    //Catching the following events is not necessary,
                    //just make the application more user friendly.
                    //If you use the object in asp.net/windows service or non-gui application,
                    //You need not to catch the following events.
                    //To learn more detail, please refer to the code in EASendMail EventHandler region
                    oSmtp.OnIdle += new SmtpClient.OnIdleEventHandler( OnIdle );
                    oSmtp.OnAuthorized += new SmtpClient.OnAuthorizedEventHandler( OnAuthorized );
                    oSmtp.OnConnected += new SmtpClient.OnConnectedEventHandler( OnConnected );
                    oSmtp.OnSecuring += new SmtpClient.OnSecuringEventHandler( OnSecuring );
                    oSmtp.OnSendingDataStream += new SmtpClient.OnSendingDataStreamEventHandler( OnSendingDataStream );

                    SmtpClientAsyncResult oResult = null;
                    if( !chkTestRecipients.Checked )
                    {
                        oResult = oSmtp.BeginSendMail(
                            oServer, oMail,  null, null );
                    }
                    else
                    {
                        //Just test the email address without sending email data.
                        oResult = oSmtp.BeginTestRecipients(
                            null, oMail, null, null );
                    }

                    //Add the object instance to the array.
                    arSmtp[i] = oSmtp;
                    arResult[i] = oResult;
                    break;
                }
            }
        }