To send an email from our application we'll need to use URL Schemes and some action on event of which the email will be sent. We can not actually send email from the application, unless it is an mailing application and we use MessageUI framework of iOS, but we can open some email app from our application with prefilled email and subject.
We'll see both the ways of doing this.
Let's see how we can open the MAIL app of iOS with an example.
Create a project and on its first view controller
add a button and change it's text to open "open e-mail", create its action in the ViewController.swift class
Add another button call it "open MF mail", and create it's action too.
Method 1 − Using URL Scheme and other mailing app
func sendEmail(email:String) { if let url = URL(string: "mailto:\(email)") { if #available(iOS 10.0, *) { UIApplication.shared.open(url) } else { UIApplication.shared.openURL(url) } } }
This function can be called to send email to some email id, call this function inside the body of First button "open e-mail", below is the result
Method 2 − Using MFMailCompose of MessageUI Framework
func sendMFmail(email: String) { let mailVC = MFMailComposeViewController() mailVC.mailComposeDelegate = self mailVC.setToRecipients([email]) mailVC.setSubject("Testing sending email") mailVC.setMessageBody("Test Body of email", isHTML: false) present(mailVC, animated: true, completion: nil) }
This function can be called inside the body of "open MF mail" button's action similar to method one, and it produces the following result.
Note - These apps can not be run on simulator because mail is not supported in simulator and you need an actual device.