简体   繁体   中英

How do I connect the SQL Server database to my e-mail system?

Having troubles with connecting my database to my email system. I have set up a database connection and a SqlDataSource connection, however I am unsure how to reference it on my aspx.cs page as I want to send an email to the email stored in the database.

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

You may convert the "emailresult" SqlDataSource to DataTable and query from there

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

As the others already commented, you have to split what you want to do in separate parts:

  1. Get the email address from your database
  2. Send the email. (already there)

So, what you want to find out it how to get email from you sqldatasource, which will be something like this (not tested):

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

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