ASP.net一键发送电子邮件给多个收件人

时间:2014-02-28 12:52:13

标签: c# asp.net

我有一个显示不同行的数据网格,每个行都有一个链接,可以向与该行标准匹配的多个收件人发送电子邮件 例如

row1col1日本col3 col4(链接发送电子邮件给所有日本用户)...................

row2 col1 Sweden co3 col4(链接发送电子邮件给所有瑞典用户)

现在,当用户点击链接时,另一个页面打开,另一个网格视图控件显示该行的所有收件人,但在此之前向所有收件人发送电子邮件。

问题是需要花费很多时间,我想知道我的方法是否错误我正在为数据行中的每一行创建一个邮件消息对象

DataView dv;

if (dv.Count > 0)
{
    foreach (DataRow row in dv.Table.Rows)
    {
        StringBuilder sbEmailBody = new StringBuilder();
        sbEmailBody.Append("<div id='mail' style='height:400px;width:750px; padding:10px; margin: 0 auto; '>");
        sbEmailBody.Append("Hi " + row["FirstName"].ToString() + ", <br/><br/>");
        sbEmailBody.Append("You have registered with siteName, your details match with the following clinical trial.");
        sbEmailBody.Append("Please contact the below trial representative for further details</br></br>");
        sbEmailBody.Append("<b>Trial Name:</b> " + Session["trialName"].ToString() + "</br>");
        sbEmailBody.Append("<b>Contact Name:</b> " + Session["recName"].ToString() + "</br>");
        sbEmailBody.Append("<b>Contact Email:</b> " + Session["username"].ToString() + "</br>");
        sbEmailBody.Append("<b>Contact Telephone:</b> " + Session["tele"].ToString() + "</br>");
        sbEmailBody.Append("<hr> </hr>");
        sbEmailBody.Append("<a href='www.sitename.com' style=text-decoration:none><span id='logo' style='font-size:X-Large;font-weight:bold;color:Black;'>siteName</span></a><br/>");
        sbEmailBody.Append("<span id='stopEmail' style='font-size:Smaller;'>");
        sbEmailBody.Append("if you want to stop receiving emails from sitename please click <a href='www.bbc.co.uk' style=text-decoration:none>here</a>");
        sbEmailBody.Append("</span>");
        sbEmailBody.Append("</div>");


        MailMessage mailMessage = new MailMessage("siteEmail@email.com", row["EmailAdd"].ToString());
        mailMessage.Subject = "Clinical trial recruiter shown interest in your profile";
        mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
        mailMessage.Body = sbEmailBody.ToString();
        mailMessage.IsBodyHtml = true;
        SmtpClient smtpClient = new SmtpClient();

        smtpClient.Send(mailMessage);


    }
}

2 个答案:

答案 0 :(得分:1)

您可以创建Task来为您进行邮寄。

Task.Run(() => YourMailMethod());

YourMailMethod方法中,您可以输入现在已有的代码。

该任务将在后台运行。

答案 1 :(得分:1)

你可以像这样做一个异步操作来解决问题

public delegate void SendMessage(SmtpClient客户端,MailMessage消息);

 SendMessage Smessage = new SendMessage(ResultCallback);
            //smtp.Send(message);
            Smessage.BeginInvoke(smtpClient, message, null, null);





public void ResultCallback(SmtpClient client, MailMessage m)
        {
            try
            {
                client.Send(m);
                client.Dispose();
                m.Dispose();
            }
            catch
            {

            }
        }