2

How can I add one or more files that are saved in a MS SQL database to an email? I already know how to attach files saved in a directory or from a fileUpload control.

My datable fields are as such:

col1: Email_ID - int

col2: file_name - varchar

col3: file_content - image

So my SQL select statement is prety simple:

Select file_name, file_content from Attachments where Email_ID = 333

I just can't figure how to attach them to my emails afterwards.

Thanks!

1
  • Save it in a temp file first and attach that to the email. Commented Jul 21, 2011 at 14:01

2 Answers 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
}

References : http://www.codeproject.com/KB/database/ImageSaveInDataBase.aspx

Sign up to request clarification or add additional context in comments.

Comments

2

Get image from SQL, convert it to stream then create Attachment to your emails. Sample: Attachment(Stream, String) Initializes a new instance of the Attachment class with the specified stream and name.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.