从 Swift 脚本撰写新邮件



我需要一个脚本来编写带有给定脚本参数的新邮件。 这是我到目前为止得到的:

#!/usr/bin/env xcrun swift
import Foundation
import AppKit
func printHelpMessage() {
let helpMessage = "Script expects the following arguments: <recepient> <subject>"
print(helpMessage)
}
func composeMail() {
guard let service = NSSharingService(named: .composeEmail) else { return }
service.recipients = [recepient]
service.subject = subject
service.perform(withItems: ["Test Mail Body"])
}
guard CommandLine.argc == 3 else {
printHelpMessage()
exit(0)
}
let recepient = CommandLine.arguments[1]
let subject = CommandLine.arguments[2]
composeMail()

我收到的错误消息是

2020-06-10 12:05:34.938140+0200 ComposeMail[58079:3848327] [default] 0 is not a valid connection ID.
2020-06-10 12:05:34.952445+0200 ComposeMail[58079:3848327] [default] 0 is not a valid connection ID.
2020-06-10 12:05:34.952805+0200 ComposeMail[58079:3848327] [default] 0 is not a valid connection ID.

这可能是系统完整性保护吗?

我只是遇到了同样的问题,并将其追溯到没有初始化 NSApplication。

NSApplication 开发人员页面提到,在使用大多数 AppKit 类之前,需要对此进行初始化。 我构建了一个简单的应用程序,插入了我的电子邮件代码,它现在可以工作了。 不过,我还没有弄清楚如何作为一个纯粹的命令行应用程序完成此操作,这是我的目标,它看起来也像你的。

事实证明,当使用AppKit类时,必须使用AppDelegate实现NSApplication实例,即使这是一个脚本。

这是现在对我有用的东西,它既快速又脏,但可能是一个起点:

import AppKit
let app = NSApplication.shared
class AppDelegate: NSObject, NSApplicationDelegate {
var recepient:String?
var subject: String?
var mailBody: String?
var attachment: String?
func applicationDidFinishLaunching(_ notification: Notification) {
guard CommandLine.argc == 5 else {
printHelpMessage()
exit(0)
}
recepient = CommandLine.arguments[1]
subject = CommandLine.arguments[2]
mailBody = CommandLine.arguments[3]
attachment = CommandLine.arguments[4]
composeMail()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
exit(1)
}
}
func composeMail() {
guard let recepient = recepient,
let subject = subject,
let mailBody = mailBody,
let attachment = attachment,
let service = NSSharingService(named: .composeEmail)
else {
exit(2)
}
let attmtUrl = URL(fileURLWithPath: attachment).absoluteURL
service.recipients = [recepient]
service.subject = subject
service.perform(withItems: [mailBody, attmtUrl as URL])
}
func printHelpMessage() {
let helpMessage = "Script expects the following arguments: <recepient> <subject> <mail body> </path/to/attachment>"
print(helpMessage)
}
}
let delegate = AppDelegate()
app.delegate = delegate
app.run()

感谢@anthosr(见下面的答案(将我推向正确的方向!

免责声明:请注意,附加不适用于MS Outlook-由于超出我的原因,附件被忽略了。使用Apple Mail,它可以工作。

最新更新