Send HTML email via C# with SmtpClient

后端 未结 6 688
野趣味
野趣味 2020-11-28 08:43

How do I send an HTML email? I use the code in this answer to send emails with SmtpClient, but they\'re always plain text, so the link in the example message be

6条回答
  •  温柔的废话
    2020-11-28 09:01

    If you are using Mailkit,We can use TextBody,HtmlBody and Both for message body. Just write this code. It will help you

                MimeMessage mailMessage = new MimeMessage();
                mailMessage.From.Add(new MailboxAddress(senderName, sender@address.com));
                mailMessage.Sender = new MailboxAddress(senderName, sender@address.com);
                mailMessage.To.Add(new MailboxAddress(emailid, emailid));
                mailMessage.Subject = subject;
                mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
                mailMessage.Subject = subject;
                var builder = new BodyBuilder();
                builder.HtmlBody = "Hello There";
                mailMessage.Body = builder.ToMessageBody();            
                try
                {
                    using (var smtpClient = new SmtpClient())
                    {
                        smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
                        smtpClient.Authenticate("user@name.com", "password");
    
                        smtpClient.Send(mailMessage);
                        Console.WriteLine("Success");
                    }
                }
                catch (SmtpCommandException ex)
                {
                    Console.WriteLine(ex.ToString());              
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());                
                }
    

提交回复
热议问题