Mailgun
is a Vapor 3 service for a popular email sending API
Vapor Mailgun Service can be installed with Swift Package Manager
.package(url: "https://github.com/twof/VaporMailgunService.git", from: "1.5.0")
Sign up and set up a Mailgun account here
Make sure you get an API key and register a custom domain
In configure.swift
:
let mailgun = Mailgun(apiKey: "<api key>", domain: "mg.example.com")
services.register(mailgun, as: Mailgun.self)
Note: If your private api key begins with
key-
, be sure to include it
In routes.swift
:
router.post("mail") { (req) -> Future<Response> in
let message = Mailgun.Message(
from: "postmaster@example.com",
to: "example@gmail.com",
subject: "Newsletter",
text: "This is a newsletter",
html: "<h1>This is a newsletter</h1>"
)
let mailgun = try req.make(Mailgun.self)
return try mailgun.send(message, on: req)
}
router.post("mail") { (req) -> Future<Response> in
let fm = FileManager.default
guard let attachmentData = fm.contents(atPath: "/tmp/test.pdf") else {
throw Abort(.internalServerError)
}
let attachment = File(data: attachmentData, filename: "test.pdf")
let message = Mailgun.Message(
from: "postmaster@example.com",
to: "example@gmail.com",
subject: "Newsletter",
text: "This is a newsletter",
html: "<h1>This is a newsletter</h1>",
attachments: [attachment]
)
let mailgun = try req.make(Mailgun.self)
return try mailgun.send(message, on: req)
}
public func boot(_ app: Application) throws {
// sets up a catch_all forward for the route listed
let routeSetup = RouteSetup(forwardURL: "http://example.com/mailgun/all", description: "A route for all emails")
let mailgunClient = try app.make(Mailgun.self)
try mailgunClient.setup(forwarding: routeSetup, with: app).map { (resp) in
print(resp)
}
}
mailgunGroup.post("all") { (req) -> Future<String> in
do {
return try req.content.decode(IncomingMailgun.self).map { (incomingMail) in
return "Hello"
}
} catch {
throw Abort(HTTPStatus.internalServerError, reason: "Could not decode incoming message")
}
}