Send an email within the App
Implementing a button for sending an email within the app can be useful for customer support and have direct feedback with your users. In this short tutorial, we will set up a button and us the MFMailComposeViewControllerDelegate method to send the email. Let’s dive in!
Step 1: import the frameworks
Import the MessageUI framework, he is links to the MFMailComposeViewController class, which is responsible for presentation the email composer in the app.
Step 2: Set up a Button
Copy/paste the following code so you can have a button place in the center of your view controller, don't’ forget to call the setupButton function inside the ViewDidLoad. We will handle the action responsible for presenting the email composer interface in the step 4.
Step 3: Add the MFMailComposeViewControllerDelegate Method
Add this extension at the end of your ViewController, after the last graph. This method is responsible for calling the mail ViewController delegate directly from your app, that way, you don’t need to build a custom email composer. The different cases covers the majors’ scenarios: the user cancel, the email failed to be delivered (internet connection for example), the user save the email or he sends it.
Step 4: Present the email composer
Last steps: give the action to the button, copy/paste the code below to the view controller. Inside the function below, we cover the basics: we set the recipient, the subject, and the body but you can also add an attachment to the email with the .addAttachmentData() method.
Step 5: Get on your phone!
The simulator often doesn’t support the presentation of the mail composer, run the app with your personal device and click on the button — you should be able to see the mail composer screen appears with an email ready to be sent!
Thanks for reading! I’m always happy to have a chat and collaborate at hello@sullivandecarli.com. Consider subscribing to enjoy unlimited access to my articles and all of Medium through my referral link
You can find the complete piece of code below, thanks for reading!