Sample code for 30+ languages & platforms
Swift Requires Chilkat v11.0.0+

Send a Gmail message with a file attachment

See more GMail REST API Examples

Live send. Prepare a small file named attachment.pdf and replace the sample addresses. Add the file as a MIME attachment and upload the complete message as message/rfc822. The response is a Gmail Message. For larger uploads or unreliable connections, see Google’s resumable upload guidance.

Authorize the application with https://www.googleapis.com/auth/gmail.send. The example reads the access token from gmail-token.json in a private working directory. Authorize a desktop application.

Google documentation

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.

    let token = CkoJsonObject()!
    success = token.loadFile(path: "gmail-token.json")
    if success != true {
        print("Could not read gmail-token.json from the private working directory.")
        return
    }

    if (token.jsonType(of: "access_token").intValue != 1) || (token.string(ofEquals: "access_token", value: "", caseSensitive: true) == true) {
        print("An OAuth access token is required.")
        return
    }

    let http = CkoHttp()!
    http.requireSslCertVerify = true
    http.authToken = token.string(of: "access_token")
    let resp = CkoHttpResponse()!
    let reply = CkoJsonObject()!
    let email = CkoEmail()!
    //  Use the authorized mailbox or one of its configured send-as addresses.
    email.from = "Sender <sender@example.com>"
    success = email.add(to: "Recipient", emailAddress: "recipient@example.net")
    if success != true {
        print("\(email.lastErrorText!)")
        return
    }

    email.subject = "Sample message"
    email.charset = "utf-8"
    email.body = "Hello from the Gmail API."
    let fileData = CkoBinData()!
    success = fileData.loadFile(path: "attachment.pdf")
    if success != true {
        print("Could not read attachment.pdf.")
        return
    }

    success = email.addAttachmentBd(filename: "attachment.pdf", binData: fileData, contentType: "application/pdf")
    if success != true {
        print("\(email.lastErrorText!)")
        return
    }

    let mime = CkoBinData()!
    success = email.getMimeBd(bindat: mime)
    if success != true {
        print("\(email.lastErrorText!)")
        return
    }

    success = http.httpBd(verb: "POST", url: "https://gmail.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=media", bd: mime, contentType: "message/rfc822", response: resp)
    if resp.statusCode.intValue == 0 {
        print("Gmail did not return an HTTP response.")
        return
    }

    if (success != true) || (resp.statusCode.intValue < 200) || (resp.statusCode.intValue >= 300) {
        print("Gmail HTTP \(resp.statusCode.intValue)")
        success = reply.load(json: resp.bodyStr)
        if success == true {
            print("\(reply.string(of: "error.message")!)")
        }

        return
    }

    success = reply.load(json: resp.bodyStr)
    if success != true {
        print("Expected a Gmail JSON response.")
        return
    }

    if (reply.jsonType(of: "id").intValue != 1) || (reply.string(ofEquals: "id", value: "", caseSensitive: true) == true) {
        print("Expected id in the response.")
        return
    }

    print("Gmail message ID: \(reply.string(of: "id")!)")

}