使用 SelectPdf .NET 在电子邮件中附加 PDF,而不保存 PDF
本文关键字:PDF 保存 NET SelectPdf 电子邮件 使用 | 更新日期: 2023-09-27 18:37:19
我正在使用 SelectPdf 将 HTML 转换为 PDF 并将 PDF 发送到电子邮件中,而无需保存它并放入 MemoryStream,但电子邮件从未发送
如果我创建电子邮件而不附加 PDF,则始终发送。
这是我的代码:
public void SendEmail(string htmlBody, string email, string emailBody, string subject)
{
PdfDocument doc = null;
try
{
//Reading the html and converting it to Pdf
HtmlToPdf pdf = new HtmlToPdf();
doc = pdf.ConvertHtmlString(htmlBodyReservaPasajeros);
var streamPdf = new MemoryStream(doc.Save());
//creating the message
message.From = new MailAddress(ConfigurationManager.AppSettings[url + "Email"]);
message.To.Add(new MailAddress(email));
message.Subject = subject;
message.Body = HtmlBody;
message.IsBodyHtml = true;
if (doc != null)
{
message.Attachments.Add(new Attachment(streamPdf , "Prueba.pdf", "application/pdf"));
}
//Sending the email
...
//Closing
streamPdf.Close();
doc.Close();
}
catch (Exception e)
{
}
}
更新
我有两个问题:
首先:Gmail将电子邮件识别为跨度,但是...
第二:即便如此,我也不得不写文档。DetachStream() 因为 pdf 已损坏。此函数将对象内存流从 PdfDocument 中分离出来,并将其释放。
最后代码是下一个:
public void SendEmail(string htmlBody, string email, string emailBody, string subject)
{
PdfDocument doc = null;
try
{
//Reading the html and converting it to Pdf
HtmlToPdf pdf = new HtmlToPdf();
doc = pdf.ConvertHtmlString(htmlBodyReservaPasajeros);
var streamPdf = new MemoryStream(doc.Save());
**doc.DetachStream();**
//creating the message
message.From = new MailAddress(ConfigurationManager.AppSettings[url + "Email"]);
message.To.Add(new MailAddress(email));
message.Subject = subject;
message.Body = HtmlBody;
message.IsBodyHtml = true;
if (doc != null)
{
message.Attachments.Add(new Attachment(streamPdf , "Prueba.pdf", "application/pdf"));
}
//Sending the email
...
//Closing
streamPdf.Close();
doc.Close();
}
catch (Exception e)
{
}
}
这段代码对我有用.. !
public void SendEmail(string htmlBody, string email, string emailBody, string subject)
{
try
{
//Reading the html and converting it to Pdf
HtmlToPdf pdf = new HtmlToPdf();
PdfDocument doc = pdf.ConvertHtmlString(htmlBodyReservaPasajeros);
using (MemoryStream memoryStream = new MemoryStream())
{
doc.Save(memoryStream);
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
MailMessage message= new MailMessage();
message.From = new MailAddress(
ConfigurationManager.AppSettings[url + "Email"]
);
message.To.Add(new MailAddress(email));
message.Subject = subject;
message.Body = htmlBody;
message.IsBodyHtml = true;
message.Attachments.Add(new Attachment(
new MemoryStream(bytes),
"Prueba.pdf"
));
//Sending the email
. . .
}
doc.Close();
}
catch (Exception e)
{
// handle Exception
. . .
}
}
检查生成的内存流是否在开头具有当前位置。您可能需要设置如下内容:
streamPdf.Position = 0;