使用MimeKit和MailKit向Outlook发送RTF邮件正文遇问题求助
解决MailKit发送RTF正文被识别为附件的问题
问题原因
单独将RTF文本设为邮件唯一Body时,多数邮件客户端无法识别text/rtf作为正文内容,会自动将其解析为未知类型附件。邮件标准中,默认优先识别text/plain或text/html作为正文,RTF需要通过多部分MIME结构正确标记为可选正文。
解决方案
方案一:用多部分替代容器兼容多种格式(推荐)
通过MultipartAlternative同时添加纯文本、HTML和RTF版本,邮件客户端会自动选择支持的格式显示,彻底避免RTF被当作附件。
var message = new MimeMessage(); message.From.Add(new MailboxAddress("Joey", "joey@sendrtf.com")); message.To.Add(new MailboxAddress("Yash", "yash@sendrtf.com")); message.Subject = $"How you doin? - {DateTime.Now}"; // 准备三种格式的内容 string rtfBody = @"{\rtf1\ansi\deff0{\colortbl;\red0\green0\blue0;\red255\green0\blue0;} This line is the default color\line \cf2 This line is red\line \cf1 This line is the default color}"; string plainTextBody = "This line is the default color\nThis line is red\nThis line is the default color"; string htmlBody = "<p>This line is the default color</p><p style='color:red'>This line is red</p><p>This line is the default color</p>"; // 创建多部分替代容器 var multipart = new MultipartAlternative(); // 添加纯文本 fallback(必选,兼容所有客户端) multipart.Add(new TextPart(TextFormat.Plain) { Text = plainTextBody }); // 添加HTML版本(适配现代客户端) multipart.Add(new TextPart(TextFormat.Html) { Text = htmlBody }); // 添加RTF版本 multipart.Add(new TextPart(TextFormat.Rtf) { Text = rtfBody }); // 设置邮件主体 message.Body = multipart; SendMail(message);
方案二:强制标记RTF为内联正文(仅适合支持RTF的客户端)
如果只需要发送RTF格式,显式设置ContentDisposition为inline,告诉客户端这是内联正文而非附件:
var message = new MimeMessage(); message.From.Add(new MailboxAddress("Joey", "joey@sendrtf.com")); message.To.Add(new MailboxAddress("Yash", "yash@sendrtf.com")); message.Subject = $"How you doin? - {DateTime.Now}"; string rtfBody = @"{\rtf1\ansi\deff0{\colortbl;\red0\green0\blue0;\red255\green0\blue0;} This line is the default color\line \cf2 This line is red\line \cf1 This line is the default color}"; var rtfPart = new TextPart(TextFormat.Rtf) { Text = rtfBody }; // 关键:标记为内联正文 rtfPart.ContentDisposition = new ContentDisposition(ContentDisposition.Inline); // 可选:指定字符集提升兼容性 rtfPart.ContentType.CharSet = "utf-8"; message.Body = rtfPart; SendMail(message);
补充提示
- 方案一兼容性最强,建议优先使用,不支持RTF的客户端会自动降级显示HTML或纯文本
- 单独发送RTF的场景非常有限,尽量遵循邮件标准提供多格式选项
- 部分老旧客户端可能仍不识别RTF正文,纯文本 fallback 是必要的
内容的提问来源于stack exchange,提问作者adrien there
相关产品推荐
相关产品推荐

