Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open eMail from App with predefined text in iOS

Hello i want to open the eMail program from my App and the body should already be defined. I can open the eMail but don't know how to define the body of the eMail as a given Parameter to show a given standard text. Anyone can help? Heres the code i use to open Email:

//EMAIL
let email = "[email protected]"
let urlEMail = NSURL(string: "mailto:\(email)")

if UIApplication.sharedApplication().canOpenURL(urlEMail!) {
                UIApplication.sharedApplication().openURL(urlEMail!)
} else {
print("Ups")
}
like image 280
JanScott Avatar asked Nov 13 '15 14:11

JanScott


People also ask

How do I open an email in iOS Swift?

Show activity on this post. let email = "[email protected]" let url = URL(string: "mailto:\(email)") UIApplication. shared. openURL(url!)


2 Answers

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)
        }
like image 188
mclaughj Avatar answered Sep 21 '22 17:09

mclaughj


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)
    }
}
like image 29
Matthew Barker Avatar answered Sep 20 '22 17:09

Matthew Barker