如何使用 Blazor 和 NetCore 5 在电子邮件中将剃刀组件作为正文发送?

How to send a razor component as body in an email using Blazor and NetCore 5?

如何使用 Blazor 服务器端和 NetCore 5 在电子邮件正文中发送 razor 组件? 在 MVC 中,我总是使用 RenderPartialViewToString() 但我不知道如何在 Blazor 中使用它。

注意:问题不在于如何使用 Blazor 发送电子邮件,而在于如何在电子邮件正文中包含 razor 页面。

// This is the code to send email. Works fine.
MimeMessage message = new MimeMessage();
MailboxAddress from = new MailboxAddress(model.FromName, model.FromAddress); message.From.Add(from);
MailboxAddress to = new MailboxAddress(model.ToName, model.ToAddress); message.To.Add(to);
message.Subject = model.Subject;

// Add email body and file attachments
BodyBuilder bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = model.Body;
//bodyBuilder.TextBody = "Hello World!";
message.Body = bodyBuilder.ToMessageBody();

//Connect and authenticate with the SMTP server
using (SmtpClient smtpClient = new SmtpClient())
{
   await InvokeAsync(() => { ShowSpinner = true; StateHasChanged(); });
   await smtpClient.ConnectAsync(model.SmtpServer, model.Port, true);
   await smtpClient.AuthenticateAsync(model.Username, model.Password);
   // Send email message
   await smtpClient.SendAsync(message);
   await InvokeAsync(() => { ShowSpinner = false; SuccessAlertMsg = "The email has been sent!"; StateHasChanged(); });
   await smtpClient.DisconnectAsync(true);
}

看来您真的只是在问如何获得 html,而不是如何建立电子邮件,对吧?我认为 JS Interop 会很容易做到。你可以把@ref放在你想要的任何项目上,我的只是垃圾测试数据。

GetHTML.js

window.getDivContents = (element) => {
    return element.innerHTML;
}

Page.razor

<div @ref="Ref">
    @{
        Random rand = new Random();
        int imax = rand.Next(4) + 1;
        for (int i = 0; i < imax; i++)
        {
            int jmax = rand.Next(3) + 1;
            <ul>
                @for (int j = 0; j < jmax; j++)
                {
                    <li>List @(i+1), Item @(j+1): #@Guid.NewGuid()</li>
                }
            </ul>
        }
    }
</div>
<button @onclick="GetHTML">Get HTML</button>
<div>
    @HTML
</div>

@code {
    ElementReference Ref { get; set; }
    string HTML { get; set; } = "";
    async Task GetHTML()
    {
        HTML = new(await JS.InvokeAsync<string>("getDivContents", Ref));
    }
}