c# Web mvc Send PDF without saving to disk and send by email

Asked

Viewed 512 times

0

Hello, I have an MVC web application and I have a method to send an email and I have to add a PDF that is dynamic, I have to attach it in this email without saving on disk.

Could someone help?

  • Share Email and PDF Generation Code.

  • We can help, but what’s the question exactly? Have you tried anything, use a Stream for example?

  • I just sent the pdf

1 answer

0

//In-memory PDF generation method

public static MemoryStream ArquivoTemporario()
    {
            HtmlToPdfBuilder builder = new HtmlToPdfBuilder(PageSize.LETTER);
            HtmlPdfPage page1 = builder.AddPage();

            string imagem = string.Empty;

            string titulo = "CONVOCAÇÃO DO FÓRUM";
            string txtparticipante = string.Empty;
            string txtconvidado = string.Empty;

            page1.AppendHtml("<table>");
            page1.AppendHtml("<thead>");
            page1.AppendHtml("<tr>");
            page1.AppendHtml("<th colspan='4'></th>");
            page1.AppendHtml("<th colspan='4'></th>");
            page1.AppendHtml("<th colspan='4' style='text-align: right;'>" + imagem + "</th>");
            page1.AppendHtml("</tr>");
            page1.AppendHtml("</thead>");
            page1.AppendHtml("</table>");

            page1.AppendHtml("<h2 align='center'><b><i>Relatório</i></b> </h2>");
            page1.AppendHtml("<br />");
            page1.AppendHtml("<table border='1'>");
            page1.AppendHtml("<thead>");
            page1.AppendHtml("<tr>");
            page1.AppendHtml("<th colspan='3'><strong>Tipo de Fórum:</strong> Duvidas</th>");
            page1.AppendHtml("<th><strong>Hora início</strong></th>");
            page1.AppendHtml("<th><strong>Hora término</strong></th>");
            page1.AppendHtml("<th><strong>Data</strong></th>");
            page1.AppendHtml("<th colspan='2'><strong>Local</strong></th>");
            page1.AppendHtml("</tr>");
            page1.AppendHtml("<tr>");
            page1.AppendHtml("<td colspan='3'><strong>Número de Fórum:</strong> </td>");
            page1.AppendHtml("<td> 00:00 </td>");
            page1.AppendHtml("<td> 00:00 </td>");
            page1.AppendHtml("<td>01/01/2018</td>");
            page1.AppendHtml("<th colspan='2'>Amazon</th>");
            page1.AppendHtml("</tr>");
            page1.AppendHtml("<tr>");
            page1.AppendHtml("<td colspan='4'><strong>Coordenador:</strong> Ana </td>");
            page1.AppendHtml("<td colspan='4'><strong>Secretário:</strong> Ana </td>");
            page1.AppendHtml("</tr>");
            page1.AppendHtml("<thead>");
            page1.AppendHtml("<tr colspan='8'>");
            page1.AppendHtml("<td><strong>Convidados:</strong> Ana </td>");
            page1.AppendHtml("</tr>");
            page1.AppendHtml("</thead>");
            page1.AppendHtml("<thead>");
            page1.AppendHtml("<tr colspan='8'>");
            page1.AppendHtml("<td><strong>Participantes:</strong> Ana </td>");
            page1.AppendHtml("</tr>");
            page1.AppendHtml("</thead>");


            page1.AppendHtml("<tr bgcolor='#E6E6FA'>");
            page1.AppendHtml("<td colspan='8'><strong>Descrição</strong></td>");
            page1.AppendHtml("</tr>");
            page1.AppendHtml("<tr>");
            page1.AppendHtml("<td colspan='8'> Descrição </td>");
            page1.AppendHtml("</tr>");
            page1.AppendHtml("<tr bgcolor='#E6E6FA'>");
            page1.AppendHtml("<td colspan='4'><strong>Pautas a serem apresentadas/discutidas.</strong></td>");
            page1.AppendHtml("<td colspan='2'><strong>Responsável</strong></td>");
            page1.AppendHtml("<td colspan='2'><strong>Duração</strong></td>");
            page1.AppendHtml("</tr>");
            page1.AppendHtml("<tr colspan='8'>");
            page1.AppendHtml("</tr>");
            page1.AppendHtml("<tr bgcolor='#E6E6FA'>");
            page1.AppendHtml("<td colspan='3'><strong>Pendências</strong></td>");
            page1.AppendHtml("<td colspan='1'><strong>Responsável</strong></td>");
            page1.AppendHtml("<td colspan='1'><strong>Prazo inicial</strong></td>");
            page1.AppendHtml("<td colspan='1'><strong>Prazo final</strong></td>");
            page1.AppendHtml("<td colspan='2'><strong>Status</strong></td>");
            page1.AppendHtml("</tr>");
            page1.AppendHtml("<tr colspan='8'>");
            page1.AppendHtml("</tr>");
            page1.AppendHtml("</tbody>");
            page1.AppendHtml("</table>");
            builder.AddStyle("th", "font-size: 10px;");
            builder.AddStyle("td", "font-size: 10px;");

            byte[] file = builder.RenderPdf();

            byte[] buffer = new byte[4096];

            MemoryStream pdfStream = new MemoryStream(file);

            pdfStream.Read(buffer, 0, buffer.Length);


            return pdfStream;
    }

//Method to send the e-mail

public void EnviarEmail(string destinatario, string sub, string body)
{
            try
            {
String path = System.AppDomain.CurrentDomain.BaseDirectory.ToString();

string server = path + "Content\\Uploads\\Email\\";

                MemoryStream pdfConvocacao = Email.ArquivoTemporario();

                string cabecalho = ConfigurationManager.AppSettings["CabecalhoEmail"];
                string remetenteEmail = ConfigurationManager.AppSettings["Email"];
                string senha = ConfigurationManager.AppSettings["Senha"];
                string dataHoraInicial = "";
                string dataHoraFinal = "";
                string agenda = "Agenda.ics";
                string schLocation = "";
                string schSubject = "";
                string schDescription = "";

                System.DateTime schBeginDate = Convert.ToDateTime(dataHoraInicial);
                System.DateTime schEndDate = Convert.ToDateTime(dataHoraFinal);

                String[] contents = { "BEGIN:VCALENDAR",
                              "PRODID:-//Flo Inc.//FloSoft//EN",
                              "BEGIN:VEVENT",
                              "DTSTART:" + schBeginDate.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"), 
                              "DTEND:" + schEndDate.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"), 
                              "LOCATION:" + schLocation, 
                              "DESCRIPTION;ENCODING=QUOTED-PRINTABLE:" + schDescription,
                              "SUMMARY:" + schSubject, "PRIORITY:3", 
                              "END:VEVENT", "END:VCALENDAR" };

                System.IO.File.WriteAllLines(server + agenda, contents);
                Attachment mailAttachment = new Attachment(server + agenda);
                MailMessage mailMessage = new MailMessage();
                mailMessage.To.Add(destinatario);
                mailMessage.From = new MailAddress(remetenteEmail, "Instituto Empresariar", System.Text.Encoding.UTF8);
                mailMessage.Subject = sub;
                mailMessage.Body = cabecalho + "<h3>" + body + "</h3>";
                mailMessage.IsBodyHtml = true;
                mailMessage.Priority = MailPriority.High;
                mailMessage.Attachments.Add(mailAttachment);

                byte[] bytes = pdfConvocacao.ToArray();
                pdfConvocacao.Close();

                mailMessage.Attachments.Add(new Attachment(new MemoryStream(bytes), "Convocação.pdf"));

                SmtpClient smtp = new SmtpClient();
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new NetworkCredential(remetenteEmail, senha);
                smtp.Port = Convert.ToInt32(ConfigurationManager.AppSettings["PortaEmail"]);
                smtp.Host = ConfigurationManager.AppSettings["HostEmail"];
                smtp.EnableSsl = true;
                smtp.Send(mailMessage);

                mailAttachment.Dispose();
                mailMessage.Dispose();
                DeletaArquivo(server, agenda);
                DeletaArquivo(server, "Convocação.pdf");
            }
            catch (Exception ex)
            {

            }
        }
  • Hi Carol. It would be interesting if you could explain how these methods work and how they can be implemented, in this way you would make it easier for users who are going through the same problems.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.