本项目提供了一个 SMTP 库。
此包使用 Swift Package Manager 构建,是 Perfect 项目的一部分。
请确保您已安装并激活最新的 Swift 4.1.1 工具链。
请确保已在 Ubuntu 16.04 上安装 libssl-dev
$ sudo apt-get install libssl-dev
在使用 Perfect-SMTP 编写代码之前,请先尝试使用 curl 命令行的 SMTP 示例。
此命令行工具可以帮助您了解 SMTP 协议以及您将要使用的目标服务器。
要使用 SMTP 类,请修改 Package.swift 文件并添加以下依赖项
.package(url: "https://github.com/PerfectlySoft/Perfect-SMTP.git", from: "3.0.0")
然后请将 SMTP 库导入到 swift 源代码中
import PerfectSMTP
Perfect SMTP 包含三个不同的数据结构:SMTPClient、Recipient 和 EMail。
SMTPClient 对象是一个用于存储邮件服务器登录信息的数据结构
let client = SMTPClient(url: "smtp://mailserver.address", username: "someone@some.where", password:"secret")
Recipient 对象是一个用于存储姓名和电子邮件地址的数据结构
let recipient = Recipient(name: "Someone's Full Name", address: "someone@some.where")
使用 email 对象来撰写和发送电子邮件。 请查看以下示例代码
// initialize an email draft with mail connection / login info
var email = EMail(client: client)
// set the title of email
email.subject = "Mail Title"
// set the sender info
email.from = Recipient(name: "My Full Name", address: "mynickname@my.home")
// fill in the main content of email, plain text or html
email.html = "<h1>Hello, world!</h1><hr><img src='http://www.perfect.org/images/perfect-logo-2-0.svg'>"
// set the mail recipients, to / cc / bcc are all arrays
email.to.append(Recipient(name: "First Receiver", address: "someone@some.where"))
email.cc.append(Recipient(name: "Second Receiver", address: "someOtherOne@some.where"))
email.bcc.append(Recipient(name: "An invisible receiver", address: "someoneElse@some.where"))
// add attachments
email.attachments.append("/path/to/file.txt")
email.attachments.append("/path/to/img.jpg")
// send the email and call back if done.
do {
try email.send { code, header, body in
/// response info from mail server
print(code)
print(header)
print(body)
}//end send
}catch(let err) {
/// something wrong
}
content
的别名 (与 content
共享相同的变量)performFully()
以获取更多信息可以在这里找到一个演示: Perfect SMTP Demo
我们收到了很多关于 google smtp 示例的请求,感谢 @ucotta @james 以及来自 @iamjono 的 Perfect 官方支持,此说明可能有助于构建 gmail 应用程序smtps://smtp.gmail.com
,您可能需要在 google 设置中 “启用安全性较低的应用的访问权限”。*
请查看下面的 SMTPS 代码,注意唯一的区别是 URL 模式
import PerfectSMTP
let client = SMTPClient(url: "smtps://smtp.gmail.com", username: "yourname@gmail.com", password:"yourpassword")
var email = EMail(client: client)
email.subject = "a topic"
email.content = "a message"
email.cc.append(Recipient(address: "who@where.com"))
do {
try email.send { code, header, body in
/// response info from mail server
print(code)
}//end send
}catch(let err) {
/// something wrong
}
有关 Perfect 项目的更多信息,请访问 perfect.org。