【问题标题】:How do I connect the SQL Server database to my e-mail system?如何将 SQL Server 数据库连接到我的电子邮件系统?
【发布时间】:2017-10-24 11:21:29
【问题描述】:

将我的数据库连接到我的电子邮件系统时遇到问题。我已经建立了一个数据库连接和一个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);
    }
}

【问题讨论】:

  • THINK THINK THINK:您可以编写一个从数据库返回字符串(电子邮件)的方法,并在您的新 MailAddress(stringreturned) 中使用它;
  • 你到底在坚持什么?读取电子邮件地址 -> 在 MailAddress 中设置 -> 发送电子邮件。
  • 你没有帮助!

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


【解决方案1】:

您可以将“emailresult”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);
}

【讨论】:

  • 您能详细说明一下吗?只是一个基本的程序员开始。
  • 修改了代码以匹配您在数据源上的选择语句。确保在代码之上使用 System.Linq。
【解决方案2】:

正如其他人已经评论的那样,您必须将您想做的事情分成不同的部分:

  1. 从您的数据库中获取电子邮件地址
  2. 发送电子邮件。 (已经存在)

那么,你想知道如何从你的 sqldatasource 获取电子邮件,这将是这样的(未测试):

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    相关资源
    最近更新 更多