2

如何将保存在 MS SQL 数据库中的一个或多个文件添加到电子邮件中?我已经知道如何附加保存在目录中或来自 fileUpload 控件的文件。

我的数据字段是这样的:

col1:Email_ID - 整数

col2: 文件名 - varchar

col3:file_content - 图像

所以我的 SQL 选择语句非常简单:

Select file_name, file_content from Attachments where Email_ID = 333

我只是想不出之后如何将它们附加到我的电子邮件中。

谢谢!

4

2 回答 2

3
  SqlCommand cmdSelect=new SqlCommand("Select file_name, file_content " + 
              " from Attachments where Email_ID=@ID",this.sqlConnection1);
        cmdSelect.Parameters.Add("@ID",SqlDbType.Int,4);
        cmdSelect.Parameters["@ID"].Value=333;

DataTable dt = new DataTable();
        this.sqlConnection1.Open();
        SqlDataAdapter sda = new SqlDataAdapter();
            sda.SelectCommand = cmdSelect;
            sda.Fill(dt);
     if(dt.Rows.Count > 0)
{
        byte[] barrImg=(byte[])dt.Rows[0]["file_content"];
        string strfn= "Your File Directory Path" + Convert.ToString(dt.Rows[0]["file_name"]);
        FileStream fs=new FileStream(strfn, 
                          FileMode.CreateNew, FileAccess.Write);
        fs.Write(barrImg,0,barrImg.Length);
        fs.Flush();
        fs.Close();
   //now you can attache you file to email here your file is generate at path stored in "strfn" variable
}

参考资料: http: //www.codeproject.com/KB/database/ImageSaveInDataBase.aspx

于 2011-07-22T05:48:08.417 回答
2

从 SQL 获取图像,将其转换为流,然后为您的电子邮件创建附件。示例:Attachment(Stream, String) 使用指定的流和名称初始化 Attachment 类的新实例。

于 2011-07-21T14:03:53.237 回答