Swift-SMTP

repository·master·Indexed 43 days ago

https://github.com/kitura/swift-smtp

A Swift-based SMTP client for securely connecting to SMTP servers using SSL/TLS. It supports various authentication methods, including XOAUTH2, and allows sending emails with local file, HTML, and raw data attachments.

Tokens
2.2K
Snippets
8
Records
9
Agent score
5%

What's inside Swift-SMTP

  1. Configure TLSMode for connection security

    master

    The TLSMode enum defines how the connection handles encryption:

    • .normal: Upgrades the connection to TLS if the STARTLS command is received; otherwise, sends mail without security.
    • .ignoreTLS: Sends mail over plaintext and ignores STARTTLS commands and TLS options. This may throw an error if the server requires TLS.
    • .requireTLS: Only sends mail after a successful initial TLS connection. The connection fails if TLS cannot be established. Note: When using this mode, you will likely need to adjust the port (e.g., to 465) depending on your server.
    • .requireSTARTTLS: Expects a STARTTLS command from the server and requires the connection to be upgraded. Throws an error if the server does not issue STARTTLS.
  2. Use XOAUTH2 authentication with SMTP (v4.0.0+)

    master

    The accessToken parameter was removed in version 4.0.0. If you are using the XOAUTH2 authorization method, you must pass your access token into the password parameter instead.

    let smtp = SMTP(
        hostname: "smtp.gmail.com",
        email: "example@gmail.com",
        password: "accessToken",
        authMethods: [.xoauth2]
    )
  3. Install Swift-SMTP via Swift Package Manager

    master

    To add SwiftSMTP to your project, add it as a dependency in your Package.swift file. Note that the dependency name is SwiftSMTP (without a hyphen). After updating your Package.swift, run swift package generate-xcodeproj in your project root to fetch dependencies and create the Xcode project.

    // 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"]),
            .testTarget(
                name: "MyProjectTests",
                dependencies: ["MyProject"]),
        ]
    )
  4. Send a single email

    master

    To send an email, create a Mail object and use the SMTP instance's send method. You define sender and receiver identities using the Mail.User struct. You can also include cc and bcc recipients.

    let drLight = Mail.User(name: "Dr. Light", email: "drlight@gmail.com")
    let megaman = Mail.User(name: "Megaman", email: "megaman@gmail.com")
    
    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)
        }
    }
  5. Send multiple emails with progress and completion callbacks

    master

    You can pass an array of Mail objects to the send method. This method provides two optional callbacks:

    • progress: Called after each individual mail is attempted. Provides the mail attempted and an optional error.
    • completion: Called after the entire batch is processed. Provides sent (array of successfully sent Mail objects) and failed (array of (Mail, Error) tuples).
    let mail1: Mail = //...
    let mail2: Mail = //...
    
    smtp.send([mail1, mail2],
        progress: { (mail, error) in
            // Called after each mail is sent
        },
        completion: { (sent, failed) in
            // Called after all mails have been sent
        }
    )
  6. Send attachments (File, HTML, and Data)

    master

    Swift-SMTP supports three types of attachments:

    1. Local File: Use filePath. You can add additionalHeaders like CONTENT-ID to reference the file in other attachments.
    2. HTML: Use htmlContent. You can use the related parameter to link the HTML content to other attachments (e.g., for inline images using cid).
    3. Raw Data: Use data, specifying the mime type and a name. Use inline: false to send it as a standard attachment or true for inline content.

    Include them in the attachments array of a Mail object.

    // Create a file `Attachment`
    let fileAttachment = Attachment(
        filePath: "~/img.png",          
        additionalHeaders: ["CONTENT-ID": "img001"]
    )
    
    // Create an HTML `Attachment`
    let htmlAttachment = Attachment(
        htmlContent: "<html>Here's an image: <img src=\"cid:img001\"/></html>",
        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",
        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!",
        attachments: [htmlAttachment, dataAttachment]
    )
    
    smtp.send(mail)
  7. Initialize SMTP with TLSMode (v5.0.0+)

    master

    Starting with version 5.0.0, the SMTP struct no longer uses a useTLS: Bool parameter. Instead, it uses a TLSMode enum to provide more granular control over connection security. The default port has also changed to 587.

    // Example of using TLSMode for connection security
    let smtp = SMTP(
        hostname: "smtp.example.com",
        email: "user@example.com",
        password: "password",
        port: 587,
        tlsMode: .requireTLS
    )
  8. Initialize the SMTP client

    master

    The SMTP struct is the primary handle for sending emails. By default, it connects on port 587 and requires a TLS connection via STARTTLS.

    Use the following initializer to configure the connection:

    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)
    import SwiftSMTP
    
    let smtp = SMTP(
        hostname: "smtp.gmail.com",     // SMTP server address
        email: "user@gmail.com",        // username to login
        password: "password"            // password to login
    )