gpt4 book ai didi

xcode - 从 swift osx 应用程序发送电子邮件

转载 作者:IT王子 更新时间:2023-10-29 05:47:13 39 4
gpt4 key购买 nike

我在从我的 osx swift 应用程序发送邮件时遇到问题。为了发送邮件,我使用了以下代码

import Foundation
import Cocoa


class sendemail : NSObject, NSSharingServiceDelegate{

func sendEmail() throws
{
print("enter email sending")
let body = "This is an email for auto testing throug code."
let shareItems = [body] as NSArray

let service = NSSharingService(named: NSSharingServiceNameComposeEmail)

service?.delegate = self
service?.recipients = ["abc@dom.com"]

let subject = "Vea Software"
service?.subject = subject

service?.performWithItems(shareItems as [AnyObject])
}

}

我从这个链接找到了源代码:https://www.veasoftware.com/posts/send-email-in-swift-xcode-62-os-x-1010-tutorial

但它不起作用。

我还尝试按照以下说明从终端发送邮件:

http://www.developerfiles.com/how-to-send-emails-from-localhost-mac-os-x-el-capitan/

它说:

postfix/postfix-script: fatal: the Postfix mail system is not running

请帮助我。

我可以从我配置好的 mac 邮件应用程序手动发送邮件。

我正在使用

xcode 7.3, osx el captain and swift 2.2

最佳答案

现代 swift :

func sendEmail(to recipients: [String], subject: String, body: String) {
let service = NSSharingService(named: .composeEmail)!
service.recipients = recipients
service.subject = subject
service.perform(withItems: [body])
}

// Usage
sendEmail(
to: ["abc@dom.com"],
subject: "Vea software",
body: "This is an email for auto testing through code."
)

本地用户必须使用 Mail.app 设置帐户。您还需要一个 NSApplication 实例来运行它。不能在 CLI 应用程序中执行此操作。如果您在控制台中看到以下错误,则表示您没有事件的 NSApplication 实例。

[default] 0 is not a valid connection ID

原始答案

这对我有用:

import Cocoa

class SendEmail: NSObject {
static func send() {
let service = NSSharingService(named: NSSharingServiceNameComposeEmail)!
service.recipients = ["abc@dom.com"]
service.subject = "Vea software"

service.performWithItems(["This is an email for auto testing through code."])
}
}

用法:

SendEmail.send()

关于xcode - 从 swift osx 应用程序发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37861111/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com