Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send email using Html template with MailKit in .net core application

I am sending an email from .net core application using MailKit, and it will sent it successfully.

But I want to use HTML template to send email with MailKit in .Net core.

Here are the code currently sending email with static body part

 var emailMessage = new MimeMessage();
        if (!string.IsNullOrWhiteSpace(cc))
        {
            emailMessage.Cc.Add(new MailboxAddress(cc));
        }
        else if (!string.IsNullOrWhiteSpace(EmailUserNameCC))
        {
            emailMessage.Cc.Add(new MailboxAddress(EmailUserNameCC));
        }
        if (!string.IsNullOrWhiteSpace(EmailUserNameBCC))
        {
            emailMessage.Bcc.Add(new MailboxAddress(EmailUserNameBCC));
        }

        emailMessage.From.Add(new MailboxAddress(mailFrom));
        emailMessage.To.Add(new MailboxAddress(mailTo));
        emailMessage.Subject = subject;
        if (!string.IsNullOrWhiteSpace(replyTo))
        {
            emailMessage.InReplyTo = replyTo;
        }
        var builder = new BodyBuilder();// { TextBody = message };
        builder.HtmlBody = message;

        if (attachments != null && attachments.Count > 0)
        {
            foreach (var item in attachments)
            {
                builder.Attachments.Add(item.Key, item.Value);
            }

            builder.HtmlBody = builder.HtmlBody + " \n" + " PFA";

        }
        var multipart = new Multipart("mixed");
        multipart.Add(new TextPart("html") { Text = message });

        emailMessage.Body = builder.ToMessageBody();
        using (var client = new SmtpClient())
        {
            var credentials = new NetworkCredential
            {
                UserName = EmailUserName,
                Password = EmailPassword
            };

            if (!client.IsConnected)
            {
                client.Connect(SmtpHost, Convert.ToInt32(EmailHostPort));
                client.Authenticate(EmailUserName, EmailPassword);
            }
            client.MessageSent += c_EmailReached;

            client.Send(emailMessage);
        }

Now, I want to use HTML template to replace body part. So how can I use HTML Template with MailKit in .Net Core ?

Additional:

-> Also the special characters are not showing in actual email after sending email with html template. For some special characters it is displaying � . So how can I resolved this, to show special characters also.

Thanks.

like image 205
Herin Avatar asked Feb 27 '17 06:02

Herin


1 Answers

You can use StreamReader to read the source file and assign it to your builder.HtmlBody.

using (StreamReader SourceReader = System.IO.File.OpenText(path to your file))
{
   builder.HtmlBody = SourceReader.ReadToEnd();
}
like image 164
Rachit Tyagi Avatar answered Nov 04 '22 17:11

Rachit Tyagi