Sending emails — #iOS 11

Andy O'Sullivan
4 min readMar 22, 2017
icons from icons8.com

Something easy but useful today — how to send emails from an app. How it basically works is that you can open the default mail client on the device, via the app, and pre-populate it with information — like email addresses, email subjects, content etc.

Let’s jump straight to it — open a new project in Xcode and go to the Main.storyboard. Add a Button, I’ve changed its attributes so it looks like this:

Open the Assistant Editor (via the little button with the two circles) to see the code beside the Storyboard:

Control-drag from the Button to create an Action function, here I call it “onEmailButtonTap”, remembering to select Action and not Outlet:

which results in:

Great. We now have a function that’ll run when the Button is tapped by the user. We’ll add code to this shortly.

First we need to add some more code so we can send emails. To start with, add:

import MessageUI

to the start of the file, under where is says:

import UIKit

This brings in the “library” we need for emailing. Now, where it says:

class ViewController: UIViewController {

add:

 , MFMailComposeViewControllerDelegate

i.e.

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {

We are “implementing” the MFMailComposeViewControllerDelegate. If you remember from this TextField tutorial, delegates are super-handy ways of carrying out certain tasks. They provide pre-written functions that you can use / add code to.

Add one of those delegate functions now:

func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
dismiss(animated: true, completion: nil)
}

You don’t need to do anything with this function, but it’s needed. What it’s doing is “dismissing” (i.e. getting rid of”) the MFMailComposeViewController — which is a new “screen” that opens up when we send an email — after the email has been sent.

We haven’t written the code yet to open that screen, so let’s do that now. In the onEmailButtonTap function, add this code:

@IBAction func onEmailButtonTap(_ sender: Any) {
if MFMailComposeViewController.canSendMail() {
let emailVC = MFMailComposeViewController()
emailVC.mailComposeDelegate = self
emailVC.setToRecipients(["whatever@wherever.com"])
emailVC.setMessageBody("OMG I just sent an email!", isHTML: false)
emailVC.setSubject("Email from app")
emailVC.setCcRecipients(["whoever@whereever.com"])
present(emailVC, animated: true)
} else {
//do something else
}
}

What’s going on?

if MFMailComposeViewController.canSendMail() {

is checking that the user has a default mail client on their device. If they don’t, don’t try to send a mail!

let emailVC = MFMailComposeViewController()

creates a new variable of type MFMailComposeViewController. This is the new “screen” / View Controller I mentioned. Note that I could have called “emailVC” anything, it’s just a variable name.

emailVC.mailComposeDelegate = self

is a necessary step to specify that the MFMailComposeViewController instance we just created will use this file as its delegate.

emailVC.setToRecipients(["whatever@wherever.com"])

is where we set the recipient of the email. To send to more than one:

emailVC.setToRecipients(["whatever@wherever.com","here@there.ie"])

i.e. it’s basically an array of Strings, which each String being an email address.

emailVC.setMessageBody("OMG I just sent an email!", isHTML: false)

is where you set what the email content will be. The first parameter i.e. “OMG I just sent an email!” is the content, and the second “isHTML” is there to specify whether the content is in HTML format or not.

HTML is how website content is created, so you could use it to structure the content of the email. Not important for now!

emailVC.setSubject(“Email from app”)

does what it says on the tin, setting the email subject.

emailVC.setCcRecipients(["email@address.com"])

sets any “CC” recipients, if you so wish. If you don’t just leave that line out.

Finally:

present(emailVC, animated: true)

actually then shows this new View Controller on screen. What does that look like exactly? Run the app and hit the button to find out! You’ll need to run on an actual device, not the Simulator … as the Simulator won’t have email!

When the app runs you should see (I changed the background color to be grey to show up on this white background!):

Hit the Button and you should see:

Amazing! Hit the Send or Cancel and you’ll be brought back to the main View Controller.

Note the “from” email is blacked out — this is so I don’t show everyone here my private email address! The emails sent via this method aren’t actually sent from the “app”, they’re sent via the app, using whatever email account is set up on the device.

Any comments or issues, let me know below!

If you found this useful / thought it almost unbearingly amazing, then please hit the little recommend heart below! Or go all out and Share!! Andy

--

--