Sending an email from swift 3 Sending an email from swift 3 swift swift

Sending an email from swift 3


It will not work with simulator. Please test it on iPhone device. You can refer Apple Developer Portal - MFMailComposeViewController


Here's how I did it. It looks like you followed the documentation very well, I thought I'd add my variation in case it helps someone else. Plus, this is a little more updated to current (Aug 2017) syntax.

Conform to the MFMailComposeViewControllerDelegate protocol, and check if the device can send mail.

import Foundationimport UIKitimport MessageUIclass WelcomeViewController: UIViewController, MFMailComposeViewControllerDelegate {override func viewDidLoad() {    super.viewDidLoad()    if !MFMailComposeViewController.canSendMail() {        print("Mail services are not available")        return    }}

My app uses an IBAction to initiate the mail composition.

@IBAction func sendFeedbackButtonTapped(_ sender: Any) {    let composeVC = MFMailComposeViewController()    composeVC.mailComposeDelegate = self    // Configure the fields of the interface.    composeVC.setToRecipients(["exampleEmail@email.com"])    composeVC.setSubject("Message Subject")    composeVC.setMessageBody("Message content.", isHTML: false)    // Present the view controller modally.    self.present(composeVC, animated: true, completion: nil)}

About the following mailComposeController function, the documentation says

The mail compose view controller is not dismissed automatically. When the user taps the buttons to send the email or cancel the interface, the mail compose view controller calls the mailComposeController(_:didFinishWith:error:) method of its delegate. Your implementation of that method must dismiss the view controller explicitly, as shown in Listing 3. You can also use this method to check the result of the operation.

func mailComposeController(_ controller: MFMailComposeViewController,                           didFinishWith result: MFMailComposeResult, error: Error?) {    // Check the result or perform other tasks.    // Dismiss the mail compose view controller.    controller.dismiss(animated: true, completion: nil)   }}

Source Apple Documentation: MFMailComposeViewController


Code seems to be good and works fine if the app is running in a real device

MFMailComposeViewController.canSendMail() // returns false for simulators.

You can't test it on simulator,You'll be able to test basic things like UI,How the things are happening on Cancel/Send button clicks.

To test,You have to use a device,The Mail application in the device should be configured with some mail(ex: abc@xyz.com).

Hope that helps.