简体   繁体   中英

smtp email sending issue in for loop c#

I want to send email multiple email addresses with the help of For loop but only first email will send properly but in second time i am getting "faild to send email " issue can any one please help me in same

below is my code

        DataSet dsAllocateUser = new DataSet();
        dsAllocateUser = ICA_Get_EmailDatafor_User(UserId, AssignedTo, BatchID, sConnectionString);
        for (int i = 0; i < dsAllocateUser.Tables[0].Rows.Count; i++)
        {

            string Body;
            MailMessage mailToSend = new MailMessage();
            System.Text.StringBuilder sb = new StringBuilder();
            string messagetext = Message;
            SmtpClient smtpMesg = new SmtpClient(ConfigurationSettings.AppSettings["SmtpServer"].ToString());
            mailToSend.From = new MailAddress(" abc.notifications@gebbs.com", " abc.notifications@gebbs.com");
            mailToSend.To.Add(new MailAddress(dsAllocateUser.Tables[0].Rows[i]["EMailID"].ToString()));

            mailToSend.IsBodyHtml = true;
            mailToSend.Body = sb.ToString();
            mailToSend.Subject = "Action Required";
            smtpMesg.UseDefaultCredentials = false;
            smtpMesg.Port = 25;
            smtpMesg.Host = "smtp.emailsrvr.com";
            smtpMesg.Credentials = new System.Net.NetworkCredential("abc.notifications@gebbs.com", "psaaword");
            smtpMesg.Send(mailToSend);
        }

This is how you should send multiple emails, make sure to use smtpMesg.Close() after sending each email.

private List<String> Get_Messages()
{
    List<String> list = new List<string>();
    list.Add("Hello");
    list.Add("Hello 2");

    return list;

}

private void SendEmail()
{

    foreach (String messages in Get_Messages())
    {
        //prepare email. 
        String subject = "test email message";

        String emailFrom = "emailFrom@email.com"
        MailMessage objeto_mail = new MailMessage();
        SmtpClient client = new SmtpClient();

        client.Port = 25;
        client.Host = "yourhost.com";
        client.UseDefaultCredentials = false;
        client.Credentials = new System.Net.NetworkCredential("username", "password");


        client.Timeout = 10000;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        objeto_mail.From = new MailAddress(emailFrom);

        objeto_mail.To.Add(new MailAddress("emailto@emailto.com"));

        objeto_mail.IsBodyHtml = true;
        objeto_mail.Subject = subject;
        objeto_mail.Body = messages;
        client.Send(objeto_mail);
        client.Dispose();
    }


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM