Sending a list of mails with SmtpClient

Posted by Malcolm Frexner on Stack Overflow See other posts from Stack Overflow or by Malcolm Frexner
Published on 2010-04-21T15:45:35Z Indexed on 2010/04/21 15:53 UTC
Read the original article Hit count: 253

Filed under:
|
|

I use SendCompletedEventHandler of SmtpClient when sending a list of emails.

The SendCompletedEventHandler is only called when have already sent all emails in the list.

I expexted, that SendCompletedEventHandler is called one an email is send.

Is there something wrong in my code?

    public void SendAllNewsletters(List<string> recipients)
    {
        string mailText  = "My Tex";
        foreach(string recipient in recipients)
        {
            //if this loop takes 10min then the first call to
            //SendCompletedCallback is after 10min
            SendNewsletter(mailText,recipient);
        }
    }

    public bool SendNewsletter(string mailText , string emailaddress)
    {

            SmtpClient sc = new SmtpClient(_smtpServer, _smtpPort);
            System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(_smtpuser, _smtppassword);
            sc.Credentials = SMTPUserInfo;
            sc.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);

            MailMessage mm = null;
            mm = new MailMessage(mailText, emailaddress);
            mm.IsBodyHtml = true;
            mm.Priority = MailPriority.Normal;
            mm.Subject = "Something";
            mm.Body = "Something";
            mm.SubjectEncoding = Encoding.UTF8;
            mm.BodyEncoding = Encoding.UTF8;

            //Mail 
            string userState = emailaddress;
            sc.SendAsync(mm, userState);

            return true;
    }


    public void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
    {
        // Get the unique identifier for this asynchronous operation.
        String token = (string)e.UserState;
        if (e.Error != null)
        {
            _news.SetNewsletterEmailsisSent(e.UserState.ToString(), _newslettername, false, e.Error.Message); 
        }
        else
        {
            _news.SetNewsletterEmailsisSent(e.UserState.ToString(), _newslettername, true, string.Empty);
        }            
    }

© Stack Overflow or respective owner

Related posts about c#

Related posts about winforms