我有一個要求將MailMessage對象(system.net.mail)保存到SQL Server 2005數據庫中的一個表中,使用.Net 2。如何將System.Net.Mail MailMessage對象保存到SQL Server數據庫中?
郵件對象還包含一個圖像附件,它是郵件正文作爲郵件頂部的徽標。
這工作和創建我的MailMessage對象,它可以發送無後顧之憂。
private bool SendEMAIL(string wsStudent, string wsNOKemails, string wsMSG)
{
try
{
MailMessage message = new MailMessage();
message.To.Clear();
string[] wsEmails = wsNOKemails.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (string address in wsEmails)
{
MailAddress to = new MailAddress(address);
message.To.Add(to);
}
//get staff email as the FROM address
DataSourceSelectArguments dss = new DataSourceSelectArguments();
sdsStaffDetails.SelectParameters["StaffID"].DefaultValue = Session["StaffID"].ToString();
DataView dv = sdsStaffDetails.Select(dss) as DataView;
DataTable dt = dv.ToTable() as DataTable;
if (dt != null)
{
foreach (DataRow dr in dt.Rows) //this loop will only happen once
{
message.From = new MailAddress(dr.ItemArray[2].ToString()); //TET's staffer email address
message.Subject = "Tec-NQ - TET Report for " + wsStudent;
message.Priority = MailPriority.High;
message.IsBodyHtml = true;
//add the logo attachment
MemoryStream ms = new MemoryStream(File.ReadAllBytes(Server.MapPath("../images/Tec-NQ-Logo-BlueOrange-60x174.png")));
Attachment logo = new Attachment(ms, "logo");
message.Attachments.Add(logo);
//..but create a Base64 version of it, as we'll need to embedd this into the message so it knows
//where to place the logo into the email
string contentID = "Image";
logo.ContentId = contentID;
logo.ContentDisposition.Inline = true;
logo.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
//replace the <p> contents of the logo with a new HTML string header to contain the cid reference for the logo
string wsHdr = "<html><body><p><a href=\"http://www.tecnq.com.au\" target=\"_blank\"><img alt=\"tecnqlogo\" src=\"cid:" + contentID + "\" style=\"border-style:none; height:34px; width:100px\" /></a></p>";
//then place back the rest of the email
string wsBody = wsHdr + " " + wsMSG.Substring(wsMSG.IndexOf("<hr />")) + "</html></body>";
message.Body = wsBody;
//send it!
SmtpClient SmtpClient = new SmtpClient();
SmtpClient.Send(message);
}
return true;
}
else
return false;
}
catch (Exception msg)
{
StatusMessage(msg.ToString());
return false;
}
}
我已閱讀this和this,但所有這些假設你想MAILMESSAGE的保存到磁盤上的文件。對我來說並非如此。
我也讀過this,這意味着我應該serialise
的消息。但我認爲MailMessage是一個無法序列化的核心對象,據微軟稱。那是對的嗎?
因此,關於如何將上述內容另存爲BLOB或某種數據類型的任何想法,都是我打開表格,讀取對象並像發送普通電子郵件一樣發送它?
UPDATE
This CodeProject上的文章是前進的方向,我剛發現。但是,在將MailMessage對象保存到磁盤時指定文件名。這是一個開始,因爲我可以在文件名中指定一些字段分隔符來指定稍後使用哪些文件,就閱讀EML文件和稍後通過電子郵件發送該對象而言。
不是將整個'MailMessage'保存爲單個BLOB或其他文件,而是將其屬性保存爲稍後可以重建的選項? – Searching
@搜索是的,我可以稍後添加它。最小值是保存附件和消息正文 – Fandango68
Sweet ..在這種情況下,對於附件,您需要先轉換爲byte [],並保存爲VARBINARY(MAX)MyTable。附件「,我想其他細節取決於你。我可以發佈一個答案.. – Searching