如何在 Swift 中打开邮件面板? Mac OS

How to open mail panel in Swift? Mac OS

在过去的几天里,我一直在努力寻找一种从我的应用程序发送电子邮件的方法。这是我目前使用的示例代码。它认为,通过使用这种方法,我可能无法处理我的应用程序将使用的计算机的邮件帐户设置不当的情况 运行,所以我考虑使用不同的方法。我想知道 mac os 是否有任何等效的 MessageUI。 mac os 是否有任何等效的 MessageUI。有什么想法吗?

有两种方法可以做到这一点:

  1. AppleScript 框架

  2. NSSharingService

用于撰写邮件的 NSSharingService:

let service = NSSharingService(named: NSSharingServiceNameComposeEmail)

service?.recipients = ["test@gmail.com"]
service?.subject = "Test Mail"
service?.performWithItems(["Test Mail body"])

启动邮件应用程序

如果您只想打开 Mail 应用程序,请尝试以下代码:

NSWorkspace.sharedWorkspace().launchApplication("Mail")

设置不当:

  • 如果系统上没有配置帐户,此代码将显示邮件配置 window
  • 当用户尝试发送邮件时,邮件应用程序会显示与设置不当相关的错误,因此您无需为此烦恼
  • 如果您想使用其他邮件应用程序,只需尝试您自己的邮件系统、本机邮件客户端或第三方邮件框架。

从终端尝试:

您可以使用 shell 脚本使用本机客户端发送邮件

mail -s "Hello" "test@gmail.com" <<EOF
Hello, Test!
EOF

对于Swift4,改动不大。

let service = NSSharingService(named: NSSharingService.Name.composeEmail)
service?.recipients = ["test@gmail.com"]
service?.subject = "Test Mail"
service?.perform(withItems: ["Test Mail body"])