You need a service to deliver your emails, this can be your own WebService or you can choose one of the many available services, like sendgrid.com which is fairly easy to implement in your Swift app and has a 40k email limit for free.
Here is a Swift 3 example using sendgrid.com service:
Note: before you use this method, signup at sendgrid.com to get the api_user
and api_key
values.
func sendEmail(_ email: String, recipientName: String, subject: String, text: String) {
let params = [
"api_user": ENTER_YOUR_API_USER,
"api_key": HERE_YOU_ENTER_API_KEY,
"to": email,
"toname": recipientName,
"subject": subject,
"html": text,
"from": "noreply@example.com"
]
var parts: [String] = []
for (k, v) in params {
let key = String(describing: k).addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
let value = String(describing: v).addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
parts.append(String(format: "%@=%@", key!, value!))
}
guard let url = URL(string: String(format: "%@?%@", "https://api.sendgrid.com/api/mail.send.json", parts.joined(separator: "&"))) else { return }
let session = URLSession(configuration: .default, delegate: nil, delegateQueue: nil)
let task = session.dataTask(with: url, completionHandler: {
(data, response, error) in
if (error == nil) {
print("Email delivered!")
} else {
print("Email could not be delivered!")
}
})
task.resume()
session.finishTasksAndInvalidate()
}
Usage-1 (plain/text):
sendEmail("recipient@email.com", recipientName: "Recipient Name", subject: "PlainText", text: "This is a PlainText test email.")
Usage-2 (html):
sendEmail("recipient@email.com", recipientName: "", subject: "HTML Test", text: "<html><div>This is a <b>HTML</b> test email.</div></html>")