Smtp

Build Status Swift 5.2 Vapor 4 Swift Package Manager Platforms OS X | Linux

📧 Vapor Web 框架的 SMTP 协议支持。

此框架仅依赖 VaporSwiftNIO 包。SwiftNIO 支持的灵感来自 Apple 示例: Swift NIO 示例

功能特点

入门指南

您需要将库添加到 Package.swift 文件中

.package(url: "https://github.com/Mikroservices/Smtp.git", from: "3.0.0")
.target(name: "App", dependencies: [
    .product(name: "Vapor", package: "vapor"),
    .product(name: "Smtp", package: "Smtp")
])

设置 SMTP 服务器配置(例如,在 main.swift 文件中)

import Smtp

var env = try Environment.detect()
try LoggingSystem.bootstrap(from: &env)

let app = Application(env)
defer { app.shutdown() }

app.smtp.configuration.host = "smtp.server"
app.smtp.configuration.signInMethod = .credentials(username: "johndoe", password: "passw0rd")
app.smtp.configuration.secure = .ssl

try configure(app)
try app.run()

使用 SMTP 客户端 (EventLoopFuture)

let email = try! Email(from: EmailAddress(address: "john.doe@testxx.com", name: "John Doe"),
                  to: [EmailAddress(address: "ben.doe@testxx.com", name: "Ben Doe")],
                  subject: "The subject (text)",
                  body: "This is email body.")

request.smtp.send(email).map { result in
    switch result {
    case .success:
        print("Email has been sent")
    case .failure(let error):
        print("Email has not been sent: \(error)")
    }  
}

您也可以直接通过 application 类发送电子邮件。

app.smtp.send(email).map { result in
    ...
}

使用 SMTP 客户端 (async/await)

您必须在 Package.swift 文件中将 macOS 12 设置为目标(以及工具版本 5.5)。

    platforms: [
        .macOS(.v12)
    ],

然后您可以使用 SMTP 方法的 async/await 替代方案。

let email = try! Email(from: EmailAddress(address: "john.doe@testxx.com", name: "John Doe"),
                  to: [EmailAddress(address: "ben.doe@testxx.com", name: "Ben Doe")],
                  subject: "The subject (text)",
                  body: "This is email body.")

try await request.smtp.send(email)

您也可以直接通过 application 类发送电子邮件。

try await app.smtp.send(email)

故障排除

您可以使用 logHandler 来处理和打印从电子邮件服务器发送/接收的所有消息。

request.smtp.send(email) { message in
    print(message)
}.map { result in
    ...
}

开发

克隆存储库后,您可以在 Xcode 中打开它。

$ git clone https://github.com/Mikroservices/Smtp.git
$ cd Smtp
$ open Package.swift

您可以直接在 Xcode 中构建和运行测试。

测试

单元(集成)测试需要正确的电子邮件凭据。凭据未签入到存储库中。如果您想运行单元测试,则必须使用您的 mailtrap 帐户和/或其他电子邮件提供商凭据。

您只需替换 Tests/SmtpTests/SmtpTests.swift 文件中的配置部分即可。

许可证

本项目根据 MIT 许可证的条款获得许可。