将 RDLC 输出作为电子邮件附件分发

发布于 2024-09-25 21:05:12 字数 412 浏览 7 评论 0原文

我们的 winforms 应用程序长期以来一直允许“打印”选项,该选项基本上使用 RDLC。

客户要求我们添加一项功能,允许用户通过电子邮件发送“打印”输出。

现在,我们知道 EMF 文件是作为当前打印过程的一种隐藏副产品创建的(在 TEMP 文件夹中)。

在我们看来,我们可以简单地获取这个 EMF 文件并将其附加到新电子邮件中,工作就完成了。

  1. 这是最好的选择吗?
  2. 我们可以依赖任何 Windows 机器打开 EMF 文件吗?
  3. 我们如何识别EMF文件? ...目前似乎被命名为 %TEMP%\DiaryGrid_1.emf 。好的,DiaryGrid 是我们的 RDLC 文件的名称,但 _1 会在此过程中添加到某个位置。

Our winforms application has long allowed a "print" option which basically uses RDLC.

The customer has requested that we add a feature allowing users to send the "printed" output via email.

Now, we know that an EMF file is created (in the TEMP folder) as a sort of hidden byproduct of our current printing process.

Seems to us we can simply grab this EMF file and attach it to a new email and the job is done.

  1. Is this the best option?
  2. Can we rely on an EMF file be opened by any Windows machine?
  3. How we identify the EMF file? ... just seems to be named %TEMP%\DiaryGrid_1.emf currently. OK so DiaryGrid is the name of our RDLC file but the _1 gets added somewhere along the way.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

遇见了你 2024-10-02 21:05:12

我以前做过。我以编程方式将报告导出为 pdf 格式到特定位置,然后我们通过电子邮件发送 pdf 文件并将其删除。我会尽力为您找到代码(现在不在家里)

已编辑:

抱歉稍后。现在我在家,我会给你一些代码块,我认为它们会给你一些帮助来完成你的任务。我将对代码添加一些注释,以便您可以理解我的项目中特定的一些内容。该代码已经过测试并且在我的客户中运行良好,但我确信它可以改进。如果您可以改进此代码,请告诉我;)

首先,我们将报告导出为 pdf。

private string ExportReportToPDF(string reportName)
{
   Warning[] warnings;
   string[] streamids;
   string mimeType;
   string encoding;
   string filenameExtension;
   byte[] bytes = ReportViewer1.LocalReport.Render(
      "PDF", null, out mimeType, out encoding, out filenameExtension,
       out streamids, out warnings);

   string filename = Path.Combine(Path.GetTempPath(), reportName);
   using (var fs = new FileStream(filename, FileMode.Create))
   {
      fs.Write(bytes, 0, bytes.Length);
      fs.Close();
   }

   return filename;
}

现在,我们需要一个控制邮件系统的类。每个邮件系统都有自己的特点,所以也许你需要修改这个类。该类的行为很简单。您只需填写属性,然后调用 Send 方法即可。就我而言,一旦我发送了pdf文件,Windows就不允许我删除它(Windows说该文件正在使用中),所以我将该文件编程为在下次重新启动时删除。看一下删除方法。请注意,发送方法使用名为 MailConfig 的自定义类。这是一个小类,有一些配置字符串,如主机、用户名和密码。邮件将使用此参数发送。

public class Mail
{
   public string Title { get; set; }
   public string Text { get; set; }
   public string From { get; set; }
   public bool RequireAutentication { get; set; }
   public bool DeleteFilesAfterSend { get; set; }

   public List<string> To { get; set; }
   public List<string> Cc { get; set; }
   public List<string> Bcc { get; set; }
   public List<string> AttachmentFiles { get; set; }

   #region appi declarations

   internal enum MoveFileFlags
   {
      MOVEFILE_REPLACE_EXISTING = 1,
      MOVEFILE_COPY_ALLOWED = 2,
      MOVEFILE_DELAY_UNTIL_REBOOT = 4,
      MOVEFILE_WRITE_THROUGH = 8
   }

   [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
   static extern bool MoveFileEx(string lpExistingFileName,
                                 string lpNewFileName,
                                 MoveFileFlags dwFlags);

   #endregion

   public Mail()
   {
      To = new List<string>();
      Cc = new List<string>();
      Bcc = new List<string>();
      AttachmentFiles = new List<string>();
      From = MailConfig.Username;
   }

   public void Send()
   {
      var client = new SmtpClient
      {
         Host = MailConfig.Host,
         EnableSsl = false,
      };

      if (RequireAutentication)
      {
         var credentials = new NetworkCredential(MailConfig.Username, 
                                                 MailConfig.Password);
         client.Credentials = credentials;
      }

      var message = new MailMessage
      {
         Sender = new MailAddress(From, From),
         From = new MailAddress(From, From)
      };

      AddDestinataryToList(To, message.To);
      AddDestinataryToList(Cc, message.CC);
      AddDestinataryToList(Bcc, message.Bcc);

      message.Subject = Title;
      message.Body = Text;
      message.IsBodyHtml = false;
      message.Priority = MailPriority.High;

      var attachments = AttachmentFiles.Select(file => new Attachment(file));
      foreach (var attachment in attachments)
         message.Attachments.Add(attachment);

      client.Send(message);

      if (DeleteFilesAfterSend)
         AttachmentFiles.ForEach(DeleteFile);
   }

   private void AddDestinataryToList(IEnumerable<string> from,
      ICollection<MailAddress> mailAddressCollection)
   {
      foreach (var destinatary in from)
         mailAddressCollection.Add(new MailAddress(destinatary, destinatary));
   }

   private void DeleteFile(string filepath)
   {
      // this should delete the file in the next reboot, not now.
      MoveFileEx(filepath, null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT);
   }
}

现在,您可以创建一个表单来询问目的地,添加一些验证等,返回 Mail 类的实例......或者您可以简单地“硬编码”这些值并填充该类。

以下是我在按钮中用于调用此表单的代码,在我的示例中,它名为 SendMailView。

private void BtnSendByMail_Click(object sender, EventArgs e)
{
   SendMailView sendMailView = new SendMailView();

   if (sendMailView.ShowDialog()== DialogResult.OK)
   {
      Mail mail = sendMailView.CurrentItem;
      mail.AttachmentFiles.Add(ExportReportToPDF("Invoice.pdf"));
      mail.DeleteFilesAfterSend = true;
      mail.RequireAutentication = true;
      mail.Send();
   }
   sendMailView.Dispose();
}

在此示例中,senMailView.CurrentItem 是邮件类的实例。我们只需要调用 Send 方法即可完成工作。

这是我在 SO 中写过的最大的答案...我希望它对您有所帮助:D 如果您在使用它时遇到任何问题,请给我打电话。顺便说一句,我对我的英语不太自豪,所以如果文字有任何错误,请原谅我。

I did it before. I did it exporting programatically the report to a pdf to a specific location, then we email the pdf file and delete it. I will try to find the code for you (Not in home now)

EDITED:

Sorry for the later. Now i'm in home and I will give you some code blocks that I think will give you some help to acomplish your task. I will include some comments to the code so you can understand some things that are specific in my project. This code are tested and are working well in my clients, but i'm sure that it can be improved. Please, let me know if you can improve this code ;)

First of all, we will export the report to pdf.

private string ExportReportToPDF(string reportName)
{
   Warning[] warnings;
   string[] streamids;
   string mimeType;
   string encoding;
   string filenameExtension;
   byte[] bytes = ReportViewer1.LocalReport.Render(
      "PDF", null, out mimeType, out encoding, out filenameExtension,
       out streamids, out warnings);

   string filename = Path.Combine(Path.GetTempPath(), reportName);
   using (var fs = new FileStream(filename, FileMode.Create))
   {
      fs.Write(bytes, 0, bytes.Length);
      fs.Close();
   }

   return filename;
}

Now, we need a class that control the Mail system. Every mail system has their own caracteristics, so maybe you will need modify this class. The behaviour of the class is simple. You only need to fill the properties, and call the Send method. In my case, windows don't let me delete the pdf file once I send it (Windows says the file is in use), so I program the file to be deleted in the next reboot. Take a look to the delete method. Please, note that the send method use a cutom class named MailConfig. This is a small class that has some config strings like Host, User Name, and Password. The mail will be send using this params.

public class Mail
{
   public string Title { get; set; }
   public string Text { get; set; }
   public string From { get; set; }
   public bool RequireAutentication { get; set; }
   public bool DeleteFilesAfterSend { get; set; }

   public List<string> To { get; set; }
   public List<string> Cc { get; set; }
   public List<string> Bcc { get; set; }
   public List<string> AttachmentFiles { get; set; }

   #region appi declarations

   internal enum MoveFileFlags
   {
      MOVEFILE_REPLACE_EXISTING = 1,
      MOVEFILE_COPY_ALLOWED = 2,
      MOVEFILE_DELAY_UNTIL_REBOOT = 4,
      MOVEFILE_WRITE_THROUGH = 8
   }

   [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
   static extern bool MoveFileEx(string lpExistingFileName,
                                 string lpNewFileName,
                                 MoveFileFlags dwFlags);

   #endregion

   public Mail()
   {
      To = new List<string>();
      Cc = new List<string>();
      Bcc = new List<string>();
      AttachmentFiles = new List<string>();
      From = MailConfig.Username;
   }

   public void Send()
   {
      var client = new SmtpClient
      {
         Host = MailConfig.Host,
         EnableSsl = false,
      };

      if (RequireAutentication)
      {
         var credentials = new NetworkCredential(MailConfig.Username, 
                                                 MailConfig.Password);
         client.Credentials = credentials;
      }

      var message = new MailMessage
      {
         Sender = new MailAddress(From, From),
         From = new MailAddress(From, From)
      };

      AddDestinataryToList(To, message.To);
      AddDestinataryToList(Cc, message.CC);
      AddDestinataryToList(Bcc, message.Bcc);

      message.Subject = Title;
      message.Body = Text;
      message.IsBodyHtml = false;
      message.Priority = MailPriority.High;

      var attachments = AttachmentFiles.Select(file => new Attachment(file));
      foreach (var attachment in attachments)
         message.Attachments.Add(attachment);

      client.Send(message);

      if (DeleteFilesAfterSend)
         AttachmentFiles.ForEach(DeleteFile);
   }

   private void AddDestinataryToList(IEnumerable<string> from,
      ICollection<MailAddress> mailAddressCollection)
   {
      foreach (var destinatary in from)
         mailAddressCollection.Add(new MailAddress(destinatary, destinatary));
   }

   private void DeleteFile(string filepath)
   {
      // this should delete the file in the next reboot, not now.
      MoveFileEx(filepath, null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT);
   }
}

Now, you can create a form to ask for the destinataries, add some validation, etc, return to you an instance of the Mail class... or you can simply "hard code" the values and fill the class.

Here is the code that I use in a button to call this form, in my example it is named SendMailView.

private void BtnSendByMail_Click(object sender, EventArgs e)
{
   SendMailView sendMailView = new SendMailView();

   if (sendMailView.ShowDialog()== DialogResult.OK)
   {
      Mail mail = sendMailView.CurrentItem;
      mail.AttachmentFiles.Add(ExportReportToPDF("Invoice.pdf"));
      mail.DeleteFilesAfterSend = true;
      mail.RequireAutentication = true;
      mail.Send();
   }
   sendMailView.Dispose();
}

In this example senMailView.CurrentItem is the instance of the mail class. We simply need to call to the Send methis and the work is done.

This is the largest answer I ever wrote in SO... I hope it help you :D If you have any problem using it, call me. By the way, i'm not very proud of my english, so forgive me if the text has any mistake.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文