smtp电子邮件发送问题for for循环c#

时间:2018-05-17 18:08:55

标签: c# smtp

我想在For循环的帮助下发送电子邮件多个电子邮件地址,但只有第一封电子邮件才能正常发送,但在第二次我收到" faild发送电子邮件"问题 任何人都可以帮助我

下面是我的代码

        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);
        }

1 个答案:

答案 0 :(得分:0)

这是你应该发送多封电子邮件的方式,确保在发送每封电子邮件后使用smtpMesg.Close()。

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();
    }


}