How Can I Send Custom Emails with Variables in .NET 6?

282 Views Asked by At

Hello I'm creating an API, I found how send emails using Mailkit with Mailtrap for testing purposes. I share the code that I'm using:

public class EmailService : IEmailService
{
    public void SendEmail()
    {
        var email = new MimeMessage();
        email.From.Add(new MailboxAddress("", ""));
        email.To.Add(MailboxAddress.Parse(""));
        email.Subject = "Test Email";
        email.Body = new TextPart("plain")
        {
            Text = "Some Text"
        };
        
        using var smtp = new SmtpClient();
        smtp.Connect("", 2525, SecureSocketOptions.StartTls);
        smtp.Authenticate("", "");
        smtp.Send(email);
        smtp.Disconnect(true);
    }

}

So my biggest question it's if I wanna use the service that I made for every single email like verification email, reset password, etc. How can I add custom HTML in the body also use some variables if I want to send an email that says the username for example. At beginning I just thought save the body template in my database but If I wanna use some variables idk how can use it in that case.

I hope that you can help with this silly thing haha given me some advice or tip!

1

There are 1 best solutions below

0
On
email.Body = new TextPart("plain")
{
    Text = "Dear {ClientName},\r\nI am pleased to announce that you have won ${WinAmount}!!\r\n\r\nCongratulations!"
        .Replace("{ClientName}", "Bob")
        .Replace("{WinAmount}", "1,000,000")
};