Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/vapor-community/mailgun
📧 Service to assist with sending emails from Vapor apps
https://github.com/vapor-community/mailgun
email mailgun swift vapor vapor-3 vapor-4 vapor-service vapor-swift
Last synced: 3 days ago
JSON representation
📧 Service to assist with sending emails from Vapor apps
- Host: GitHub
- URL: https://github.com/vapor-community/mailgun
- Owner: vapor-community
- Created: 2018-03-10T05:05:45.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2024-05-30T12:57:40.000Z (9 months ago)
- Last Synced: 2025-02-12T06:10:46.945Z (9 days ago)
- Topics: email, mailgun, swift, vapor, vapor-3, vapor-4, vapor-service, vapor-swift
- Language: Swift
- Homepage:
- Size: 138 KB
- Stars: 120
- Watchers: 13
- Forks: 32
- Open Issues: 11
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Mailgun
[](https://vapor.team)
[](http://cocoapods.org/pods/FASwift)
[](http://swift.org)
[](https://vapor.codes)##
`Mailgun` is a Vapor 4 service for a popular [email sending API](https://www.mailgun.com/)
> Note: Vapor3 version is available in `vapor3` branch and from `3.0.0` tag## Installation
Mailgun can be installed with Swift Package Manager```swift
.package(url: "https://github.com/vapor-community/mailgun.git", from: "5.0.0").target(name: "App", dependencies: [
.product(name: "Vapor", package: "vapor"),
.product(name: "Mailgun", package: "mailgun")
])
```## Usage
### Sign up and set up a Mailgun account [here](https://www.mailgun.com/)
Make sure you get an API key and register a custom domain### Configure
In `configure.swift`:
```swift
import Mailgun// Called before your application initializes.
func configure(_ app: Application) throws {
/// case 1
/// put into your environment variables the following keys:
/// MAILGUN_API_KEY=...
app.mailgun.configuration = .environment/// case 2
/// manually
app.mailgun.configuration = .init(apiKey: "")
}
```> Note: If your private api key begins with `key-`, be sure to include it
### Declare all your domains
```swift
extension MailgunDomain {
static var myApp1: MailgunDomain { .init("mg.myapp1.com", .us) }
static var myApp2: MailgunDomain { .init("mg.myapp2.com", .eu) }
static var myApp3: MailgunDomain { .init("mg.myapp3.com", .us) }
static var myApp4: MailgunDomain { .init("mg.myapp4.com", .eu) }
}
```Set default domain in `configure.swift`
```swift
app.mailgun.defaultDomain = .myApp1
```### Usage
`Mailgun` is available on both `Application` and `Request`
```swift
// call it without arguments to use default domain
app.mailgun().send(...)
req.mailgun().send(...)// or call it with domain
app.mailgun(.myApp1).send(...)
req.mailgun(.myApp1).send(...)
```#### In `configure.swift`
```swift
import Mailgun// Called before your application initializes.
func configure(_ app: Application) throws {
/// configure mailgun/// then you're ready to use it
app.mailgun(.myApp1).send(...).whenSuccess { response in
print("just sent: \(response)")
}
}
```> 💡 NOTE: All the examples below will be with `Request`, but you could do the same with `Application` as in example above.
#### In `routes.swift`:
##### Without attachments
```swift
import Mailgunfunc routes(_ app: Application) throws {
app.post("mail") { req -> EventLoopFuture in
let message = MailgunMessage(
from: "[email protected]",
to: "[email protected]",
subject: "Newsletter",
text: "This is a newsletter",
html: "This is a newsletter
"
)
return req.mailgun().send(message)
}
}
```##### With attachments
```swift
import Mailgunfunc routes(_ app: Application) throws {
app.post("mail") { req -> EventLoopFuture in
let fm = FileManager.default
guard let attachmentData = fm.contents(atPath: "/tmp/test.pdf") else {
throw Abort(.internalServerError)
}
let bytes: [UInt8] = Array(attachmentData)
var bytesBuffer = ByteBufferAllocator().buffer(capacity: bytes.count)
bytesBuffer.writeBytes(bytes)
let attachment = File.init(data: bytesBuffer, filename: "test.pdf")
let message = MailgunMessage(
from: "[email protected]",
to: "[email protected]",
subject: "Newsletter",
text: "This is a newsletter",
html: "This is a newsletter
",
attachments: [attachment]
)
return req.mailgun().send(message)
}
}
```##### With template (attachments can be used in same way)
```swift
import Mailgunfunc routes(_ app: Application) throws {
app.post("mail") { req -> EventLoopFuture in
let message = MailgunTemplateMessage(
from: "[email protected]",
to: "[email protected]",
subject: "Newsletter",
template: "my-template",
templateData: ["foo": "bar"]
)
return req.mailgun().send(message)
}
}
```##### Setup content through Leaf
Using Vapor Leaf, you can easily setup your HTML Content.
First setup a leaf file in `Resources/Views/Emails/my-email.leaf`
```html
Hi #(name)
```
With this, you can change the `#(name)` with a variable from your Swift code, when sending the mail
```swift
import Mailgunfunc routes(_ app: Application) throws {
app.post("mail") { req -> EventLoopFuture in
let content = try req.view().render("Emails/my-email", [
"name": "Bob"
])let message = Mailgun.Message(
from: "[email protected]",
to: "[email protected]",
subject: "Newsletter",
text: "",
html: content
)return req.mailgun().send(message)
}
}
```##### Setup routes
```swift
public func configure(_ app: Application) throws {
// sets up a catch_all forward for the route listed
let routeSetup = MailgunRouteSetup(forwardURL: "http://example.com/mailgun/all", description: "A route for all emails")
app.mailgun().setup(forwarding: routeSetup).whenSuccess { response in
print(response)
}
}
```##### Handle routes
```swift
import Mailgunfunc routes(_ app: Application) throws {
let mailgunGroup = app.grouped("mailgun")
mailgunGroup.post("all") { req -> String in
do {
let incomingMail = try req.content.decode(MailgunIncomingMessage.self)
print("incomingMail: (incomingMail)")
return "Hello"
} catch {
throw Abort(.internalServerError, reason: "Could not decode incoming message")
}
}
}
```##### Creating templates
```swift
import Mailgunfunc routes(_ app: Application) throws {
let mailgunGroup = app.grouped("mailgun")
mailgunGroup.post("template") { req -> EventLoopFuture in
let template = MailgunTemplate(name: "my-template", description: "api created :)", template: "Hello {{ name }}
")
return req.mailgun().createTemplate(template)
}
}
```