如何将SQL Server数据库连接到我的电子邮件系统?

时间:2017-10-24 11:21:29

标签: c# asp.net system.net.mail

将数据库连接到我的电子邮件系统时遇到麻烦。我已经建立了数据库连接和SqlDataSource连接,但我不确定如何在我的aspx.cs页面上引用它,因为我想向存储在数据库中的电子邮件发送电子邮件。

<asp:SqlDataSource ID="emailresult" runat="server" 
     ConnectionString='<%$ ConnectionStrings:databaseconnection %>' 
     SelectCommand ="SELECT [ID], [email], [role] FROM [emailtest]">
</asp:SqlDataSource>

protected void EmailTestButton_Click(object sender, EventArgs e)
{

    try
    {
        MailMessage mailMessage = new MailMessage();
        mailMessage.To.Add("");
        mailMessage.To.Add("");
        mailMessage.From = new MailAddress("studiodefault@hotmail.com");
        mailMessage.Subject = "Scrum Management Studio - Role Confirmation";
        mailMessage.IsBodyHtml = true;
        mailMessage.Body = "Hello, <br /><br /> You have been assigned the role of <b>[ROLE]</b>  <br /><br /> \n\nKind Regards, <br />The Scrum Management Studio Team" ;
        mailMessage.Priority = MailPriority.High; 
        SmtpClient smtpClient = new SmtpClient("smtp-isp.com");
        smtpClient.Send(mailMessage);
        Response.Write("Email has been successfully sent");
    }
    catch (Exception ex)
    {
        Response.Write("Could not send the email - error: " + ex.Message);
    }
}

2 个答案:

答案 0 :(得分:1)

您可以转换&#34; emailresult&#34; SqlDataSource到DataTable并从那里查询

var dt = ((DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty)).Table;
var emails = from e in dt.AsEnumerable()
                where e.Field<int>("ID") == 1
                select e.email;

foreach (var email in emails)
{
    mailMessage.To.Add(email);
}

答案 1 :(得分:0)

正如其他人已经评论过的那样,你必须在不同的部分中分割你想要做的事情:

  1. 从您的数据库中获取电子邮件地址
  2. 发送电子邮件。 (已经在那里)
  3. 那么,你想知道如何从你的sqldatasource获取电子邮件,这将是这样的(未经测试):

    DataView dv = emailresult.Select(DataSourceSelectArguments.Empty);
    DataTable dt = dv.ToTable();
    String Email = Convert.ToString(dt.rows[0]["Email"]);