如何将System.Net.Mail MailMessage对象保存到SQL Server数据库中?

时间:2016-11-16 03:46:44

标签: c# asp.net sql-server email

我要求使用.Net 2将MailMessage对象(system.net.mail)保存到SQL Server 2005数据库中的表。

邮件对象还包含一个图像附件,它是邮件消息正文的一部分,作为邮件顶部的徽标。

这可以工作并创建我的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或某些数据类型的任何想法,以后我都要做的就是打开表格,读取对象并像普通电子邮件一样发送它?

更新

This CodeProject文章是我发现的前进方式。但是,在将MailMessage对象保存到磁盘时指定文件名。这是一个开始,因为我可以在文件名中指定一些字段分隔符,以指定稍后要使用的文件,包括读取EML文件和稍后通过电子邮件发送对象。

1 个答案:

答案 0 :(得分:2)

我认为您发布的更新非常好。另请查看How to save MailMessage object to disk as *.eml or *.msg file的答案。您可能可以创建多个客户端,一个用于正确发送,另一个用于将消息保存到本地文件,然后需要将其保存到DB。我虽然没试过这个。

如果您仍在调查此事,请发布示例代码......

仅限于单个附件。该示例仅供您入门,不应该按原样使用。有很大的改进空间。 我们将附件加载到byte[],然后将其添加为Attachment(Stream s)。我们将此作为VARBINARY内容保存到数据库中。

您的第一个发送方法,也将消息保存到db

try
        {
            MailMessage message = new MailMessage();
            var logoPath = @"C:\MyLogo.jpg";
            message.From = new MailAddress("from@email.co.nz");
            message.To.Add("to@email.co.nz");
            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("from@email.co.nz");
            message.To.Add("to@email.co.nz");
            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[];
                    }
                }
            }
        }
    }