SwiftUI macOS应用HTML邮件发送问题:HTML内容无法渲染
解决macOS SwiftUI邮件发送HTML正文不渲染的问题
一、mailto:链接的局限
mailto:协议仅支持纯文本内容,不兼容HTML格式,因此macOS端邮件客户端会直接显示HTML源码,这种方式无法实现HTML渲染,建议放弃用它传递HTML正文。
二、使用NSSharingService实现HTML正文渲染
通过将HTML字符串转换为NSAttributedString再传递给NSSharingService,可让Mac端邮件客户端正确渲染格式,具体实现如下:
1. 编写HTML转富文本工具方法
import Foundation import AppKit extension String { func htmlToAttributedString() -> NSAttributedString? { guard let data = self.data(using: .utf8) else { return nil } do { return try NSAttributedString( data: data, options: [ .documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue ], documentAttributes: nil ) } catch { return nil } } }
2. SwiftUI中调用NSSharingService发送邮件
import SwiftUI struct ContentView: View { var body: some View { Button("Send Email") { sendHTMLMail() } } private func sendHTMLMail() { let osVersion = ProcessInfo.processInfo.operatingSystemVersionString let htmlBody = """ <strong>Please describe your issue below:</strong><br><br><hr><strong>Operating system:</strong> \(osVersion) """ guard let attributedBody = htmlBody.htmlToAttributedString() else { print("Failed to convert HTML to attributed string") return } let sharingService = NSSharingService(named: .composeEmail)! sharingService.recipients = ["me@domain.ltd"] sharingService.subject = "Test" sharingService.perform(withItems: [attributedBody]) } }
说明
- 转换后的
NSAttributedString会被邮件客户端识别为富文本,Mail.app和Outlook.app均可正确渲染加粗、换行、水平线等格式。 NSSharingService会自动处理富文本传递逻辑,无需手动设置Content-Type。
三、验证注意事项
- 确保HTML字符串格式规范,比如标签闭合、使用标准HTML元素(复杂HTML可能存在客户端兼容问题)。
- 测试前确认Mac端邮件客户端已配置有效账号,排除客户端本身配置问题导致的渲染异常。
内容的提问来源于stack exchange,提问作者markb
相关产品推荐
相关产品推荐

