Sample code for 30+ languages & platforms
Swift

Amazon SES v2: Create and preview a receipt template

See more Amazon SES Examples

Create the regional OrderReceipt template once. Set createTemplate to false to preview it with sample order data. To exercise the missing-field case, omit orderNumber from the preview data and inspect the rendering error. A successful preview returns MIME content without sending a message.

CreateEmailTemplate · TestRenderEmailTemplate

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = false

    var createTemplate: Bool = true
    //  Use the same AWS Region for the identity, endpoint, and Signature Version 4.
    var region: String? = "us-west-2"
    let host = CkoStringBuilder()!
    host.append(value: "email.")
    host.append(value: region)
    host.append(value: ".amazonaws.com")

    let signer = CkoAuthAws()!
    //  Supply the credentials from your application's credential provider.
    signer.accessKey = "AWS_ACCESS_KEY_ID"
    signer.secretKey = "AWS_SECRET_ACCESS_KEY"
    signer.region = region
    signer.serviceName = "ses"

    let connection = CkoSocket()!
    connection.requireSslCertVerify = true
    success = connection.connect(hostname: host.getAsString(), port: 443, ssl: true, maxWaitMs: 10000)
    if success != true {
        print("\(connection.lastErrorText!)")
        return
    }

    let rest = CkoRest()!
    success = rest.useConnection(connection: connection, autoReconnect: false)
    if success != true {
        print("\(rest.lastErrorText!)")
        return
    }

    success = rest.setAuthAws(authProvider: signer)
    if success != true {
        print("\(rest.lastErrorText!)")
        return
    }

    //  For temporary AWS credentials, supply the session token from the same provider.
    var sessionToken: String? = ""
    if sessionToken != "" {
        rest.addQueryParam(name: "X-Amz-Security-Token", value: sessionToken)
    }

    if createTemplate == true {
        let request = CkoJsonObject()!
        request.updateString(jsonPath: "TemplateName", value: "OrderReceipt")
        request.updateString(jsonPath: "TemplateContent.Subject", value: "Receipt for {{orderNumber}}")
        request.updateString(jsonPath: "TemplateContent.Text", value: "Thank you, {{firstName}}. Order {{orderNumber}}: {{#each items}}{{quantity}} x {{name}}. {{/each}}")
        request.updateString(jsonPath: "TemplateContent.Html", value: "<p>Thank you, {{firstName}}.</p><ul>{{#each items}}<li>{{quantity}} x {{name}}</li>{{/each}}</ul>")

        rest.addHeader(name: "Content-Type", value: "application/json")
        var setupResponse: String? = rest.fullRequestString(httpVerb: "POST", uriPath: "/v2/email/templates", bodyText: request.emit())
        if rest.lastMethodSuccess != true {
            print("\(rest.lastErrorText!)")
            return
        }

        if rest.responseStatusCode.intValue != 200 {
            print("SES returned HTTP \(rest.responseStatusCode.intValue) \(setupResponse!)")
            return
        }

        print("Template created. Set createTemplate to false to preview it.")
        return
    }

    let order = CkoJsonObject()!
    order.updateString(jsonPath: "firstName", value: "Avery")
    order.updateString(jsonPath: "orderNumber", value: "1042")
    order.updateString(jsonPath: "items[0].name", value: "Notebook")
    order.updateInt(jsonPath: "items[0].quantity", value: 2)
    order.updateString(jsonPath: "items[1].name", value: "Pen")
    order.updateInt(jsonPath: "items[1].quantity", value: 1)
    //  Remove this key to try the missing-field case.
    var tryMissingField: Bool = false
    if tryMissingField == true {
        order.delete(name: "orderNumber")
    }

    let preview = CkoJsonObject()!
    preview.updateString(jsonPath: "TemplateData", value: order.emit())

    rest.addHeader(name: "Content-Type", value: "application/json")
    var responseText: String? = rest.fullRequestString(httpVerb: "POST", uriPath: "/v2/email/templates/OrderReceipt/render", bodyText: preview.emit())
    if rest.lastMethodSuccess != true {
        print("\(rest.lastErrorText!)")
        return
    }

    if rest.responseStatusCode.intValue != 200 {
        print("SES returned HTTP \(rest.responseStatusCode.intValue) \(responseText!)")
        return
    }

    let response = CkoJsonObject()!
    success = response.load(json: responseText)
    if success != true {
        print("\(response.lastErrorText!)")
        return
    }

    print("\(response.string(of: "RenderedTemplate")!)")

}