Fra*_*ran 3 .net html c# pdf email
我正在使用 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)
{
}
}
Run Code Online (Sandbox Code Playgroud)
更新
我有两个问题:
首先:gmail 将电子邮件识别为跨度,但是...
第二:即使这样我也不得不写doc.DetachStream()因为 pdf 已损坏。此函数从 PdfDocument 中分离对象 memoryStream 并将其释放。
最后的代码是下一个:
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)
{
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
此代码对我有用..!
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
. . .
}
}
Run Code Online (Sandbox Code Playgroud)