You've not put all of your code together there. What you're doing is opening a URL of mailto:test@gmail.com
which isn't the correct way to do it. You should be using MFMailComposeViewController
First and foremost:
import MessageUI
And your code should be something similar to:
@IBAction func sendEmailTest(_ sender: Any) {
if MFMailComposeViewController.canSendMail() {
let composeVC = MFMailComposeViewController()
composeVC.mailComposeDelegate = self
composeVC.setToRecipients(["test@gmail.com"])
composeVC.setSubject("Email Subject")
composeVC.setMessageBody("", isHTML: false)
self.present(composeVC, animated: true, completion: nil)
} else {
print("Cannot send mail")
}
}
Also include a way to handle the code once a user has finished in the mail composer by including after the above method:
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: nil)
}
You can read more about MFMailComposeViewController on the Apple developer site here: https://developer.apple.com/documentation/messageui/mfmailcomposeviewcontroller
If indeed, you do want to open a URL, you should implement the following:
@IBAction func sendEmailTest(_ sender: Any) {
if let url: NSURL = NSURL(string: "mailto:test@gmail.com") {
UIApplication.shared.canOpenURL((url as NSURL) as URL)
}
}
Make sure you run it on an actual device, not on simulator.
But MFMailComposeViewController should be the correct way of implementing it.
Hope this helps.