January 18, 2021



Swift send email from your iOS 9 app

swift send email

Swift send email from your iOS app

Swift send email from your iOS app. How do we do that…
It was easier than I first thought. At least with this method. Using the MessageUI and have the app to pre-fill an email and using iOS mail to send it.

First we need to import the MessageUI. We will do that from the view controller in my example code. By the way you can download the example code from my github. Just go to https://github.com/solron/Swift-Send-Email and download the code.

The we will need to setup the MFMailComposeViewControllerDelegate.

// Set delegate
class MyViewController: UIViewController,MFMailComposeViewControllerDelegate {
// Code goes here

My swift send email example only contains a send button on the user interface. Not showing here how to link an action to a button. But inside the button action code we do something like this:

@IBAction func btnSendEmail(sender: AnyObject) {
let email = MFMailComposeViewController()
email.mailComposeDelegate = self
email.setSubject("Subject goes here")
email.setMessageBody("Some example text", isHTML: false)
email.setToRecipients(["post@email.com"]) // the recipient email address
if MFMailComposeViewController.canSendMail() {
presentViewController(email, animated: true, completion: nil)

The code above will populate all fields needed to send you email. Subject field, recipient address and message body. You can of course edit any of these in the email that pops up before you send it. Because you will need to confirm the mail. Just like any other email you send. Just that you dont have to enter the information your self. The fields doesn’t have to be fixed in your code either. You can have dynamic values changed programatically based on anything you want.

Last we will need to enter the function in order for the delegate to work. And that is something like this:
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
dismissViewControllerAnimated(true, completion: nil)

Now you have all the code you need to send emails from your app.

Thats it for swift send email.

Happy emailing!