Make sure SENDGRID_API_KEY is set in your environment. This can be set in the
Xcode scheme, or specified in your docker-compose.yml, or even provided as
part of a swift run command.
Optionally, explicitly initialize the provider (this is strongly recommended, as
otherwise a missing API key will cause a fatal error some time later in your
application):
app.sendgrid.initialize()
Now you can access the client at any time:
app.sendgrid.client
Using the API
You can use all of the available parameters here to build your SendGridEmail
Usage in a route closure would be as followed:
import SendGrid
let email = SendGridEmail(…)
return req.application.sendgrid.client.send([email], on: req.eventLoop)
Error handling
If the request to the API failed for any reason a SendGridError is the result
of the future, and has an errors property that contains an array of errors
returned by the API:
return req.application.sendgrid.client.send([email], on: req.eventLoop).flatMapError { error in
if let sendgridError = error as? SendGridError {
req.logger.error("\(error)")
}
// ...
}
SendGrid Provider for Vapor
Adds a mail backend for SendGrid to the Vapor web framework. Send simple emails, or leverage the full capabilities of SendGrid’s V3 API.
Setup
Add the dependency to Package.swift:
Make sure
SENDGRID_API_KEY
is set in your environment. This can be set in the Xcode scheme, or specified in yourdocker-compose.yml
, or even provided as part of aswift run
command.Optionally, explicitly initialize the provider (this is strongly recommended, as otherwise a missing API key will cause a fatal error some time later in your application):
Now you can access the client at any time:
Using the API
You can use all of the available parameters here to build your
SendGridEmail
Usage in a route closure would be as followed:Error handling
If the request to the API failed for any reason a
SendGridError
is the result of the future, and has anerrors
property that contains an array of errors returned by the API: