A Swift library for interacting with the Gmail API, allowing developers to easily integrate Gmail functionalities into their iOS and macOS applications.
This is still a work in progress and my first Swift project, however, feel free to open an issue and request a feature. They are quick to add.
- labels
- messages (partial support)
You can install the Swift Gmail SDK using the Swift Package Manager. Add the following dependency to your
Package.swift file:
dependencies: [
.package(url: "https://github.com/levzem/SwiftGmailClient", from: "0.1.9")
],
targets: [
.target(
name: "YourApp",
dependencies: ["SwiftGmailClient"]
)
]To use the Swift Gmail client in your application, follow these steps:
-
Acquire the user's OAuth 2.0 credentials: Before using this client, you will need to ask the user to authenticate your application with their Google account. This typically involves using the Google Sign-In SDK or manually handling OAuth 2.0 flows.
- For Google Sign-In, you can follow the Google Sign-In for iOS documentation to set up the necessary configurations and obtain the credentials.
- Alternatively, you can use OAuth 2.0 directly by following the OAuth 2.0 documentation.
-
Import the SDK: In your Swift file, import the Swift Gmail module.
import SwiftGmailClient -
Initialize the client: Initialize the client with your user's OAuth 2.0 credentials.
let gmailService = GmailService( credentialsProvider: SimpleCredentialsProvider(accessToken: <ACCESS_TOKEN>) )
let gmailService = GmailService( credentialsProvider: RefreshingCredentialsProvider( accessToken: <ACCESS_TOKEN>, refreshToken: <REFRESH_TOKEN>, clientID: <OAUTH_CLIENT_ID>, clientSecret: <OAUTH_CLIENT_SECRET> ) )
-
List user's labels: To list a user's email labels, create a
ListLabelsRequestobject and call thelistmethod.let result = await gmail.users.labels.list() switch result { case .success(let response): print("Labels found: \(response.labels)") case .failure(let error): print("Failed to fetch user's labels: \(error.localizedDescription)") } }
-
The call pattern mirrors the Google Gmail REST resources, so you can refer to the Gmail API documentation for more details on available methods and their parameters.
To run the tests, you can use the following command in your terminal:
swift testYou will need to set up some OAuth credentials. You can do this by creating a .env file and adding the following
lines:
GMAIL_OAUTH_ACCESS_TOKEN=<YOUR_ACCESS_TOKEN>
GMAIL_OAUTH_REFRESH_TOKEN=<YOUR_REFRESH_TOKEN>
GMAIL_OAUTH_CLIENT_ID=<YOUR_CLIENT_ID>
GMAIL_OAUTH_CLIENT_SECRET=<YOUR_CLIENT_SECRET>
Alternatively, you can set the environment variables directly in your terminal.
I would like to improve this in the future, but for now, this is the best way to test the library.