2016-11-16 136 views
0

我有一個要求將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; 
     } 
    } 

我已閱讀thisthis,但所有這些假設你想MAILMESSAGE的保存到磁盤上的文件。對我來說並非如此。

我也讀過this,這意味着我應該serialise的消息。但我認爲MailMessage是一個無法序列化的核心對象,據微軟稱。那是對的嗎?

因此,關於如何將上述內容另存爲BLOB或某種數據類型的任何想法,都是我打開表格,讀取對象並像發送普通電子郵件一樣發送它?

UPDATE

This CodeProject上的文章是前進的方向,我剛發現。但是,在將MailMessage對象保存到磁盤時指定文件名。這是一個開始,因爲我可以在文件名中指定一些字段分隔符來指定稍後使用哪些文件,就閱讀EML文件和稍後通過電子郵件發送該對象而言。

+2

不是將整個'MailMessage'保存爲單個BLOB或其他文件,而是將其屬性保存爲稍後可以重建的選項? – Searching

+0

@搜索是的,我可以稍後添加它。最小值是保存附件和消息正文 – Fandango68

+1

Sweet ..在這種情況下,對於附件,您需要先轉換爲byte [],並保存爲VARBINARY(MAX)MyTable。附件「,我想其他細節取決於你。我可以發佈一個答案.. – Searching

回答

1

我認爲你發佈的更新非常好。還請查看How to save MailMessage object to disk as *.eml or *.msg file的答案。您可能可以創建多個客戶端,一個用於正確發送,另一個用於將消息保存到本地文件,然後需要將其保存到數據庫。我還沒有嘗試過。

如果你還在尋找到這一點,貼示例代碼...

僅可用於單個附件。樣本只是爲了讓你開始,不應該被視爲現實。有很多改進的餘地。 我們將附件加載到byte[]中,然後將其添加爲Attachment(Stream s)。我們將其保存到db中作爲我們的VARBINARY內容。

你先發送方法,這也節省了消息DB

try 
     { 
      MailMessage message = new MailMessage(); 
      var logoPath = @"C:\MyLogo.jpg"; 
      message.From = new MailAddress("[email protected]"); 
      message.To.Add("[email protected]"); 
      message.IsBodyHtml = true; 

      //Read the attachment into byte Array. This assumes single attachment only in the Mail Message. 
      byte[] arr = File.ReadAllBytes(logoPath); 

      using (var stream = new MemoryStream(arr)) 
      { 
       stream.Position = 0; 
       Attachment logo = new Attachment(stream, "Logo"); 
       string contentID = "Image"; 
       logo.ContentId = contentID; 
       logo.ContentDisposition.Inline = true; 
       logo.ContentDisposition.DispositionType = DispositionTypeNames.Inline; 

       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>" + "</html></body>"; ; 

       message.Body = wsHdr; 
       message.Attachments.Add(logo); 


       SmtpClient smtp = new SmtpClient(); 
       smtp.Host = "MyServer"; 
       smtp.Port = 25; 
       smtp.Send(message); 
       SaveMessage(message, arr); 
      }    
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.ToString()); 
     } 

要保存郵件

//ZERO ERRO CHECKING. 
    private static void SaveMessage(MailMessage message, byte[] arr) 
    { 
     using (var conn = new SqlConnection("CONNECTION_STRING")) 
     { 
      using (var cmd = new SqlCommand("INSERT INTO MailSent (Body,Attachment) VALUES(@BODY,@ATTACHMENT)", conn)) 
      { 
       conn.Open(); 
       var param = new SqlParameter("@BODY", SqlDbType.VarChar) 
       { 
        Value = message.Body 
       }; 
       var param2 = new SqlParameter("@ATTACHMENT", SqlDbType.Binary) 
       { 
        Value = arr 
       }; 
       cmd.Parameters.Add(param); 
       cmd.Parameters.Add(param2); 
       cmd.ExecuteNonQuery(); 
      } 
     }    
    } 

重新發送消息

try 
     { 
      MailMessage message = new MailMessage(); 
      byte[] arr2 = null; 
      GetMailMessage(2, ref message, ref arr2); 


      message.From = new MailAddress("[email protected]"); 
      message.To.Add("[email protected]"); 
      message.IsBodyHtml = true; 

      using (var stream = new MemoryStream(arr2)) 
      { 
       stream.Position = 0; 
       Attachment logo = new Attachment(stream, "Logo"); 
       string contentID = "Image"; 
       logo.ContentId = contentID; 
       logo.ContentDisposition.Inline = true; 
       logo.ContentDisposition.DispositionType = DispositionTypeNames.Inline; 
       message.Attachments.Add(logo); 

       SmtpClient smtp = new SmtpClient(); 
       smtp.Host = "MyServer"; 
       smtp.Port = 25; 
       smtp.Send(message); 

      } 

      // SaveMessage(message, arr); 
     } 
     catch (Exception ex) 
     { 

      Console.WriteLine(ex.ToString()); 
     } 

來檢索信息

//ZERO ERROR CHECKING. 
    private static void GetMailMessage(int itemId, ref MailMessage msg2, ref byte[] arr2) 
    { 
     using (var conn = new SqlConnection("CONNECTION_STRING")) 
     { 
      using (var cmd = new SqlCommand("SELECT [Body],[Attachment] FROM MailSent WHERE ID = @itemId", conn)) 
      { 
       conn.Open(); 
       cmd.Parameters.AddWithValue("@itemId", itemId); 

       using (SqlDataReader dr = cmd.ExecuteReader()) 
       { 
        while (dr.Read()) 
        { 
         msg2.Body = dr[0].ToString(); 
         arr2 = dr[1] as byte[]; 
        } 
       } 
      } 
     } 
    } 
+0

作品!謝謝 – Fandango68

相關問題