• Stars
    star
    249
  • Rank 156,995 (Top 4 %)
  • Language
    Swift
  • License
    Apache License 2.0
  • Created about 7 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Swift SMTP client

Swift-SMTP

Swift-SMTP bird

Swift SMTP client.

Build Status macOS Linux Apache 2

Features

  • Connect securely through SSL/TLS when needed
  • Authenticate with CRAM-MD5, LOGIN, PLAIN, or XOAUTH2
  • Send emails with local file, HTML, and raw data attachments
  • Add custom headers
  • Documentation

Swift Version

macOS & Linux: Swift 5.2 or above.

Installation

You can add SwiftSMTP to your project using Swift Package Manager. If your project does not have a Package.swift file, create one by running swift package init in the root directory of your project. Then open Package.swift and add SwiftSMTP as a dependency. Be sure to add it to your desired targets as well:

// swift-tools-version:4.0

import PackageDescription

let package = Package(
    name: "MyProject",
    products: [
        .library(
            name: "MyProject",
            targets: ["MyProject"]),
    ],
    dependencies: [
        .package(url: "https://github.com/Kitura/Swift-SMTP", .upToNextMinor(from: "5.1.0")),    // add the dependency
    ],
    targets: [
        .target(
            name: "MyProject",
            dependencies: ["SwiftSMTP"]),                                                           // add targets
        .testTarget(                                                                                // note "SwiftSMTP" (NO HYPHEN)
            name: "MyProjectTests",
            dependencies: ["MyProject"]),
    ]
)

After adding the dependency and saving, run swift package generate-xcodeproj in the root directory of your project. This will fetch dependencies and create an Xcode project which you can open and begin editing.

Migration Guide

Version 5.0.0 brings breaking changes. See the quick migration guide here.

Usage

Initialize an SMTP instance:

import SwiftSMTP

let smtp = SMTP(
    hostname: "smtp.gmail.com",     // SMTP server address
    email: "[email protected]",        // username to login
    password: "password"            // password to login
)

TLS

Additional parameters of SMTP struct:

public init(hostname: String,
            email: String,
            password: String,
            port: Int32 = 587,
            tlsMode: TLSMode = .requireSTARTTLS,
            tlsConfiguration: TLSConfiguration? = nil,
            authMethods: [AuthMethod] = [],
            domainName: String = "localhost",
            timeout: UInt = 10)

By default, the SMTP struct connects on port 587 and sends mail only if a TLS connection can be established. It also uses a TLSConfiguration that uses no backing certificates. View the docs for more configuration options.

Send email

Create a Mail object and use your SMTP handle to send it. To set the sender and receiver of an email, use the User struct:

let drLight = Mail.User(name: "Dr. Light", email: "[email protected]")
let megaman = Mail.User(name: "Megaman", email: "[email protected]")

let mail = Mail(
    from: drLight,
    to: [megaman],
    subject: "Humans and robots living together in harmony and equality.",
    text: "That was my ultimate wish."
)

smtp.send(mail) { (error) in
    if let error = error {
        print(error)
    }
}

Add Cc and Bcc:

let roll = Mail.User(name: "Roll", email: "[email protected]")
let zero = Mail.User(name: "Zero", email: "[email protected]")

let mail = Mail(
    from: drLight,
    to: [megaman],
    cc: [roll],
    bcc: [zero],
    subject: "Robots should be used for the betterment of mankind.",
    text: "Any other use would be...unethical."
)

smtp.send(mail)

Send attachments

Create an Attachment, attach it to your Mail, and send it through the SMTP handle. Here's an example of how you can send the three supported types of attachments--a local file, HTML, and raw data:

// Create a file `Attachment`
let fileAttachment = Attachment(
    filePath: "~/img.png",          
    // "CONTENT-ID" lets you reference this in another attachment
    additionalHeaders: ["CONTENT-ID": "img001"]
)

// Create an HTML `Attachment`
let htmlAttachment = Attachment(
    htmlContent: "<html>Here's an image: <img src=\"cid:img001\"/></html>",
    // To reference `fileAttachment`
    related: [fileAttachment]
)

// Create a data `Attachment`
let data = "{\"key\": \"hello world\"}".data(using: .utf8)!
let dataAttachment = Attachment(
    data: data,
    mime: "application/json",
    name: "file.json",
    // send as a standalone attachment
    inline: false   
)

// Create a `Mail` and include the `Attachment`s
let mail = Mail(
    from: from,
    to: [to],
    subject: "Check out this image and JSON file!",
    // The attachments we created earlier
    attachments: [htmlAttachment, dataAttachment]
)

// Send the mail
smtp.send(mail)

/* Each type of attachment has additional parameters for further customization */

Send multiple mails

let mail1: Mail = //...
let mail2: Mail = //...

smtp.send([mail1, mail2],
    // This optional callback gets called after each `Mail` is sent.
    // `mail` is the attempted `Mail`, `error` is the error if one occured.
    progress: { (mail, error) in
    },

    // This optional callback gets called after all the mails have been sent.
    // `sent` is an array of the successfully sent `Mail`s.
    // `failed` is an array of (Mail, Error)--the failed `Mail`s and their corresponding errors.
    completion: { (sent, failed) in
    }
)

Acknowledgements

Inspired by Hedwig and Perfect-SMTP.

License

Apache v2.0

More Repositories

1

Kitura

A Swift web framework and HTTP server.
Swift
7,614
star
2

BlueSocket

Socket framework for Swift using the Swift Package Manager. Works on iOS, macOS, and Linux.
Swift
1,392
star
3

Swift-JWT

JSON Web Tokens in Swift
Swift
539
star
4

Swift-Kuery

SQL database abstraction layer
Swift
427
star
5

Swift-Kuery-ORM

An ORM for Swift, built on Codable
Swift
211
star
6

BlueCryptor

Swift cross-platform crypto library using CommonCrypto/libcrypto
Swift
189
star
7

HeliumLogger

A lightweight logging framework for Swift
Swift
175
star
8

swift-html-entities

HTML5 spec-compliant character encoder/decoder for Swift
Swift
165
star
9

swift-ubuntu-docker

🚫 This repo is deprecated - please use the images here: https://hub.docker.com/_/swift
Vim Script
155
star
10

BlueRSA

RSA public/private key encryption, private key signing and public key verification in Swift using the Swift Package Manager. Works on iOS, macOS, and Linux (work in progress).
Swift
128
star
11

SwiftyRequest

SwiftyRequest is an HTTP networking library built for Swift.
Swift
108
star
12

Kitura-net

Kitura networking
Swift
103
star
13

BlueSSLService

SSL/TLS Add-in for BlueSocket using Secure Transport and OpenSSL
Swift
96
star
14

Kitura-redis

Swift Redis library
Swift
94
star
15

BlueECC

Elliptic-curve cryptography for Swift
Swift
92
star
16

BlueSignals

Generic Cross Platform Signal Handler
Swift
92
star
17

Kitura-Sample

A sample application that shows how to use various features of Kitura
Swift
80
star
18

Configuration

Hierarchical configuration manager for Swift applications
Swift
78
star
19

Kitura-WebSocket

WebSocket support for Kitura
Swift
66
star
20

Swift-Kuery-PostgreSQL

PostgreSQL plugin for Swift-Kuery framework
Swift
61
star
21

OpenSSL

Swift modulemaps for libSSL and libcrypto
C
58
star
22

SwiftKafka

Swift SDK for Apache Kafka
Swift
58
star
23

KituraKit

Swift client library for using Codable routes with Kitura
Swift
58
star
24

Kitura-CouchDB

CouchDB adapter for Kitura
Swift
50
star
25

CircuitBreaker

A Swift Circuit Breaker library – Improves application stability and reliability.
Swift
45
star
26

Kitura-Credentials

A pluggable framework for validating user credentials in a Swift server using Kitura
Swift
40
star
27

Kitura-NIO

A networking library for Kitura, based on SwiftNIO
Swift
37
star
28

Kitura-OpenAPI

OpenAPI support for Kitura
Swift
36
star
29

TypeDecoder

A Swift library to allow the runtime inspection of Swift language native and complex types.
Swift
35
star
30

SwiftKueryMySQL

MySQL plugin for Swift-Kuery framework
Swift
34
star
31

Package-Builder

Build and utility scripts used for continuous integration builds for Swift Package Manager projects on the Travis CI environment
Shell
33
star
32

CCurl

Modulemap for the libcurl library
Objective-C
30
star
33

Kitura-StencilTemplateEngine

Stencil templating for Kitura
Swift
26
star
34

kitura.dev

http://www.kitura.dev
JavaScript
26
star
35

LoggerAPI

Logger protocol
Swift
25
star
36

Kitura-Markdown

Templating engine for Kitura that uses Markdown based templates
C
24
star
37

Health

An application health library for Swift.
Swift
21
star
38

Kitura-Session

A pluggable framework for managing user sessions in a Swift server using Kitura
Swift
18
star
39

Kitura-WebSocket-NIO

A SwiftNIO based implementation of WebSocket for Kitura
Swift
17
star
40

CommonCrypto

CommonCrypto Module Map
Swift
17
star
41

FileKit

Swift
16
star
42

Swift-Kuery-SQLite

An SQLite plugin for the Swift-Kuery framework
Swift
16
star
43

Kitura-TemplateEngine

Kitura Template Engine protocol
Swift
15
star
44

Kitura-CredentialsHTTP

A plugin for the Kitura-Credentials framework that authenticates using HTTP Basic and Digest authentication
Swift
15
star
45

kitura-cli

⌨️ Kitura command-line interface
Go
13
star
46

KituraContracts

A library containing type definitions shared by client and server Kitura code.
Swift
12
star
47

CZlib

Module map for Zlib library
Swift
11
star
48

CloudEnvironment

Convenience Swift package for accessing environment variables, credentials.
Swift
11
star
49

Kitura-CredentialsFacebook

A plugin for the Kitura-Credentials framework that authenticates using the Facebook web login
Swift
9
star
50

Kitura-CORS

Kitura CORS middleware
Swift
9
star
51

Kitura-Cache

Kitura cache
Swift
9
star
52

Kitura-CredentialsGoogle

A plugin for the Kitura-Credentials framework that authenticates using the Google web login
Swift
8
star
53

Swift-cfenv

Easy access to Cloud Foundry application environment for Swift Packages.
Swift
8
star
54

Kitura-Compression

Kitura compression middleware
Swift
6
star
55

CEpoll

A modulemap file and include to help Swift code use epoll on Linux
Swift
5
star
56

Kitura-WebSocket-Client

A WebSocket client based on SwiftNIO
Swift
5
star
57

Kitura-CredentialsGitHub

A plugin for the Kitura-Credentials framework that authenticates using the GitHub web login
Swift
4
star
58

Kitura-MustacheTemplateEngine

Adapter of GRMustache Template Engine to Kitura Template Engine
Swift
4
star
59

CHTTPParser

Modulemap for the http-parser library
C
4
star
60

Kitura-WebSocket-Compression

A WebSocket compression library based on SwiftNIO
Swift
3
star
61

Kitura-Session-Redis

Kitura-Session store using Redis as the backing store
Swift
3
star
62

generator-swiftserver-projects

Autogenerated Kitura projects
Shell
2
star
63

Kitura-CredentialsJWT

A plugin for the Kitura-Credentials framework that supports JWT authentication.
Swift
2
star
64

homebrew-kitura

Homebrew tap
Ruby
2
star
65

Kitura-Benchmarks

Benchmarks for Kitura
Swift
2
star
66

anapistula

Simple standalone web server in swift
Swift
1
star
67

CLibpq

PostgreSQL wrapper
Swift
1
star
68

ShellToolKit

Utility classes to help with common system/shell actions in Swift
Swift
1
star