Classes

The following classes are available globally.

  • The Attachment class represents a file to attach to an email.

    See more

    Declaration

    Swift

    open class Attachment : Encodable
  • The Personalization struct is used by the Email class to add personalization settings to an email. The only required property is the to property, and each email must have at least one personalization.

    See more

    Declaration

    Swift

    open class Personalization : Encodable, EmailHeaderRepresentable, Scheduling
  • The TemplatedPersonalization class is a subclass of Personalization, and is used if you are using the Dynamic Templates feature.

    There is a generic TemplateData type that you can specify which represents the substitution data. An example of using this class might look something like this:

    // First let's define our dynamic data types:
    struct CheckoutData: Encodable {
        let total: String
        let items: [String]
        let receipt: Bool
    }
    
    // Next let's create the personalization.
    let thisData = CheckoutData(total: "$239.85",
                                items: ["Shoes", "Shirt"],
                                receipt: true)
    let personalization = TemplatedPersonalization(dynamicTemplateData: thisData,
                                                   recipients: "foo@bar.example")
    
    See more

    Declaration

    Swift

    open class TemplatedPersonalization<TemplateData> : Personalization where TemplateData : Encodable
  • The Email class is used to make the Mail Send API call. The class allows you to configure many different aspects of the email.

    Content

    To specify the content of an email, use the Content class. In general, an email will have plain text and/or HTML text content, however you can specify other types of content, such as an ICS calendar invite. Following RFC 1341, section 7.2, if either HTML or plain text content are to be sent in your email: the plain text content needs to be first, followed by the HTML content, followed by any other content.

    Personalizations

    The new V3 endpoint introduces the idea of personalizations. When using the API, you define a set of global characteristics for the email, and then also define seperate personalizations, which contain recipient-specific information for the email. Since personalizations contain the recipients of the email, each request must contain at least 1 personalization.

    // Send a basic example
    let personalization = Personalization(recipients: "test@example.com")
    let plainText = Content(contentType: ContentType.plainText, value: "Hello World")
    let htmlText = Content(contentType: ContentType.htmlText, value: "<h1>Hello World</h1>")
    let email = Email(
        personalizations: [personalization],
        from: "foo@bar.com",
        content: [plainText, htmlText],
        subject: "Hello World"
    )
    do {
        try Session.shared.send(request: email)
    } catch {
        print(error)
    }
    

    An Email instance can have up to 1000 Personalization instances. A Personalization can be thought of an individual email. It can contain several to addresses, along with cc and bcc addresses. Keep in mind that if you put two addresses in a single Personalization instance, each recipient will be able to see each other’s email address. If you want to send to several recipients where each recipient only sees their own address, you’ll want to create a seperate Personalization instance for each recipient.

    The Personalization class also allows personalizing certain email attributes, including:

    If a Personalization instance contains an email attribute that is also defined globally in the request (such as the subject), the Personalization instance’s value takes priority.

    Here is an advanced example of using personalizations:

    // Send an advanced example
    let recipients = [
        Address(email: "jose@example.none", name: "Jose"),
        Address(email: "isaac@example.none", name: "Isaac"),
        Address(email: "tim@example.none", name: "Tim")
    ]
    let personalizations = recipients.map { (recipient) -> Personalization in
        let name = recipient.name ?? "there"
        return Personalization(
            to: [recipient],
            cc: nil,
            bcc: [Address(email: "bcc@example.none")],
            subject: "Hello \(name)!",
            headers: ["X-Campaign":"12345"],
            substitutions: ["%name%":name],
            customArguments: ["campaign_id":"12345"]
        )
    }
    let contents = Content.emailBody(
        plain: "Hello %name%,\n\nHow are you?\n\nBest,\nSender",
        html: "<p>Hello %name%,</p><p>How are you?</p><p>Best,<br>Sender</p>"
    )
    let email = Email(
        personalizations: personalizations,
        from: Address(email: "sender@example.none"),
        content: contents,
        subject: nil
    )
    email.parameters?.headers = [
        "X-Campaign": "12345"
    ]
    email.parameters?.customArguments = [
        "campaign_id": "12345"
    ]
    do {
        try Session.shared.send(request: email) { (result) in
            switch result {
            case .success(let response):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    You’ll notice in the example above, the global email defines custom headers and custom arguments. In addition, each personalization defines some headers and custom arguments. For the resulting email, the headers and custom arguments will be merged together. In the event of a conflict, the personalization’s values will be used.

    Attachments

    The Attachment class allows you to easily add attachments to an email. All you need is to convert your desired attachment into Data and initialize it like so:

    let personalization = Personalization(recipients: "test@example.com")
    let contents = Content.emailBody(
        plain: "Hello World",
        html: "<h1>Hello World</h1>"
    )
    let email = Email(
        personalizations: [personalization],
        from: "foo@bar.com",
        content: contents,
        subject: "Hello World"
    )
    do {
        if let path = Bundle.main.url(forResource: "proposal", withExtension: "pdf") {
            let attachment = Attachment(
                filename: "proposal.pdf",
                content: try Data(contentsOf: path),
                disposition: .attachment,
                type: .pdf,
                contentID: nil
            )
            email.parameters?.attachments = [attachment]
        }
        try Session.shared.send(request: email) { (result) in
            switch result {
            case .success(let response):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    You can also use attachments as inline images by setting the disposition property to .inline and setting the cid property. You can then reference that unique CID in your HTML like so:

    let personalization = Personalization(recipients: "test@example.com")
    let contents = Content.emailBody(
        plain: "Hello World",
        html: "<img src=\"cid:main_logo_12345\" /><h1>Hello World</h1>"
    )
    let email = Email(
        personalizations: [personalization],
        from: "foo@bar.com",
        content: contents,
        subject: "Hello World"
    )
    do {
        let filename = NSImage.Name("logo.png")
        if let path = Bundle.main.urlForImageResource(filename) {
            let attachment = Attachment(
                filename: "logo.png",
                content: try Data(contentsOf: path),
                disposition: .inline,
                type: .png,
                contentID: "main_logo_12345"
            )
            email.parameters?.attachments = [attachment]
        }
        try Session.shared.send(request: email) { (result) in
            switch result {
            case .success(let response):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    Mail and Tracking Settings

    There are various classes available that you can use to modify the mail and tracking settings for a specific email.

    MAIL SETTINGS

    The following mail setting classes are available:

    • BCCSetting - This allows you to have a blind carbon copy automatically sent to the specified email address for every email that is sent.
    • BypassListManagement - Allows you to bypass all unsubscribe groups and suppressions to ensure that the email is delivered to every single recipient. This should only be used in emergencies when it is absolutely necessary that every recipient receives your email. Ex: outage emails, or forgot password emails.
    • Footer - The default footer that you would like appended to the bottom of every email.
    • SandboxMode - This allows you to send a test email to ensure that your request body is valid and formatted correctly. For more information, please see the Classroom.
    • SpamChecker - This allows you to test the content of your email for spam.

    TRACKING SETTINGS

    The following tracking setting classes are available:

    • ClickTracking - Allows you to track whether a recipient clicked a link in your email.
    • GoogleAnalytics - Allows you to enable tracking provided by Google Analytics.
    • OpenTracking - Allows you to track whether the email was opened or not, but including a single pixel image in the body of the content. When the pixel is loaded, we can log that the email was opened.
    • SubscriptionTracking - Allows you to insert a subscription management link at the bottom of the text and html bodies of your email. If you would like to specify the location of the link within your email, you may specify a substitution tag.

    EXAMPLE

    Each setting has its own properties that can be configured, but here’s a basic example:

    let personalization = Personalization(recipients: "test@example.com")
    let contents = Content.emailBody(
        plain: "Hello World",
        html: "<h1>Hello World</h1>"
    )
    let email = Email(
        personalizations: [personalization],
        from: "foo@bar.com",
        content: contents,
        subject: "Hello World"
    )
    email.parameters?.mailSettings.footer = Footer(
        text: "Copyright 2016 MyCompany",
        html: "<p><small>Copyright 2016 MyCompany</small></p>"
    )
    email.parameters?.trackingSettings.clickTracking = ClickTracking(section: .htmlBody)
    email.parameters?.trackingSettings.openTracking = OpenTracking(location: .off)
    do {
        try Session.shared.send(request: email) { (result) in
            switch result {
            case .success(let response):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    Unsubscribe Groups (ASM)

    If you use SendGrid’s unsubscribe groups feature, you can specify which unsubscribe group to send an email under like so:

    let personalization = Personalization(recipients: "test@example.com")
    let contents = Content.emailBody(
        plain: "Hello World",
        html: "<h1>Hello World</h1>"
    )
    let email = Email(
        personalizations: [personalization],
        from: "foo@bar.com",
        content: contents,
        subject: "Hello World"
    )
    /// Assuming your unsubscribe group has an ID of 4815…
    email.parameters?.asm = ASM(groupID: 4815)
    do {
        try Session.shared.send(request: email) { (result) in
            switch result {
            case .success(let response):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    You can also specify which unsubscribe groups should be shown on the subscription management page for this email:

    let personalization = Personalization(recipients: "test@example.com")
    let contents = Content.emailBody(
        plain: "Hello World",
        html: "<h1>Hello World</h1>"
    )
    let email = Email(
        personalizations: [personalization],
        from: "foo@bar.com",
        content: contents,
        subject: "Hello World"
    )
    /// Assuming your unsubscribe group has an ID of 4815…
    email.parameters?.asm = ASM(groupID: 4815, groupsToDisplay: [16,23,42])
    do {
        try Session.shared.send(request: email) { (result) in
            switch result {
            case .success(let response):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    IP Pools

    If you’re on a pro plan or higher, and have set up IP Pools on your account, you can specify a specific pool to send an email over like so:

    let personalization = Personalization(recipients: "test@example.com")
    let contents = Content.emailBody(
        plain: "Hello World",
        html: "<h1>Hello World</h1>"
    )
    let email = Email(
        personalizations: [personalization],
        from: "foo@bar.com",
        content: contents,
        subject: "Hello World"
    )
    /// Assuming you have an IP pool called "transactional" on your account…
    email.parameters?.ipPoolName = "transactional"
    do {
        try Session.shared.send(request: email) { (result) in
            switch result {
            case .success(let response):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    Scheduled Sends

    If you don’t want the email to be sent right away, but rather at some point in the future, you can use the sendAt property. NOTE: You cannot schedule an email further than 72 hours in the future. You can also assign an optional, unique batchID to the email so that you can cancel via the API in the future if needed.

    let personalization = Personalization(recipients: "test@example.com")
    let contents = Content.emailBody(
        plain: "Hello World",
        html: "<h1>Hello World</h1>"
    )
    let email = Email(
        personalizations: [personalization],
        from: "foo@bar.com",
        content: contents,
        subject: "Hello World"
    )
    // Schedule the email for 24 hours from now.
    email.parameters?.sendAt = Date(timeIntervalSinceNow: 24 * 60 * 60)
    
    // This part is optional, but if you [generated a batch ID](https://sendgrid.com/docs/API_Reference/Web_API_v3/cancel_schedule_send.html)
    // and specify it here, you'll have the ability to cancel this send via the API if needed.
    email.parameters?.batchID = "76A8C7A6-B435-47F5-AB13-15F06BA2E3WD"
    
    do {
        try Session.shared.send(request: email) { (result) in
            switch result {
            case .success(let response):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    In the above example, we’ve set the sendAt property on the global email, which means every personalization will be scheduled for that time. You can also set the sendAt property on a Personalization if you want each one to be set to a different time, or only have certain ones scheduled:

    let recipientInfo: [String : Date?] = [
        "jose@example.none": Date(timeIntervalSinceNow: 4 * 60 * 60),
        "isaac@example.none": nil,
        "tim@example.none": Date(timeIntervalSinceNow: 12 * 60 * 60)
    ]
    let personalizations = recipientInfo.map { (recipient, date) -> Personalization in
        let personalization = Personalization(recipients: recipient)
        personalization.sendAt = date
        return personalization
    }
    let contents = Content.emailBody(
        plain: "Hello there,\n\nHow are you?\n\nBest,\nSender",
        html: "<p>Hello there,</p><p>How are you?</p><p>Best,<br>Sender</p>"
    )
    let email = Email(
        personalizations: personalizations,
        from: "sender@example.none",
        content: contents,
        subject: nil
    )
    do {
        try Session.shared.send(request: email) { (result) in
            switch result {
            case .success(let response):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    Categories

    You can assign categories to an email which will show up in your SendGrid stats, Email Activity, and event webhook. You can not have more than 10 categories per email.

    let personalization = Personalization(recipients: "test@example.com")
    let contents = Content.emailBody(
        plain: "Hello World",
        html: "<h1>Hello World</h1>"
    )
    let email = Email(
        personalizations: [personalization],
        from: "foo@bar.com",
        content: contents,
        subject: "Hello World"
    )
    email.parameters?.categories = ["Foo", "Bar"]
    do {
        try Session.shared.send(request: email) { (result) in
            switch result {
            case .success(let response):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    Sections

    Sections allow you to define large blocks of content that can be inserted into your emails using substitution tags. An example of this might look like the following:

    let bob = Personalization(recipients: "bob@example.com")
    bob.substitutions = [
        ":salutation": ":male",
        ":name": "Bob",
        ":event_details": ":event2",
        ":event_date": "Feb 14"
    ]
    
    let alice = Personalization(recipients: "alice@example.com")
    alice.substitutions = [
        ":salutation": ":female",
        ":name": "Alice",
        ":event_details": ":event1",
        ":event_date": "Jan 1"
    ]
    
    let casey = Personalization(recipients: "casey@example.com")
    casey.substitutions = [
        ":salutation": ":neutral",
        ":name": "Casey",
        ":event_details": ":event1",
        ":event_date": "Aug 11"
    ]
    
    let personalization = [
        bob,
        alice,
        casey
    ]
    let plainText = ":salutation,\n\nPlease join us for the :event_details."
    let htmlText = "<p>:salutation,</p><p>Please join us for the :event_details.</p>"
    let content = Content.emailBody(plain: plainText, html: htmlText)
    let email = Email(
        personalizations: personalization,
        from: "from@example.com",
        content: content
    )
    email.parameters?.subject = "Hello World"
    email.parameters?.sections = [
        ":male": "Mr. :name",
        ":female": "Ms. :name",
        ":neutral": ":name",
        ":event1": "New User Event on :event_date",
        ":event2": "Veteran User Appreciation on :event_date"
    ]
    

    Template Engine

    If you use SendGrid’s Template Engine, you can specify a template to apply to an email like so:

    let personalization = Personalization(recipients: "test@example.com")
    let contents = Content.emailBody(
        plain: "Hello World",
        html: "<h1>Hello World</h1>"
    )
    let email = Email(
        personalizations: [personalization],
        from: "foo@bar.com",
        content: contents,
        subject: "Hello World"
    )
    /// Assuming you have a template with ID "52523e14-7e47-45ed-ab32-0db344d8cf9z" on your account…
    email.parameters?.templateID = "52523e14-7e47-45ed-ab32-0db344d8cf9z"
    do {
        try Session.shared.send(request: email) { (result) in
            switch result {
            case .success(let response):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    
    See more

    Declaration

    Swift

    public class Email : Request<Email.Parameters>
  • The Statistic.Category class is used to make the Get Category Stats API call. At minimum you need to specify a start date.

    do {
        let now = Date()
        let lastMonth = now.addingTimeInterval(-2592000) // 30 days
        let request = RetrieveCategoryStatistics(
            startDate: lastMonth,
            endDate: now,
            aggregatedBy: .week,
            categories: "Foo", "Bar"
        )
        try Session.shared.send(modeledRequest: request) { result in
            switch result {
            case .success(_, let model):
                // The `model` variable will be an array of `Statistic` structs.
                model.forEach { _ in
                    // Do something with the stats here...
                }
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    
    See more

    Declaration

    Swift

    public class RetrieveCategoryStatistics : RetrieveGlobalStatistics
  • The Statistic.Global class is used to make the Get Global Stats API call. At minimum you need to specify a start date.

    do {
        let now = Date()
        let lastMonth = now.addingTimeInterval(-2592000) // 30 days
        let request = RetrieveGlobalStatistics(
            startDate: lastMonth,
            endDate: now,
            aggregatedBy: .week
        )
        try Session.shared.send(modeledRequest: request) { result in
            switch result {
            case .success(_, let model):
                // The `model` property will be an array of `Statistic` structs.
                model.forEach { _ in
                    // Do something with the stats here...
                }
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    
    See more

    Declaration

    Swift

    public class RetrieveGlobalStatistics : ModeledRequest<[Statistic], RetrieveStatisticsParameters>
  • The RetrieveStatisticsParameters class represents the

    See more

    Declaration

    Swift

    public class RetrieveStatisticsParameters : Codable
  • The Statistic.Subuser class is used to make the Get Subuser Stats API call. At minimum you need to specify a start date.

    do {
        let now = Date()
        let lastMonth = now.addingTimeInterval(-2592000) // 30 days
        let request = RetrieveSubuserStatistics(
            startDate: lastMonth,
            endDate: now,
            aggregatedBy: .week,
            subusers: "Foo", "Bar"
        )
        try Session.shared.send(modeledRequest: request) { result in
            switch result {
            case .success(_, let model):
                // The `model` property will be an array of `Statistic` structs.
                model.forEach { _ in
                    // Do something with the stats here...
                }
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    
    See more

    Declaration

    Swift

    public class RetrieveSubuserStatistics : RetrieveGlobalStatistics
  • This class is used to make the get subusers API call.

    You can provide pagination information, and also search by username. If you partial searches are allowed, so for instance if you had a subuser with username foobar, searching for foo would return it.

    do {
        let search = RetrieveSubusers(username: "foo")
        try Session.shared.send(modeledRequest: search) { result in
            switch result {
            case .success(_, let list):
                // The `list` variable will be an array of
                // `Subuser` instances.
                list.forEach { print($0.username) }
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    
    See more

    Declaration

    Swift

    public class RetrieveSubusers : ModeledRequest<[Subuser], RetrieveSubusers.Parameters>
  • The DeleteBlocks class represents the API call to delete from the block list. You can use it to delete the entire list, or specific entries in the list.

    Delete All Blocks

    To delete all blocks, use the request returned from DeleteBlocks.all. This request will delete all blocks on your block list.

    do {
        let request = DeleteBlocks.all
        try Session.shared.send(request: request) { result in
            switch result {
            case .success(let response):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    Delete Specific Blocks

    To delete specific entries from your block list, use the DeleteBlocks class. You can either specify email addresses (as strings), or you can use Block instances (useful for if you just retrieved some from the RetrieveBlocks class).

    do {
        let request = DeleteBlocks(emails: "foo@example.none", "bar@example.none")
        try Session.shared.send(request: request) { result in
            switch result {
            case .success(let response):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    
    See more

    Declaration

    Swift

    public class DeleteBlocks : SuppressionListDeleter<Block>
  • The RetrieveBlocks class represents the API call to retrieve the block list. You can use it to retrieve the entire list, or specific entries in the list.

    Get All Blocks

    To retrieve the list of all blocks, use the RetrieveBlocks class with the init(start:end:page:) initializer. The library will automatically map the response to the Block struct model, accessible via the model property on the response instance you get back.

    do {
        // If you don't specify any parameters, then the first page of your
        // entire block list will be fetched:
        let request = RetrieveBlocks()
        try Session.shared.send(modeledRequest: request) { result in
            switch result {
            case .success(let response, let model):
                // The `model` property will be an array of `Block` structs.
                model.forEach { print($0.email) }
    
                // The response object has a `Pagination` instance on it as well.
                // You can use this to get the next page, if you wish.
                if let nextPage = response.pages?.next {
                    let nextRequest = RetrieveBlocks(page: nextPage)
                }
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    You can also specify any or all of the init parameters to filter your search down:

    do {
        // Retrieve page 2
        let page = Page(limit: 500, offset: 500)
        // Blocks starting from yesterday
        let now = Date()
        let start = now.addingTimeInterval(-86400) // 24 hours
    
        let request = RetrieveBlocks(start: start, end: now, page: page)
        try Session.shared.send(modeledRequest: request) { result in
            switch result {
            case .success(_, let model):
                // The `model` variable will be an array of `Block` structs.
                model.forEach { print($0.email) }
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    Get Specific Block

    If you’re looking for a specific email address in the block list, you can use the init(email:) initializer on RetrieveBlocks:

    do {
        let request = RetrieveBlocks(email: "foo@example.none")
        try Session.shared.send(modeledRequest: request) { result in
            switch result {
            case .success(_, let model):
                // The `model` property will be an array of `Block` structs.
                model.forEach { item in
                    print("\(item.email) was blocked with reason \"\(item.reason)\"")
                }
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    Declaration

    Swift

    public class RetrieveBlocks : SuppressionListReader<Block>
  • The DeleteBounces class represents the API call to delete from the bounce list. You can use it to delete the entire list, or specific entries from the list.

    Delete All Bounces

    To delete all bounces, use the request returned from DeleteBounces.all. This request will delete all bounces on your bounce list.

    do {
        let request = DeleteBounces.all
        try Session.shared.send(request: request) { result in
            switch result {
            case .success(let response):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    Delete Specific Bounces

    To delete specific entries from your bounce list, use the DeleteBounces class. You can either specify email addresses (as strings), or you can use Bounce instances (useful for if you just retrieved some from the RetrieveBounces class).

    do {
        let request = DeleteBounces(emails: "foo@example.none", "bar@example.none")
        try Session.shared.send(request: request) { result in
            switch result {
            case .success(let response):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    
    See more

    Declaration

    Swift

    public class DeleteBounces : SuppressionListDeleter<Bounce>
  • The RetrieveBounces class represents the API call to retrieve the bounce list. You can use it to retrieve the entire list, or specific entries in the list.

    Get All Bounces

    To retrieve the list of all bounces, use the RetrieveBounces class with the init(start:end:page:) initializer. The library will automatically map the response to the Bounce struct model, accessible via the model property on the response instance you get back.

    do {
        // If you don't specify any parameters, then the first page of your entire
        // bounce list will be fetched:
        let request = RetrieveBounces()
        try Session.shared.send(modeledRequest: request) { result in
            switch result {
            case .success(let response, let model):
                // The `model` property will be an array of `Bounce` structs.
                model.forEach { print($0.email) }
    
                // The response object has a `Pagination` instance on it as well.
                // You can use this to get the next page, if you wish.
                if let nextPage = response.pages?.next {
                    let nextRequest = RetrieveBounces(page: nextPage)
                }
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    You can also specify any or all of the init parameters to filter your search down:

    do {
        // Retrieve page 2
        let page = Page(limit: 500, offset: 500)
        // Bounces starting from yesterday
        let now = Date()
        let start = now.addingTimeInterval(-86400) // 24 hours
    
        let request = RetrieveBounces(start: start, end: now, page: page)
        try Session.shared.send(modeledRequest: request) { result in
            switch result {
            case .success(_, let model):
                // The `model` property will be an array of `Bounce` structs.
                model.forEach { print($0.email) }
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    Get Specific Bounce

    If you’re looking for a specific email address in the bounce list, you can use the init(email:) initializer on RetrieveBounces:

    do {
        let request = RetrieveBounces(email: "foo@example.none")
        try Session.shared.send(modeledRequest: request) { result in
            switch result {
            case .success(_, let model):
                // The `model` property will be an array of `Bounce` structs.
                if let match = model.first {
                    print("\(match.email) bounced with reason \"\(match.reason)\"")
                }
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    Declaration

    Swift

    public class RetrieveBounces : SuppressionListReader<Bounce>
  • The AddGlobalUnsubscribes class represents the API call to add email addresses to the global unsubscribe list.

    You can specify email addresses (as strings), or you can use Address instances.

    do {
        let request = AddGlobalUnsubscribes(emails: "foo@example.none", "bar@example.none")
        try Session.shared.send(modeledRequest: request) { result in
            switch result {
            case .success(let response, _):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    
    See more

    Declaration

    Swift

    public class AddGlobalUnsubscribes : ModeledRequest<AddGlobalUnsubscribes.Parameters, AddGlobalUnsubscribes.Parameters>
  • The DeleteGlobalUnsubscribe class represents the API call to delete from the invalid email list.

    You can specify an email address (as a string), or you can use a GlobalUnsubscribe instance (useful for if you just retrieved some from the RetrieveGlobalUnsubscribes class).

    do {
        let request = DeleteGlobalUnsubscribe(email: "foo@example.none")
        try Session.shared.send(request: request) { result in
            switch result {
            case .success(let response):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    
    See more

    Declaration

    Swift

    public class DeleteGlobalUnsubscribe : Request<[String : String]>
  • The RetrieveGlobalUnsubscribes class represents the API call to retrieve the global unsubscribe list. You can use it to retrieve the entire list, or specific entries on the list.

    Get All Global Unsubscribes

    To retrieve the list of all global unsubscribes, use the RetrieveGlobalUnsubscribes class with the init(start:end:page:) initializer. The library will automatically map the response to the GlobalUnsubscribe struct model, accessible via the model property on the response instance you get back.

    do {
        // If you don't specify any parameters, then the first page of your
        // entire global unsubscribe list will be fetched:
        let request = RetrieveGlobalUnsubscribes()
        try Session.shared.send(modeledRequest: request) { result in
            switch result {
            case .success(let response, let model):
                // The `model` property will be an array of `GlobalUnsubscribe` structs.
                model.forEach { print($0.email) }
    
                // The response object has a `Pagination` instance on it as well.
                // You can use this to get the next page, if you wish.
                if let nextPage = response.pages?.next {
                    let nextRequest = RetrieveGlobalUnsubscribes(page: nextPage)
                }
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    You can also specify any or all of the init parameters to filter your search down:

    do {
        // Retrieve page 2
        let page = Page(limit: 500, offset: 500)
        // Global unsubscribes starting from yesterday
        let now = Date()
        let start = now.addingTimeInterval(-86400) // 24 hours
    
        let request = RetrieveGlobalUnsubscribes(start: start, end: now, page: page)
        try Session.shared.send(modeledRequest: request) { result in
            switch result {
            case .success(_, let model):
                model.forEach { print($0.email) }
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    Get Specific Global Unsubscribe

    If you’re looking for a specific email address in the global unsubscribe list, you can use the init(email:) initializer on RetrieveGlobalUnsubscribes:

    do {
        let request = RetrieveGlobalUnsubscribes(email: "foo@example")
        try Session.shared.send(modeledRequest: request) { result in
            switch result {
            case .success(_, let model):
                if let unsub = model.first {
                    print(unsub)
                }
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    Declaration

    Swift

    public class RetrieveGlobalUnsubscribes : SuppressionListReader<GlobalUnsubscribe>
  • The DeleteInvalidEmails.Delete class represents the API call to delete from the invalid email list. You can use it to delete the entire list, or specific entries on the list.

    Delete All Invalid Emails

    To delete all invalid emails, use the request returned from DeleteInvalidEmails.all. This request will delete all addresses on your invalid email list.

    do {
        let request = DeleteInvalidEmails.all
        try Session.shared.send(request: request) { result in
            switch result {
            case .success(let response):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    Delete Specific Invalid Emails

    To delete specific entries from your invalid email list, use the DeleteInvalidEmails class. You can either specify email addresses (as strings), or you can use InvalidEmail instances (useful for if you just retrieved some from the RetrieveInvalidEmails class).

    do {
        let request = DeleteInvalidEmails(emails: "foo@example", "bar@example")
        try Session.shared.send(request: request) { result in
            switch result {
            case .success(let response):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    
    See more

    Declaration

    Swift

    public class DeleteInvalidEmails : SuppressionListDeleter<InvalidEmail>
  • The RetrieveInvalidEmails class represents the API call to retrieve the invalid email list. You can use it to retrieve the entire list, or specific entries from the list.

    Get All Invalid Emails

    To retrieve the list of all invalid emails, use the RetrieveInvalidEmails class with the init(start:end:page:) initializer. The library will automatically map the response to the InvalidEmail struct model, accessible via the model property on the response instance you get back.

    do {
        // If you don't specify any parameters, then the first page of your
        // entire invalid email list will be fetched:
        let request = RetrieveInvalidEmails()
        try Session.shared.send(modeledRequest: request) { result in
            switch result {
            case .success(let response, let model):
                // The `model` property will be an array of `InvalidEmail`
                // structs.
                model.forEach { print($0.email) }
    
                // The response object has a `Pagination` instance on it as
                // well. You can use this to get the next page, if you wish.
                if let nextPage = response.pages?.next {
                    let nextRequest = RetrieveInvalidEmails(page: nextPage)
                }
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    You can also specify any or all of the init parameters to filter your search down:

    do {
        // Retrieve page 2
        let page = Page(limit: 500, offset: 500)
        // Invalid emails starting from yesterday
        let now = Date()
        let start = now.addingTimeInterval(-86400) // 24 hours
    
        let request = RetrieveInvalidEmails(start: start, end: now, page: page)
        try Session.shared.send(modeledRequest: request) { result in
            switch result {
            case .success(_, let model):
                model.forEach { print($0.email) }
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    Get Specific Invalid Email

    If you’re looking for a specific email address in the invalid email list, you can use the init(email:) initializer on RetrieveInvalidEmails:

    do {
        let request = RetrieveInvalidEmails(email: "foo@example")
        try Session.shared.send(modeledRequest: request) { result in
            switch result {
            case .success(_, let model):
                model.forEach { print($0.email) }
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    Declaration

    Swift

    public class RetrieveInvalidEmails : SuppressionListReader<InvalidEmail>
  • The DeleteSpamReports class represents the API call to delete from the spam report list. You can use it to delete the entire list, or specific entries from the list.

    Delete All Spam Reports

    To delete all spam reports, use the request returned from DeleteSpamReports.all. This request will delete all spam reports on your spam report list.

    do {
        let request = DeleteSpamReports.all
        try Session.shared.send(request: request) { result in
            switch result {
            case .success(let response):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    Delete Specific Spam Reports

    To delete specific entries from your spam report list, use the DeleteSpamReports class. You can either specify email addresses (as strings), or you can use SpamReport instances (useful for if you just retrieved some from the RetrieveSpamReports class).

    do {
        let request = DeleteSpamReports(emails: "foo@example.none", "bar@example.none")
        try Session.shared.send(request: request) { result in
            switch result {
            case .success(let response):
                print(response.statusCode)
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    
    See more

    Declaration

    Swift

    public class DeleteSpamReports : SuppressionListDeleter<SpamReport>
  • The RetrieveSpamReports class represents the API call to retrieve the spam reports list. You can use it to retrieve the entire list, or specific entries on the list.

    Get All Spam Reports

    To retrieve the list of all spam reports, use the RetrieveSpamReports class with the init(start:end:page:) initializer. The library will automatically map the response to the SpamReport struct model, accessible via the model property on the response instance you get back.

    do {
        // If you don't specify any parameters, then the first page of your
        // entire spam report list will be fetched:
        let request = RetrieveSpamReports()
        try Session.shared.send(modeledRequest: request) { result in
            switch result {
            case .success(let response, let model):
                // The `model` property will be an array of `SpamReport` structs.
                model.forEach { print($0.email) }
    
                // The response object has a `Pagination` instance on it as well.
                // You can use this to get the next page, if you wish.
                if let nextPage = response.pages?.next {
                    let nextRequest = RetrieveSpamReports(page: nextPage)
                }
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    You can also specify any or all of the init parameters to filter your search down:

    do {
        // Retrieve page 2
        let page = Page(limit: 500, offset: 500)
        // Spam Reports starting from yesterday
        let now = Date()
        let start = now.addingTimeInterval(-86400) // 24 hours
    
        let request = RetrieveSpamReports(start: start, end: now, page: page)
        try Session.shared.send(modeledRequest: request) { result in
            switch result {
            case .success(_, let model):
                // The `model` property will be an array of `SpamReport`
                // structs.
                model.forEach { print($0.email) }
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    Get Specific Spam Report

    If you’re looking for a specific email address in the spam report list, you can use the init(email:) initializer on RetrieveSpamReports:

    do {
        let request = RetrieveSpamReports(email: "foo@example.none")
        try Session.shared.send(modeledRequest: request) { result in
            switch result {
            case .success(_, let model):
                // The `model` value will be an array of `SpamReport`
                // structs.
                model.forEach { print($0.email) }
            case .failure(let err):
                print(err)
            }
        }
    } catch {
        print(error)
    }
    

    Declaration

    Swift

    public class RetrieveSpamReports : SuppressionListReader<SpamReport>
  • The FormURLEncoder class encodes any Encodable instance into the application/x-www-form-urlencoded Content-Type.

    The example below shows how to encode an instance of a simple GroceryProduct type to a form URL encoded string. The type adopts Codable so that it’s encodable as JSON using a JSONEncoder instance.

    struct GroceryProduct: Codable {
        var name: String
        var points: Int
        var description: String?
    }
    
    let pear = GroceryProduct(name: "Pear", points: 250, description: "A ripe pear.")
    
    let encoder = FormURLEncoder()
    let results = try encoder.stringEncode(pear)
    print(results)
    
    /* Prints:
     description=A%20ripe%20pear.&name=Pear&points=250
    */
    
    See more

    Declaration

    Swift

    open class FormURLEncoder
  • The Request class should be inherited by any class that represents an API request and sent through the send function in Session.

    Only classes that aren’t expecting any data back in the response should directly inherit this class. If data is expected, then ModeledRequest should be used instead.

    See more

    Declaration

    Swift

    open class Request<Parameters> : Validatable where Parameters : Encodable
  • The ModeledRequest class should be inherited by any class that represents an API request and sent through the send function in Session.

    This class contains a ModelType generic, which is used to map the API response to a specific model that conforms to Decodable.

    Declaration

    Swift

    open class ModeledRequest<ModelType, Parameters> : Request<Parameters> where ModelType : Decodable, Parameters : Encodable
  • The Session class is used to faciliate the HTTP request to the SendGrid API endpoints. When starting out, you’ll want to configure Session with your authentication information, whether that be credentials or an API Key. A class conforming to the Resource protocol is then used to provide information about the desired API call.

    You can also call the sharedInstance property of Session to get a singleton instance. This will allow you to configure the singleton once, and continually reuse it later without the need to re-configure it.

    See more

    Declaration

    Swift

    open class Session