H.N. H.N. - 10 days ago 5
Swift Question

Sending an email from swift 3

I am trying to set up an app with send email option.

I have this code:

import Foundation
import MessageUI
import UIKit

class emailClass: UIViewController, MFMailComposeViewControllerDelegate {

override func viewDidLoad() {
super.viewDidLoad()

if !MFMailComposeViewController.canSendMail() {
print("Mail services are not available")
return
}

sendEmail()
}




func sendEmail() {

let composeVC = MFMailComposeViewController()
composeVC.mailComposeDelegate = self

// Configure the fields of the interface.
composeVC.setToRecipients(["address@example.com"])
composeVC.setSubject("Hello!")
composeVC.setMessageBody("Hello this is my message body!", isHTML: false)

// Present the view controller modally.
self.present(composeVC, animated: true, completion: nil)


}


func mailComposeController(controller: MFMailComposeViewController,
didFinishWithResult result: MFMailComposeResult, error: NSError?) {
// Check the result or perform other tasks.

// Dismiss the mail compose view controller.
controller.dismiss(animated: true, completion: nil)
}



override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}


So I get this message: "Mail services are not available".
Now I've logged in the simulator device in iCloud... So i think it should do it but it's not. Why isn't this working? Can you tell me whats wrong and how can I move forward?

Answer

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