Home > Software design >  Unable to send a Razor template using FluentEmail in ASP.NET Core
Unable to send a Razor template using FluentEmail in ASP.NET Core

Time:09-25

I watched Tim Corey's video about FluentEmail. I tested his code and everything worked fine, but when I tried to implement it in Asp.Net Core I couldn't send any message using template. The only thing I could do was send a message using body.
I've seen some people also had the same problem, but I didn't find any solution.

public async Task SendEmailAsync() {
        var sender = new SmtpSender(() => new SmtpClient("smtp.gmail.com") {
            UseDefaultCredentials = false,
            Port = 587,
            Credentials = new NetworkCredential("email", "******"),
            EnableSsl = true
        });

        StringBuilder template = new();
        template.AppendLine("Dear @Model.FirstName,");
        template.AppendLine("<p>Thanks for purchasing @Model.ProductName. We hope you enjoy it.</p>");
        template.AppendLine("- The TimCo Team");

        Email.DefaultSender = sender;
        Email.DefaultRenderer = new RazorRenderer();

        var email = await Email
            .From("email")
            .To("email", "Sue")
            .Subject("Thanks!")
            .UsingTemplate(template.ToString(), new { FirstName = "Tim", ProductName = "Bacon-Wrapped Bacon" })
            .SendAsync();
    }

And I also added this line in .csproj file

<PreserveCompilationContext>true</PreserveCompilationContext>

CodePudding user response:

I found the issue. I just had to add a reference to:

Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
  • Related