第一步:SQL邮件服务器的搭建
第二步:调用SQL 邮件自带的sp_send_dbmail存储进行邮件发送
private static void SendEmail(SqlParameter[] paras = null)
{
string connString = "server='server ip';database=msdb;user id=sa;pwd=123456";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand comm = new SqlCommand("sp_send_dbmail", conn);
comm.CommandType = CommandType.StoredProcedure;
conn.Open();
if (paras != null)
{
comm.Parameters.AddRange(paras);
comm.ExecuteNonQuery();
}
conn.Close();
}
}
//填充邮件参数,调用SendEmail方法发送邮件
string recipients = "user1@test.com;user2@test.com";
string copy_recipients = "user3@test.com;";
string blind_copy_recipients= "user4@test.com";
string subject = "邮件标题" ;
string body = "邮件内容(可用html格式填充内容)";
SqlParameter[] paras = new SqlParameter[] {
//发件账号 @profile_name
//收件人 @recipients
//标题 @subject
//内容 @body
new SqlParameter(){ParameterName="@profile_name",SqlDbType=SqlDbType.NVarChar,SqlValue="发件人名称" },
new SqlParameter(){ParameterName="@recipients",SqlDbType=SqlDbType.NVarChar,SqlValue=recipients },
new SqlParameter(){ParameterName="@copy_recipients",SqlDbType=SqlDbType.NVarChar,SqlValue=copy_recipients },
new SqlParameter(){ParameterName="@blind_copy_recipients",SqlDbType=SqlDbType.NVarChar,SqlValue=blind_copy_recipients },
new SqlParameter(){ ParameterName="@subject", SqlDbType=SqlDbType.NVarChar,SqlValue=subject },
new SqlParameter(){ ParameterName="@body", SqlDbType=SqlDbType.NVarChar,SqlValue=body },
new SqlParameter(){ ParameterName="@body_format", SqlDbType=SqlDbType.NVarChar,SqlValue="HTML" }
};
try
{
SendEmail(paras);
}
catch
{
MessBox.Show("发送失败!");
}