Skip to content

Instantly share code, notes, and snippets.

@vzsg
Created October 4, 2018 19:40
Show Gist options
  • Save vzsg/9c69419fd33a6ffd592536f519b67731 to your computer and use it in GitHub Desktop.
Save vzsg/9c69419fd33a6ffd592536f519b67731 to your computer and use it in GitHub Desktop.
Custom service and DirectoryConfig usage example (Vapor 3)
import Service
import Foundation
import SwiftSMTP
struct EmailSenderConfig: Service {
let fromEmail: String
let fromName: String
let smtpHostname: String
let smtpPort: Int
let smtpEmail: String
let smtpPassword: String
}
final class EmailSender: ServiceType {
private let header: String
private let footer: String
private let config: EmailSenderConfig
private init(header: String, footer: String, config: EmailSenderConfig) {
self.header = header
self.footer = footer
self.config = config
}
static func makeService(for worker: Container) throws -> EmailSender {
let directoryConfig = try worker.make(DirectoryConfig.self)
let header = try String(contentsOfFile: directoryConfig.workDir + "Resources/mail-header.html")
let footer = try String(contentsOfFile: directoryConfig.workDir + "Resources/mail-footer.html")
return EmailSender(header: header, footer: footer, config: try worker.make())
}
func send(to email: String, name: String, subject: String = "***", content: String) {
let html = header + content + footer
let mail = Mail(
from: Mail.User(name: config.fromName, email: config.fromEmail),
to: [Mail.User(name: name, email: email)],
subject: subject,
text: html)
SMTP(
hostname: config.smtpHostname,
email: config.smtpEmail,
password: config.smtpPassword,
port: config.smtpPort,
tlsMode = .requireTLS
).send(mail)
}
}
// ... imports omitted ...
public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws {
// ... other services omitted to keep the sample short ...
// TODO: you should consider using environment variables instead of hardcoding credentials
let smtpConfig = EmailSenderConfig(
fromEmail: "[email protected]",
fromName: "Foo Bar",
smtpHostname: "something.something",
smtpPort: 465,
smtpEmail: "my",
smtpPassword: "*******")
services.register(smtpConfig)
services.register(EmailSender.self)
}
// ... imports omitted ...
/// Register your application's routes here.
public func routes(_ router: Router) throws {
// ... other routes omitted ...
router.get("email") { req -> String in
let sender = try req.make(EmailSender.self)
sender.send(to: "[email protected]", name: "Baz Qux", subject: "Test Email", content: "Hello World!")
return "OK"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment