Click here to Skip to main content
14,691,808 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using Rotativa to convert my view to pdf. I would like to send that generated pdf as an email attachment (without having to download it first to disk).

I've been following a bunch of tutorials to do this but I just keep going round in circles. I would much appreciate any help I can get.

What I have tried:

public async Task<iactionresult>SomeReport()
    {
    ...
    return new ViewAsPdf (report)
    }
    return view();


    MemoryStream memoryStream = new MemoryStream();

    MimeMessage msg = new MimeMessage();
    MailboxAddress from = new MailboxAddress ("Name", "emailAddress")
    msg.From.Add(from);
    MailboxAddress to = new MailboxAddress ("Name", "emailAddress")
    msg.From.Add(to);
    BodyBuilder bd = new BodyBuilder();
    bb.HtmlBody ="some text";
    bb.Attachments.Add("attachmentName", new MemoryStream());
    msg.Body = bb.ToMessageBody();
    SmtpClient smtp = new SmtpClient();
    smtp.Connect("smtp.gmail.com",465, true);
    smtp.Authenticate("emailAddress", "Pwd");
    smtp.Send(msg);
    smtp.Disconnect(true);
    smtp.Dispose();
Posted
Updated 15-Aug-20 22:29pm
v2

1 solution

Referring to following documents about your use case on how to get the PDF:
Creating PDF In ASP.NET Core MVC Using Rotativa.AspNetCore[^]
How to create PDF from Asp.net MVC with RotativaHQ[^]

Once that is in place, code snippet like below should do the job:
var attachment = new Attachment(new MemoryStream(pdfBytes), PdfFileName); //this is from the articles referred above

MailMessage mailMessage = new MailMessage();
mailMessage.To.Add(new MailAddress("to@to.t"));
mailMessage.From = new MailAddress("from@from.f");
mailMessage.Subject = "my pdf attached";
mailMessage.Attachments.Add(attachment);

SmtpClient smtp = new SmtpClient();
smtp.Connect("smtp.gmail.com",465, true);
smtp.Authenticate("emailAddress", "Pwd");
smtp.Send(mailMessage);

PS: Make sure to take care of memory release for the objects.

UPDATE: A better way to wireup your email configurations/sending email: How to Send an Email with Attachments in ASP.NET Core - Code Maze[^]

Try out!
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900