Created C# Email Sending in Blazor Server App, Before using CKEditor 5 for Email body-Under fluent validation (OnValidSubmit), its working fine but After Using CKEditor 5 for Email Body, body field show empty after entered data.
Entered data in CKEditor 5 Body field, On Validation its showing body is empty, but without Validation for body it works, I expect it to work on Validation
EmailRequest EmailRequest { get; set; } = new();
private string? FileUploadError { get; set; }
private string? EmailSendResult { get; set; }
private string? EmailResultClass { get; set; } // Bootstrap class for success/error styling
async Task SendEmail()
{
// Fetch CKEditor content and assign it to the EmailRequest.Body
EmailRequest.Body = await JSRuntime.InvokeAsync<string>("getEditorContent", "editor");
// Now run the validation or proceed with sending the email
if (string.IsNullOrWhiteSpace(EmailRequest.Body))
{
EmailSendResult = "The email body cannot be empty.";
EmailResultClass = "alert-danger";
return; // Prevent email from being sent if the body is empty
}
try
{
var email = new MimeMessage();
// Set the From address
email.From.Add(MailboxAddress.Parse("EmailID"));
if (!string.IsNullOrWhiteSpace(EmailRequest.To))
{
foreach (var toAddress in EmailRequest.To.Split(',', StringSplitOptions.RemoveEmptyEntries))
{
email.To.Add(MailboxAddress.Parse(toAddress.Trim()));
}
}
// Set the Subject
email.Subject = EmailRequest.Subject ?? "No Subject";
// Create the body of the email
var bodyBuilder = new BodyBuilder
{
HtmlBody = EmailRequest.Body
};
email.Body = bodyBuilder.ToMessageBody();
// Send the email
using var smtp = new SmtpClient();
smtp.Connect("smtp.gmail.com", 587, MailKit.Security.SecureSocketOptions.StartTls);
smtp.Authenticate("emailID", "Password");
smtp.Send(email);
smtp.Disconnect(true);
// Show success message
EmailSendResult = "Email sent successfully!";
EmailResultClass = "alert-success";
}
catch (Exception ex)
{
// Show error message if something goes wrong
EmailSendResult = $"Failed to send email: {ex.Message}";
EmailResultClass = "alert-danger";
}
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
// Initialize CKEditor with the id of the textarea
await JSRuntime.InvokeVoidAsync("initializeCKEditor", "editor");
}
}
}
siva ranjani is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.