📧 SendGridKit is a Swift package that helps you communicate with the SendGrid API in your Server Side Swift applications.
Send simple emails or leverage the full capabilities of SendGrid's V3 API.
Use the SPM string to easily include the dependendency in your Package.swift
file
.package(url: "https://github.com/vapor-community/sendgrid-kit.git", from: "3.1.0"),
and add it to your target's dependencies:
.product(name: "SendGridKit", package: "sendgrid-kit"),
Register the config and the provider.
import AsyncHTTPClient
import SendGridKit
let httpClient = HTTPClient(...)
let sendGridClient = SendGridClient(httpClient: httpClient, apiKey: "YOUR_API_KEY")
You can use all of the available parameters here to build your SendGridEmail
.
Usage in a route closure would be as followed:
import SendGridKit
let email = SendGridEmail(...)
try await sendGridClient.send(email: email)
If the request to the API failed for any reason a SendGridError
is thrown, which has an errors
property that contains an array of errors returned by the API.
Simply ensure you catch errors thrown like any other throwing function.
import SendGridKit
do {
try await sendGridClient.send(email: email)
} catch let error as SendGridError {
print(error)
}
SendGridKit supports SendGrid's Email Address Validation API, which provides detailed information on the validity of email addresses.
import SendGridKit
let sendGridClient = SendGridEmailValidationClient(httpClient: .shared, apiKey: "YOUR_API_KEY")
// Create a validation request
let validationRequest = EmailValidationRequest(email: "[email protected]")
// Validate the email
do {
let validationResponse = try await sendGridClient.validateEmail(validationRequest)
// Check if the email is valid
if validationResponse.result?.verdict == .valid {
print("Email is valid with score: \(validationResponse.result?.score)")
} else {
print("Email is invalid")
}
// Access detailed validation information
if validationResponse.result?.checks?.domain?.isSuspectedDisposableAddress ?? true {
print("Warning: This is probably a disposable email address")
}
if validationResponse.result?.checks?.localPart?.isSuspectedRoleAddress {
print("Note: This is a role-based email address")
}
} catch {
print("Validation failed: \(error)")
}
For validating multiple email addresses at once, SendGridKit provides access to SendGrid's Bulk Email Address Validation API. This requires uploading a CSV file with email addresses:
import SendGridKit
import Foundation
let sendGridClient = SendGridEmailValidationClient(httpClient: .shared, apiKey: "YOUR_API_KEY")
do {
// Step 1: Create a CSV file with email addresses
let csvContent = """
emails
[email protected]
[email protected]
[email protected]
"""
guard let csvData = csvContent.data(using: .utf8) else {
throw SomeError.invalidCSV
}
// Step 2: Upload the CSV file
let fileUpload = try await sendGridClient.uploadBulkEmailValidationFile(
fileData: csvData,
fileType: .csv
)
guard fileUpload.succeeded, let jobID = fileUpload.jobID else {
throw SomeError.uploadError
}
// Step 4: Check job status (poll until completed)
var jobStatus = try await sendGridClient.checkBulkEmailValidationJob(by: jobID)
while jobStatus.status != .done {
print("Job \(jobStatus.id) status: \(jobStatus.status) - \(jobStatus.segmentsProcessed)/\(jobStatus.segments) segments processed")
// Wait before checking again (implement your own backoff strategy)
try? await Task.sleep(nanoseconds: 5_000_000_000) // 5 seconds
jobStatus = try await sendGridClient.checkBulkEmailValidationJob(by: jobID)
}
} catch {
print("Bulk validation failed: \(error)")
}