如何读取二进制数据并作为附件发送?

时间:2015-09-01 12:51:40

标签: c# asp.net smtp

我的DataBase数据实际上是PDF文件

command = " select pdffile from pdftable where ...."

我有下一个代码:

OracleDataReader reader = command.ExecuteReader();
            if (reader.Read() && !reader.IsDBNull(1))
            {
                byte[] BytesData = (byte[])reader["BOOKC_ATTACHMENT"];
                Response.ContentType = "application/force-download";
                Response.AddHeader("content-disposition",
                                   "attachment; filename=\"" +
                                   Path.GetFileName((string)reader["BOOKC_ATTACHMENT_NAME"]) + "\"");
                Response.AddHeader("Expires", "0");
                Response.BinaryWrite(BytesData);
                Response.End();
            }
            reader.Close();
            reader.Dispose();

它从数据库中读取数据并从中创建PDF文件,然后将其作为下载提供。

现在,我不想下载它,我想用SMTP将其发送到电子邮件地址:

MailMessage mm = new MailMessage();
            mm.Subject = strSubject;
            mm.Body = strHtmlBody;
            mm.From = "xxx@xxx.com";
            mm.To = "xx@xx.com";

    Attachment att = new Attachment();
            att. ????
            mm.Attachments.Add(att);

SmtpClient smtp = new SmtpClient();
                smtp.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["msg_ben_from"],
                                                         ConfigurationManager.AppSettings["msg_ben_pwd"]);
                smtp.Send(mm);

有人可以帮我解决吗?

1 个答案:

答案 0 :(得分:0)

只需从byte []数组构造一个流并将其传递给附件构造函数。 像:

// assuming byte[] BytesData = something at this point
var att = new Attachment(new MemoryStream(BytesData, false), 
  "file.pdf", "application/pdf");