Open eMail from App with predefined text in iOS
You can do it using MFMailComposeViewController
:
import MessageUI
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(["[email protected]"])
mailComposerVC.setSubject("Subject")
mailComposerVC.setMessageBody("Body", isHTML: false)
self.presentViewController(mailComposerVC, animated: true, completion: nil)
Also, you need to implement mailComposeController:didFinishWithResult:error:
from MFMailComposeViewControllerDelegate
where you should dismiss MFMailComposeViewController
Swift 4.0
let email = "[email protected]"
let subject = "subject"
let bodyText = "Please provide information that will help us to serve you better"
if MFMailComposeViewController.canSendMail() {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients([email])
mailComposerVC.setSubject(subject)
mailComposerVC.setMessageBody(bodyText, isHTML: true)
self.present(mailComposerVC, animated: true, completion: nil)
} else {
let coded = "mailto:\(email)?subject=\(subject)&body=\(bodyText)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
if let emailURL = URL(string: coded!)
{
if UIApplication.shared.canOpenURL(emailURL)
{
UIApplication.shared.open(emailURL, options: [:], completionHandler: { (result) in
if !result {
// show some Toast or error alert
//("Your device is not currently configured to send mail.")
}
})
}
}
}
If you'd like to open the built-in email app as opposed to showing the MFMailComposeViewController
as has been mentioned by others, you could construct a mailto:
link like this:
let subject = "My subject"
let body = "The awesome body of my email."
let encodedParams = "subject=\(subject)&body=\(body)".stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())
let url = "mailto:[email protected]?\(encodedParams)"
if let emailURL = NSURL(url) {
if UIApplication.sharedApplication().canOpenURL(emailURL) {
UIApplication.sharedApplication().openURL(emailURL)
}
}
Just to save anyone typing, for 2016 the syntax has changed slightly:
let subject = "Some subject"
let body = "Plenty of email body."
let coded = "mailto:[email protected]?subject=\(subject)&body=\(body)".stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())
if let emailURL:NSURL = NSURL(string: coded!)
{
if UIApplication.sharedApplication().canOpenURL(emailURL)
{
UIApplication.sharedApplication().openURL(emailURL)
}
Swift 3 Version
let subject = "Some subject"
let body = "Plenty of email body."
let coded = "mailto:[email protected]?subject=\(subject)&body=\(body)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
if let emailURL: NSURL = NSURL(string: coded!) {
if UIApplication.shared.canOpenURL(emailURL as URL) {
UIApplication.shared.openURL(emailURL as URL)
}
}