从 C# 应用程序中的 SQL Server 存储过程获取 mail.to.add 的电子邮件地址

问题描述 投票:0回答:1

我想在用户在我的 C# 应用程序中提交表单后向他们发送电子邮件。他们的电子邮件地址存储在数据库中,我想创建一个存储过程,根据他们的人员编号选择他们的电子邮件地址。

这是我到目前为止的工作代码,但它仅适用于已经列出的电子邮件地址。

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

SmtpClient SmtpServer = new SmtpClient("smtp.office365.com", 25);
SmtpServer.EnableSsl = true;
SmtpServer.Timeout = 10000000;
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpServer.UseDefaultCredentials = false;

SmtpServer.Credentials = new System.Net.NetworkCredential(email, password, domain);

MailMessage mail = new MailMessage();
mail.From = new MailAddress(email);
mail.To.Add(""); **//Want this to come calling a stored procedure**
mail.Subject = "MAIL TEST";
mail.Body = "Mail code working";
mail.IsBodyHtml = true;

SmtpServer.Send(mail);
SmtpServer.Dispose();

SmtpServer.SendCompleted += (s, x) => {
    SmtpServer.Dispose();
    mail.Dispose();
};

WebMessageBox.Show("Mail sent");
c# asp.net sql-server smtp
1个回答
0
投票

您需要创建一个 C# 部分和一个 tSQL 部分才能完成此工作。

C#

//Create a new function that returns a string.
private string GetEmailAddresFromDB(int ManNo) {
    //sqlText is the name of the stored procedure in SQL server.
    string sqlText = "sp_GetEmailAddressFromManNo";

    //using blocks for the connection and command so they are properly disposed when done.
    //You have to provide a valid connection string.
    using (SqlConnection conn = new SqlConnection("sqlconnectionstring")) {
        conn.Open();    //Open the connection.
        using (SqlCommand cmd = new SqlCommand(sqlText, conn)) {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@ManNo", SqlDbType.Int, -1) { Value =  ManNo });
            cmd.Parameters.Add(new SqlParameter("@EmailAddress", SqlDbType.NVarChar, 255) { Direction = ParemeterDirection.Output });

            cmd.ExecuteNonQuery();
            return cmd.Parameters["@EmailAddress"].Value.ToString(); //Read the output parameter and return.
        }
    }
}

SQL

--This stored procedure uses an output parameter to send the email address back to code.
--If you want to return more than just an email address, 
--  you should return a table result and use some kind of 
--  DataAdapter in C# to read the relevant table data from the result.
CREATE PROCEDURE sp_GetEmailAddressFromManNo 
    @ManNo int
    , @EmailAddress nvarchar output
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    SELECT @EmailAddress = email_address
    FROM users
    WHERE man_no = @ManNo
END

然后修改你的代码:

mail.To.Add(GetEmailAddressFromDB(ManNo: manNo));

这都是伪代码。您必须修改存储过程和 C# 函数以匹配您的参数、存储过程名称以及您未向我们展示的其他未知内容。您可能还想使用

try {} catch {}
块添加一些错误处理。

© www.soinside.com 2019 - 2024. All rights reserved.