2011-07-21 31 views
2

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

我确定年代领域是这样:

COL1:EMAIL_ID - 诠释

COL2:FILE_NAME - VARCHAR

COL3:FILE_CONTENT - 图像

所以我的SQL SELECT语句prety简单:

Select file_name, file_content from Attachments where Email_ID = 333 

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

谢谢!

+0

将它保存在一个临时文件第一并附加到电子邮件。 – Johan

回答

3
SqlCommand cmdSelect=new SqlCommand("Select file_name, file_content " + 
       " from Attachments where [email protected]",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

2

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

相关问题