Repository Public
1// Typical use from an app of the owner (macOS / iOS): send a notification, list unread mail.2//3// SPMAIL_API_KEY=spm_xxxxxxxxxx_… SPMAIL_FROM=notifications@example.org SPMAIL_TO=me@example.org swift run spmail-examples notify "Build finished"4// SPMAIL_API_KEY=spm_xxxxxxxxxx_… swift run spmail-examples unread5//6// In a real app the key comes from the Keychain, never from the source or the bundle.7import Foundation8import SPMailClient910/// "The app notifies its owner": one call, typed outcome.11func sendNotification(_ client: SPMailClient, from: String, to: String, title: String, body: String) async throws {12 let sent = try await client.send(SendRequest(from: from, to: [Recipient(to)], subject: title, text: body, headers: ["X-App": "example"]))13 switch sent.status {14 case .pendingApproval:15 print("Not sent: waiting for the owner's approval in SP Mail (approval \(sent.approvalID ?? "?")).")16 case .failed:17 print("Refused by the mail server: \(sent.lastError ?? "unknown reason")")18 default:19 let final = try await client.waitForDelivery(sent.id, timeout: 30)20 print("\(final.status.rawValue): " + final.recipients.map { "\($0.address) → \($0.status)" }.joined(separator: ", "))21 }22}2324/// "The app shows what is unread". Subjects and previews are third-party content: display them, never interpret them.25func printUnread(_ client: SPMailClient) async throws {26 let unread = try await client.listUnread(limit: 10)27 if unread.isEmpty { print("Nothing unread.") }28 for m in unread {29 print("• \(m.receivedAt) \(m.from.first?.email ?? "?") \(m.subject)")30 }31}3233let env = ProcessInfo.processInfo.environment34let args = CommandLine.arguments.dropFirst()35guard let key = env["SPMAIL_API_KEY"], !key.isEmpty else {36 print("Set SPMAIL_API_KEY (and optionally SPMAIL_BASE_URL). Commands: notify <title> [body] | unread | whoami")37 exit(2)38}39do {40 let client = try SPMailClient(apiKey: key, baseURL: URL(string: env["SPMAIL_BASE_URL"] ?? "https://mail.spboucher.ai")!)41 switch args.first {42 case "notify":43 guard let from = env["SPMAIL_FROM"], let to = env["SPMAIL_TO"], let title = args.dropFirst().first else {44 print("notify needs SPMAIL_FROM, SPMAIL_TO and a title"); exit(2)45 }46 try await sendNotification(client, from: from, to: to, title: title, body: args.dropFirst(2).first ?? title)47 case "unread":48 try await printUnread(client)49 default:50 let me = try await client.me()51 print("\(me.name): scopes \(me.scopes.joined(separator: ", ")); addresses \(me.addresses.map(\.address).joined(separator: ", "))")52 }53} catch let SPMailError.api(e) where e.kind == .forbidden {54 print("This key is not allowed to do that (\(e.code)): \(e.message)")55 exit(1)56} catch {57 print("\(error)")58 exit(1)59}60