2

I want to retrieve mail attachments and store them into bytes[] so that I can insert them into table where a column attachment is of varbinary type. In windows form I am using OpenFileDialog and I don't know how to get the file's bytes in a byte[] type so that I can insert that into table in SQLServer.

Here is the code:

namespace fyp8
{
    public partial class ComposeMail : Form1
    {
        ArrayList alAttachments;
        MailMessage mmsg;
        string conn = @"Data source=(local);Initial Catalog=fyp;Integrated Security=true";


        public ComposeMail()
        {
            InitializeComponent();
        }

        private void ComposeMail_Load(object sender, EventArgs e)
        {

        }

        private void btnAttachment_Click(object sender, EventArgs e)
        {
            OpenFileDialog odflg = new OpenFileDialog();
            odflg.ShowDialog();
            if (odflg.ShowDialog() == DialogResult.OK)
            {

                try
                {
                    txtAttachments.Text = odflg.FileName;

                }

                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error");
                }
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {

            try
            {
                if (txtEmid.Text != null && txtPass.Text != null)
                {
                    mmsg = new MailMessage(txtEmid.Text, txtTo.Text);

                    mmsg.Subject = txtSub.Text;
                    mmsg.Body = txtBody.Text;
                    mmsg.IsBodyHtml = true;

                    /* Set the SMTP server and send the email with attachment */

                    SmtpClient smtpClient = new SmtpClient();

                    // smtpClient.Host = emailServerInfo.MailServerIP;
                    //this will be the host in case of gamil and it varies from the service provider

                    smtpClient.Host = "smtp.gmail.com";
                    //smtpClient.Port = Convert.ToInt32(emailServerInfo.MailServerPortNumber);
                    //this will be the port in case of gamil for dotnet and it varies from the service provider

                    smtpClient.Port = 587;
                    smtpClient.UseDefaultCredentials = true;

                    //smtpClient.Credentials = new System.Net.NetworkCredential(emailServerInfo.MailServerUserName, emailServerInfo.MailServerPassword);
                    smtpClient.Credentials = new NetworkCredential(txtEmid.Text, txtPass.Text);

                    //Attachment
                    Attachment attachment = new Attachment(txtAttachments.Text);
                    if (attachment != null)
                    {
                        mmsg.Attachments.Add(attachment);
                    }


                    //this will be the true in case of gamil and it varies from the service provider
                    smtpClient.EnableSsl = true;
                    smtpClient.Send(mmsg);
                }

                string msg = "Message Send Successfully:";
                msg += "\n To :" + txtTo.Text;

                SqlConnection con = new SqlConnection(conn);
                string query = "insert into sentmail values(@from,@to,@sub,@body,@status)";
                SqlCommand cmd = new SqlCommand(query, con);
                cmd.Parameters.AddWithValue("@from", txtFrom.Text);
                cmd.Parameters.AddWithValue("@to", txtTo.Text);
                cmd.Parameters.AddWithValue("@sub", txtSub.Text);
                cmd.Parameters.AddWithValue("@body",txtBody.Text);
                cmd.Parameters.AddWithValue("@status","sent" );
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();

                MessageBox.Show(msg.ToString());

                /* clear the controls */
                txtEmid.Text = string.Empty;
                txtPass.Text = string.Empty;
                txtFrom.Text = string.Empty;
                txtTo.Text = string.Empty;
                txtSub.Text = string.Empty;
                txtBody.Text = string.Empty;
                txtAttachments.Text = string.Empty;
            }

            catch (Exception ex)
            { 
                MessageBox.Show(ex.Message.ToString());
            }
        }
    }
}
2
  • 1
    Can you please provide a minimal example? From what I gather from your question text, all the code related to the open dialog and the e-mail is entirely irrelevant to your problem. You have a filename string, and you want to get the contents of that file into a byte array, right? Commented Apr 26, 2014 at 22:08
  • yes right. I wan to store the attachment file into byte[] Commented Apr 26, 2014 at 22:10

1 Answer 1

14
void Test() {
    var dialog = new OpenFileDialog();
    var result = dialog.ShowDialog();
    if (result != DialogResult.OK)
        return;

    byte[] buffer = File.ReadAllBytes(dialog.FileName);

    // Do whatever you want here with buffer
}

You're currently calling ShowDialog() twice. Just call it once and save the result.

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

1 Comment

when i declare var dialog=Openfiledialog() on the button click event its giving the erreo as system.windows.form.openfiledialog is a type but is used like variable.

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.