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

本文关键字:数据 何读取 读取 二进制 | 更新日期: 2023-09-27 18:10:38

我的数据库中有一个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);
有人能帮我解决这个问题吗?

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

简单地从byte[]数组构造一个流并将其传递给附件构造函数。如:

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