向SMTP服务器轻松传递email – Hedwig

codeday· 2019-09-23
本文来自 codeday ,作者 codeday

Hedwig是一个Swift包,支持一套高等级的API,让你能够向SMTP服务器轻松传递email。如果你计划从你的下一个Swift服务器app中传递email,Hedwig时一个好的选择。

Features

  • 与所有SMTP服务器链接,无论是普通的,SSL或者TLS端口。
  • 与PLAIN?,?CRAM-MD5?,?LOGIN?或者?XOAUTH2 的认证。
  • MD5,LOGIN或者XOAUTH2。
  • 传送带有HTML正文及附件的email。
  • 队列邮件发送,不阻塞应用程序
  • 与Swift包一起工作,使用最新的Swift语法并跨平台。
  • 全测试和文档 .

安装

在Package.swift中添加这个库的url:

import PackageDescription

let package = Package(
    name: "YourAwesomeSoftware",
    dependencies: [
        .Package(url: "https://github.com/onevcat/Hedwig.git", 
                 majorVersion: 1)
    ]
)

使用方法

只通过email传递文本

let hedwig = Hedwig(hostName: "smtp.example.com", user: "foo@bar.com", password: "password")
let mail = Mail(
        text: "Across the great wall we can reach every corner in the world.", 
        from: "onev@onevcat.com", 
        to: "foo@bar.com", 
        subject: "Hello World"
)

hedwig.send(mail) { error in
    if error != nil { /* Error happened */ }
}

传送 HTML 邮箱

let hedwig = Hedwig(hostName: "smtp.example.com", user: "foo@bar.com", password: "password")
let attachment = Attachment(htmlContent: "<html><body><h1>Title</h1><p>Content</p></body></html>")
let mail = Mail(
        text: "Fallback text", 
        from: "onev@onevcat.com", 
        to: "foo@bar.com", 
        subject: "Title", 
        attachments: [attachment]
)
hedwig.send(mail) { error in
    if error != nil { /* Error happened */ }
}

CC 和 BCC

let hedwig = Hedwig(hostName: "smtp.example.com", user: "foo@bar.com", password: "password")
let mail = Mail(
        text: "Across the great wall we can reach every corner in the world.", 
        from: "onev@onevcat.com", 
        to: "foo@bar.com",
        cc: "Wei Wang <onev@onevcat.com>, tom@example.com", // Addresses will be parsed for you
        bcc: "My Group: onev@onevcat.com, foo@bar.com;",    // Even with group syntax
        subject: "Hello World"
)
hedwig.send(mail) { error in
    if error != nil { /* Error happened */ }
}

使用不同的SMTP设置

let hedwig = Hedwig(
        hostName: "smtp.example.com", 
        user: "foo@bar.com", 
        password: "password",
        port: 1234,     // Determined from secure layer by default
        secure: .plain, // .plain (Port 25) | .ssl (Port 465) | .tls (Port 587) (default)
        validation: .default, // You can set your own certificate/cipher/protocols
        domainName: "onevcat.com", // Used when saying hello to STMP Server
        authMethods: [.plain, .login] // Default: [.plain, .cramMD5, .login, .xOauth2]        
)