I am using SelectPdf to convert a HTML to PDF and sending the PDF in an email without saving it and putting into a MemoryStream, but the email is never sent
If I create an Email without attaching the PDF is always sent.
Here my code:
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)
{
}
}
UPDATE
I had two problems:
First: gmail recognized the email as span, but...
Second:Even so I had to write doc.DetachStream() since the pdf was corrupted. This function detach the object memoryStream from PdfDocument and set it free.
in the end the code is the next:
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)
{
}
}
This Code worked for me.. !
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
. . .
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With