Skip to content

Instantly share code, notes, and snippets.

@anthonycastelli
Created May 31, 2017 03:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonycastelli/18bcf01d912074fd8b4b5b92b0471b1b to your computer and use it in GitHub Desktop.
Save anthonycastelli/18bcf01d912074fd8b4b5b92b0471b1b to your computer and use it in GitHub Desktop.
Mailgun Mailing Lists Subscribing
//
// Mailgun+Lists.swift
// Canteen
//
// Created by Anthony Castelli on 5/18/17.
//
//
import Foundation
import FormData
import Multipart
extension MailProtocol {
public func addSubscriber(_ email: String, toList list: String) throws {
if let mailgun = self as? Mailgun {
try mailgun.addSubscriber(email, toList: list)
}
}
}
extension Mailgun {
public func addSubscriber(_ email: String, toList list: String) throws {
let uri = try URI("https://api.mailgun.net/v3/lists/\(list)/members")
let req = Request(method: .post, uri: uri)
let basic = "api:\(apiKey)".makeBytes().base64Encoded.makeString()
req.headers["Authorization"] = "Basic \(basic)"
let subscribed = FormData.Field(
name: "subscribed",
filename: nil,
part: Part(
headers: [:],
body: "true".makeBytes()
)
)
let address = FormData.Field(
name: "address",
filename: nil,
part: Part(
headers: [:],
body: email.makeBytes()
)
)
req.formData = [
"subscribed": subscribed,
"address": address
]
let client = try clientFactory.makeClient(
hostname: apiURI.hostname,
port: apiURI.port ?? 443,
securityLayer: .tls(EngineClient.defaultTLSContext())
)
let res = try client.respond(to: req)
guard res.status.statusCode < 400 else {
throw Abort.badRequest
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment