0

Is there anyway how to save whole .msg file with attachments from Outlook into a SQL Server database?

I am able to send MailItem objects into database.

Outlook._Application _app = new Outlook.Application();
Outlook.NameSpace _ns = _app.GetNamespace("MAPI");
Outlook.MailItem item = _ns.GetItemFromID(selectedMailEntryId);

string sentOn = item.SentOn.ToLongDateString() + " " + item.SentOn.ToLongTimeString();

if (ServicesMail.InsertMail(txtSenderName.Text, txtSenderAddress.Text, item.Subject, txtQuestions.Text, txtAnswers.Text, item.HTMLBody, sentOn))
{
    MessageBox.Show("Your Mail has been successfully saved in databse.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

and this is the query.

cmd.CommandText = @"INSERT INTO EmailStorage (fullName, emailAddress, questions, answers, htmlBody, sentOn, savedOn, subject)
                    VALUES(@fullName, @emailAddress, @questions, @answers, @htmlBody, @sentOn, @savedOn, @subject)";

cmd.Parameters.AddWithValue("@fullName", fullName);
cmd.Parameters.AddWithValue("@emailAddress", emailAddress);
cmd.Parameters.AddWithValue("@questions", questions);
cmd.Parameters.AddWithValue("@answers", answers);
cmd.Parameters.AddWithValue("@htmlBody", htmlBody);
cmd.Parameters.AddWithValue("@sentOn", sentOn);
cmd.Parameters.AddWithValue("@savedOn", DateTime.Now);
cmd.Parameters.AddWithValue("@subject", subject);

cmd.ExecuteNonQuery();

It works perfectly. But I need to store whole message, so I can take it from database when needed and open it in Outlook.

Looked at many resources, but only found how to store it locally. Can anyone give me a hint?

2
  • 4
    You might be able to save the .msg file as a VarBinary, but why would you? File storage is much better suited for storing ... files. Commented Jul 13, 2016 at 14:51
  • 2
    You might also want to take a look at this article. When you use AddWithValue for pass through queries like this it will sometimes get the wrong datatype. blogs.msmvps.com/jcoehoorn/blog/2014/05/12/… Commented Jul 13, 2016 at 14:53

1 Answer 1

1

Sure, call MailItem.SaveAs(..., olMsg) to save as a local file, then read the file data into a buffer or stream and set binary field's value.

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

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.