The fastest way of coding is doing a lot of copy-paste. I know, you shouldn’t. But most of us do … so lets be honest about that 🙂
Following some copy-paste-ready Swift code for sending e-mails form your iOS app.
// MailerViewController.swift
import UIKit
import MessageUI
class MailerViewController: UIViewController, MFMailComposeViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let mSubject = "The subject of the e-mail"
let mBody = "Hi! This is an e-mail. Please se the attached file."
let mRecipients = ["info@devjockeys.com", "martin@devjockeys.com", "some_recipient@some_email.com"]
let mAttachment = "Some content".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let mAttachmentName = "attachment_filename.txt"
doEmail(subject: mSubject, body: mBody, recipients: mRecipients, attachment: mAttachment, attachmentName: mAttachmentName)
}
func doEmail(subject: String, body: String, recipients: Array, attachment: Data, attachmentName: String ) {
if MFMailComposeViewController.canSendMail() {
let mailer = MFMailComposeViewController()
mailer.mailComposeDelegate = self
// the subject
mailer.setSubject(subject)
// the recepients: an Array of Strings
mailer.setToRecipients(recipients)
// make an attachment. You can attach anything, as long as it is a "Data?" object
mailer.addAttachmentData(attachment, mimeType: "application/octet-stream", fileName: attachmentName)
// the message body
mailer.setMessageBody(body, isHTML: false)
// present the mailer
self.present(mailer, animated: true, completion: nil)
}
else
{
let alert = UIAlertController(title: "Mail Error", message: "Your device has not been configured to send e-mails", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(okAction)
self.present(alert,animated: true,completion: nil)
}
}
// mailer delegate
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
var message = ""
switch (result)
{
case .cancelled: message = "You cancelled the operation and no e-mail message was sent."
case .saved: message = "You saved the e-mail message in the drafts folder."
case .sent: message = "Mail send: e-mail message sent successfully."
case .failed: message = "Mail failed: the e-mail message was not sent. Please check your e-mail settings."
}
let alert = UIAlertController(title: "Mailer", message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(okAction)
self.present(alert,animated: true,completion: nil)
// Remove the mail view
self.dismiss(animated: true, completion: nil)
}
}