reactjsasp.netasp.net-core-webapihtml-emailmailkit

How to send HTML email with ASP .NET Core 7


I need to send the email with HTML tags with ASP .NET Core 7 using SMTP and MailKit. I have already send emails with minimum html tags like . But I need to send with with headers and footers with images(logos). This is the API scheme. API request

And I need to send a HTML email like below Email sample

I inserted the html code like thissending email

But it gives a error like this. Error I encounter

My problem is I don't know how to insert html code inside the body which contain CSS and images. How to send a email like that? Is this error occur due to the API code I wrote or are there another way to do that?

This is the email service code I have written in .net

using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using MimeKit.Text;

namespace AgrarianTradeSystemWebAPI.Services.EmailService
{
    public class EmailService : IEmailService
    {
        private readonly IConfiguration _config;

        public EmailService(IConfiguration config)
        {
            _config = config;
        }

        public void SendEmail(EmailDto request)
        {
            var email = new MimeMessage();
            email.From.Add(MailboxAddress.Parse(_config.GetSection("EmailConfig:EmailUsername").Value));
            email.To.Add(MailboxAddress.Parse(request.To));
            email.Subject = request.Subject;
            email.Body = new TextPart(TextFormat.Html) { Text = request.Body };
            using var smtp = new SmtpClient();
            smtp.Connect(_config.GetSection("EmailConfig:EmailHost").Value, 587, SecureSocketOptions.StartTls);
            smtp.Authenticate(_config.GetSection("EmailConfig:EmailUsername").Value, _config.GetSection("EmailConfig:EmailPassword").Value);
            smtp.Send(email);
            smtp.Disconnect(true);
        }
    }
}

The DTO I used for this is

public class EmailDto
{
    public string To { get; set; } = string.Empty;
    public string Subject { get; set; } = string.Empty;
    public string Body { get; set; } = string.Empty;
}

In React JS I used axios to send emails when user registered to the system.

try {
        const response = await axios.post('https://localhost:7144/Auth/register', formData);
        console.log('Server Response:', response.data);
        if (response.status === 200) {
            const emailResponse = await axios.post('https://localhost:7144/api/Email', emaildata);
            console.log('Email Response:', emailResponse.data);
        }
    } catch (error) {
        console.error('Error:', error.response.data);
        if(error.response.data === "Email exist"){
            alert('Error: Email already exists and you can not register from existing email address');
        }
    }

Solution

  • I need to send the email with HTML tags with ASP .NET Core 7 using SMTP and MailKit. I have already send emails with minimum html tags like . But I need to send with with headers and footers with images(logos).

    Well, it would be very convenient if you could have been shared, what html you were sent along with your email attachment. But you have missed that.

    However, according to your error message screenshot:

    enter image description here

    That indicates, something went wrong within your html syntax or string the way you have sent that. So I think, you should first test that in html visualizer or you have to check if there's any error remains in the html email body. If any incorrect string or syntax remains within your CSS attribute or html tag you might get the same error, so please double check that.

    My problem is I don't know how to insert html code inside the body which contain CSS and images. How to send a email like that?

    Regarding custom eamil body like, your CSS or image, you could use inline css with required attribute within the style tag you can define but it has to be within the same place. No external reference shouldn't put in which may break. On the other hand, for the image, you could use base64 image conversion, the way we used in html image src. Or you could directly use the image path located in wwwroot folder. But base64 is more suitable.

    You could do as following:

    var bodyBuilder = new BodyBuilder();
            bodyBuilder.HtmlBody = @"
                <html>
     <head>
        <style>
            /* Your CSS styles here */
        </style>
    </head>
    <body>
        <h1 style='color:red;'>Hello!</h1>
        <p>This is a sample HTML email with a base64-encoded image.</p>
        <img src="data:image/png;base64,iVBORw0KGgoA_Your_Base_64_Code_fv/X6F4MHQC0/0PyyAAAAAElFTkSuQmCC" alt="Base64 Encoded Logo">
    </body>
    </html>";
    

    After building above html string, then you can pass/bind it within your email.Body

    Output:

    When then eamil would sent, out should be as like below:

    enter image description here

    Note: If you need additional assistance or example, please refer to this official document. Also this one might be helful as well.