• Stars
    star
    119
  • Rank 297,930 (Top 6 %)
  • Language
    Swift
  • Created over 6 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

📧 Service to assist with sending emails from Vapor apps

Mailgun

Discord Platforms Swift 5.2 Vapor 4

Mailgun is a Vapor 4 service for a popular email sending API

Note: Vapor3 version is available in vapor3 branch and from 3.0.0 tag

Installation

Mailgun can be installed with Swift Package Manager

.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

Make sure you get an API key and register a custom domain

Configure

In configure.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: "<api key>")
}

Note: If your private api key begins with key-, be sure to include it

Declare all your domains

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

app.mailgun.defaultDomain = .myApp1

Usage

Mailgun is available on both Application and Request

// 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

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
import Mailgun

func routes(_ app: Application) throws {
    app.post("mail") { req -> EventLoopFuture<ClientResponse> in
        let message = MailgunMessage(
            from: "[email protected]",
            to: "[email protected]",
            subject: "Newsletter",
            text: "This is a newsletter",
            html: "<h1>This is a newsletter</h1>"
        )
        return req.mailgun().send(message)
    }
}
With attachments
import Mailgun

func routes(_ app: Application) throws {
    app.post("mail") { req -> EventLoopFuture<ClientResponse> 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: "<h1>This is a newsletter</h1>",
            attachments: [attachment]
        )
        return req.mailgun().send(message)
    }
}
With template (attachments can be used in same way)
import Mailgun

func routes(_ app: Application) throws {
    app.post("mail") { req -> EventLoopFuture<ClientResponse> 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>
    <body>
        <p>Hi #(name)</p>
    </body>
</html>

With this, you can change the #(name) with a variable from your Swift code, when sending the mail

import Mailgun

func routes(_ app: Application) throws {
    app.post("mail") { req -> EventLoopFuture<ClientResponse> 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
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
import Mailgun

func 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
import Mailgun

func routes(_ app: Application) throws {
    let mailgunGroup = app.grouped("mailgun")
    mailgunGroup.post("template") { req -> EventLoopFuture<ClientResponse> in
        let template = MailgunTemplate(name: "my-template", description: "api created :)", template: "<h1>Hello {{ name }}</h1>")
        return req.mailgun().createTemplate(template)
    }
}

More Repositories

1

awesome-vapor

A curated list of Vapor-related awesome projects.
Ruby
1,174
star
2

sockets

🔌 Non-blocking TCP socket layer, with event-driven server and client.
Swift
575
star
3

HTMLKit

Create and render HTML templates with HTMLKit
Swift
403
star
4

stripe

Stripe library for Vapor
Swift
179
star
5

example

Starting point for using the Vapor framework.
Swift
164
star
6

Imperial

Federated Authentication with OAuth providers
Swift
153
star
7

postgresql

Robust PostgreSQL interface for Swift
Swift
131
star
8

stripe-kit

A Swift on Server SDK for the Stripe API
Swift
125
star
9

vapor-aws-lambda-runtime

Run your Vapor api server on AWS Lambda using the official Swift Server runtime.
Swift
105
star
10

slack-bot

An example Slack Bot application built with Vapor in Swift.
Swift
76
star
11

chat-example

Realtime chat example built with Vapor.
CSS
73
star
12

ferno

Vapor Firebase Realtime database provider
Swift
71
star
13

sendgrid

SendGrid-powered mail backend for Vapor
Swift
71
star
14

postgresql-provider

PostgreSQL Provider for the Vapor web framework.
Swift
70
star
15

chat-ios-example

A basic realtime chat project using Vapor on the server -- See vapor-chat.herokuapp.com
Swift
68
star
16

pagination

Simple Vapor 3 Pagination
Swift
64
star
17

apns

Vapor APNS for iOS
Swift
60
star
18

docker

Docker images for Vapor.
Dockerfile
60
star
19

leaf-markdown

Markdown renderer for Vapor
Swift
60
star
20

wkhtmltopdf

Generate and return PDFs from Vapor views
Swift
58
star
21

PassKit

🎟️ 📦 A package for creating passes and orders for Apple Wallet with Vapor.
Swift
58
star
22

forms

Brings simple, dynamic and re-usable web form handling to Vapor.
Swift
56
star
23

Lingo-Vapor

Vapor provider for Lingo - the Swift localization library
Swift
55
star
24

markdown

Swift cmark wrapper for SwiftPM
Swift
50
star
25

google-cloud-kit

Swift
46
star
26

VaporMonitoring

Monitoring for Vapor
Swift
46
star
27

todo-example

An example implementation for http://todobackend.com
Swift
46
star
28

google-cloud

Access GoogleCloud APIs using Vapor
Swift
45
star
29

CSRF

A package to add protection to Vapor against CSRF attacks.
Swift
41
star
30

mongo-provider

MongoDB Provider for Vapor
Swift
40
star
31

vapor-ext

⚙️ A collection of Swift extensions for wide range of Vapor data types and classes
Swift
36
star
32

async

⏱ Promises and reactive-streams in Swift built for high-performance and scalability.
Swift
35
star
33

bcrypt

Swift implementation of the BCrypt password hashing function
Swift
34
star
34

swiftybeaver-provider

SwiftyBeaver Logging Provider for Vapor, the server-side Swift web framework https://swiftybeaver.com
Swift
33
star
35

json

Convenience wrapper for Foundation JSON.
Swift
30
star
36

mysql-provider

MySQL provider for the Vapor web framework.
Swift
30
star
37

tls

🔒 Non-blocking, event-driven TLS built on OpenSSL & macOS security.
Swift
29
star
38

styleguide

An opinionated, unofficial style guide for developing production-level Vapor applications
28
star
39

mongo-driver

MongoDB driver for Fluent
Swift
28
star
40

open-api

OpenAPI integration for Vapor.
Swift
27
star
41

node

A formatted data encapsulation meant to facilitate the transformation from one object to another
Swift
25
star
42

penny

Penny Coin is a Slack Bot in Swift written with Vapor. It is used to track coins in the Vapor community.
Swift
23
star
43

postgresql-driver

PostgreSQL driver for Fluent
Swift
23
star
44

gzip-provider

gzip support for Vapor
Swift
21
star
45

VaporTwilioService

Twilio API provider for all your Vapor needs
Swift
19
star
46

redis-provider

Adds Redis Cache to Vapor
Swift
17
star
47

auth-provider

Middleware and conveniences for using Auth in Vapor.
Swift
17
star
48

bits

A bite sized library for dealing with bytes.
Swift
16
star
49

fluent-example

Starting point for using the Fluent framework.
Swift
16
star
50

auth-example

Authentication example for Vapor 1.0.
Swift
16
star
51

mustache-provider

Render Mustache templates in Vapor
Swift
16
star
52

soto-cognito-authentication

Authenticating with AWS Cognito for Vapor
Swift
15
star
53

JWT3PA

Handles routes, registration and login for Sign in with Apple and Google
Swift
14
star
54

fluent-provider

A provider for including Fluent in Vapor applications
Swift
13
star
55

queues-database-hooks

A package for tracking queue job statuses in your database via Queue Hooks
Swift
13
star
56

onesignal

Swift
12
star
57

openai

A Swift package for interacting with the OpenAI API using Vapor
Swift
12
star
58

moat

A line of defense for your Vapor application including attack filtering + extras.
Swift
12
star
59

telesign-provider

A Telesign provider for Vapor.
Swift
10
star
60

debugging

A library to aid Vapor users with better debugging around the framework
Swift
10
star
61

sendgrid-kit

📧 A Swift on Server SDK for the SendGrid API
Swift
10
star
62

sqlite-provider

SQLite3 provider for Vapor
Swift
10
star
63

sqlite-driver

SQLite driver for Fluent
Swift
10
star
64

pokedex-example

Pokédex example created with Vapor
Swift
9
star
65

dashboard-example

A dashboard site showing some
CSS
9
star
66

jwt-provider

(Deprecated) Adds conveniences for using JWTs in Vapor 2.
Swift
9
star
67

board-example

A demonstration of a board written in Vapor demonstrating database relationships.
Swift
9
star
68

random

Module for generating random bytes and numbers.
Swift
8
star
69

csqlite

C module map for SQLite
Swift
8
star
70

repository-template

💧 A starting point for Vapor APIs... According the Style Guide
Swift
8
star
71

cpostgresql

PostgreSQL C module map
Swift
7
star
72

vapor-sitemap

A dynamic sitemap generator for Vapor.
Swift
7
star
73

mars-rovers

View photos from the Mars rovers.
Swift
7
star
74

kitura-provider

Use IBM's Kitura HTTP server in your Vapor application.
Swift
7
star
75

sublime-leaf

Leaf syntax highlighting for Sublime Text
7
star
76

Vii

Vii attempts to reverse engineer an existing database into Vapor 4 compatible models
Swift
7
star
77

documentation-zh

Documentation markdown for all Vapor packages in Chinese.
HTML
7
star
78

leaf-provider

Add leaf templating into your vapor app
Swift
7
star
79

htmlkit-vapor-provider

Swift
6
star
80

PackageCatalogAPI

A replacement for the IBM Swift Package Catalog.
Swift
6
star
81

ctls

LibreSSL / OpenSSL module map for Swift
Swift
6
star
82

migrator

A package for updating from Vapor 1 to Vapor 2
Swift
6
star
83

queues-mongo-driver

A MongoDB implementation for https://github.com/vapor/queues
Swift
6
star
84

libc

Wraps Linux and OS X libc
Swift
6
star
85

yeoman

Yeoman generators for Vapor.
Swift
6
star
86

polymorphic

Syntax for easily accessing values from generic data.
Swift
5
star
87

clibressl

LibreSSL wrapped in a Swift package.
C
5
star
88

light-template

An extremely lightweight, no frills template for Vapor web apps.
Swift
5
star
89

vapor-extensions

A collection of Swift extensions, with handy methods, syntactic sugar, and performance improvements for wide range of Vapor data types and classes
Swift
5
star
90

MongoKitten-Provider

Integrate MongoKitten with Vapor
Swift
5
star
91

cmysql

MySQL C module map
Swift
5
star
92

postman-provider

Postman Provider for Vapor
Swift
5
star
93

MultiLogging

Logging utility package for Vapor 3
Swift
5
star
94

checkpoint

Verify's Amazon Alexa requests
Swift
4
star
95

GatewayAPIKit

A Swift package for sending SMS using GatewayAPI
Swift
4
star
96

swift

Helps manage and install Swift 3 versions.
Shell
4
star
97

vapor-elementary

A modern and efficient HTML rendering library - inspired by SwiftUI, built for the web.
Swift
4
star
98

jobs-postgresql-driver

A PostgreSQL Persistance Layer for the Vapor Jobs framework
Swift
4
star
99

HTMLKit-Components

This package contains common UI-components wich are build with HTMLKit.
Swift
4
star
100

swift-dependency-submission

Calculates dependencies for a Swift build-target and submits the list to the Dependency Submission API
Swift
4
star