SwiftResend

Swift 5.7 Logo MIT License

SwiftResend 是一个 Swift 包,用于与 Resend 电子邮件发送平台 API 进行通信,适用于服务器端 Swift 应用程序。

设置

将依赖项添加到你的 Package.swift 文件中

dependencies: [
	...
	.package(url: "https://github.com/hsharghi/swift-resend.git", from: "1.0.0")
],
targets: [
    .target(name: "App", dependencies: [
        .product(name: "Resend", package: "swift-resend"),
    ]),

注册配置和提供程序

配置 HTTP 客户端和 Resend 客户端

let httpClient = HTTPClient(...)
let resendClient = ResendClient(httpClient: httpClient, apiKey: "YOUR_API_KEY")

用法

电子邮件客户端

你可以通过创建一个 ResendEmail 对象并返回电子邮件 ID 来发送单个电子邮件。

import Resend

let email: ResendEmail = .init(
    from: .init(email: "hadi@example.com", name: "Hadi"),
    to: ["hadi@domain.com"],
    subject: "running xctest",
    replyTo: [
        "hadi@example.com",
        "manager@example.com"
    ],
    text: "sending email from XCTest suit",
    headers: [
        .init(name: "X-Entity-Ref-ID", value: "234H3-44"),
        .init(name: "X-Entity-Dep-ID", value: "SALE-03"),
    ],
    attachments: [
        .init(content: .init(data: .init(contentsOf: .init(filePath: "path/to/a/file"))),
              filename: "sales.xlsx")
    ],
    tags: [
        .init(name: "priority", value: "medium"),
        .init(name: "department", value: "sales")
    ]
)

let id = try await resendClient.emails.send(email)

ResendEmail 同时支持 texthtml 内容。

你可以通过创建一个 ResendBatchEmail 对象一次发送多封电子邮件。批量发送不支持附件和标签。将返回一个电子邮件 ID 数组。

let emails = ResendBatchEmail(...)
let ids = try await resendClient.emails.sendBatch(emails)

检索电子邮件信息

你可以通过提供电子邮件 ID 来检索有关已发送电子邮件的信息。

let emailInfo = try await resendClient.emails.get(emailId: id)

管理受众

访问 AudienceClient 以通过 API 管理受众。 有关完整详细信息,请参阅 Resend 受众 API

let audience = try await resendClient.audiences.create(name: "marketing")

管理联系人

访问 ContactClient 以通过 API 管理联系人。 有关完整详细信息,请参阅 Resend 联系人 API

let contactId = try await resendClient.contacts.create(audienceId: audience.id,
                                                       email: "john@apple.com",
                                                       firstName: "John",
                                                       subscriptionStatus: true)

错误处理

如果由于任何原因导致 API 请求失败,则会抛出 ResendError。 确保像处理任何其他 throwing 函数一样捕获错误。

do {
    try await resendClient.emails.send(...)
}
catch let error as ResendError {
    print(error.message)
    print(error.suggestion)
}

当前 SDK 支持的 API

许可证

此包在 MIT 许可证下发布。 有关详细信息,请参阅 LICENSE