提问人:KayC 提问时间:11/14/2023 最后编辑:marc_sKayC 更新时间:11/15/2023 访问量:63
从 C# 应用程序中的 SQL Server 存储过程获取 mail.to.add 的电子邮件地址
Get email address for mail.to.add from a SQL Server stored procedure in C# application
问:
我想在用户在我的 C# 应用程序中提交表单后向他们发送电子邮件。他们的电子邮件地址存储在数据库中,我想创建一个存储过程,该过程将根据他们的 man no 选择他们的电子邮件地址。
到目前为止,这是我的工作代码,但它仅适用于已列出的电子邮件地址。
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");
答:
0赞
Tim Jarosz
11/15/2023
#1
您需要创建一个 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 {}
评论
0赞
marc_s
12/21/2023
旁注:不应将前缀用于存储过程。Microsoft 已保留该前缀供其自己使用(请参阅命名存储过程),并且您确实会在将来的某个时候面临名称冲突的风险。这对存储过程的性能也很不利。最好只是简单地避免并使用其他东西作为前缀 - 或者根本没有前缀!sp_
sp_
评论
SmtpServer.Timeout = 10000000