如何通过 Mimekit/Mailkit 发送 HTML 消息

How to send HTML message via Mimekit/Mailkit

BodyBuilder bodyBuilder = new BodyBuilder();
messageContent.Body = "<b>This is a test mail</b>";
bodyBuilder.HtmlBody = messageContent.Body;

我试图将我的 body 嵌入到 body 构建器中,但是当我收到电子邮件时,它返回了一个空的 body。如果 body 为空,我有一个异常会抛出一个参数..

像您一样使用 BodyBuilder 可能是最简单的方法。

var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = "<b>This is some html text</b>";
bodyBuilder.TextBody = "This is some plain text";

message.Body = bodyBuilder.ToMessageBody();

client.Send(message);

MimeKit Documentation - Creating Messages

var message = new MimeMessage();    
message.Body = new TextPart ("html") { Text = "<b>Test Message</b>" };

"A TextPart is a leaf-node MIME part with a text media-type. The first argument to the TextPart constructor specifies the media-subtype: plain, html, enriched, rtf, and xml."

如果你想严格,这里还有一个选择;

msg.Body = new TextPart(MimeKit.Text.TextFormat.Html) { Text = "<b>html content</b>" };
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = body;
bodyBuilder.TextBody = "-";

message.Body = bodyBuilder.ToMessageBody();

在某些邮件 ISP 中,您应该始终按值设置 bodyBuilder.TextBody。