In my application, if the user gave their gmail account then i am required to open the mail client with the gmail login credentials which comes when we select gmail option of mail programmatically but if that account is already stored in mail then i am required to redirect the user directly to their account. Can anybody pliz give me a glimpse of how i can achieve this programmatically.
You won't get that much control over the Mail app as all apps on the iPhone are sandboxed to prevent them from messing with Apple applications.
The only thing you can do (if you want to open the mail client to send an email), is something like this:
/* create mail subject */
NSString *subject = [NSString stringWithFormat:@"Subject"];
/* define email address */
NSString *mail = [NSString stringWithFormat:@"[email protected]"];
/* define allowed character set */
NSCharacterSet *set = [NSCharacterSet URLHostAllowedCharacterSet];
/* create the URL */
NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"mailto:?to=%@&subject=%@",
[mail stringByAddingPercentEncodingWithAllowedCharacters:set],
[subject stringByAddingPercentEncodingWithAllowedCharacters:set]]];
/* load the URL */
[[UIApplication sharedApplication] openURL:url];
/* release the URL. If you are using ARC, remove this line. */
[url release];
Swift:
if let url = NSURL(string: "mailto://\(email)") {
UIApplication.sharedApplication().openURL(url)
}
Swift version of Léon Rodenburg's answer:
// define email address
let address = "[email protected]"
// create mail subject
let subject = "Subject"
// create the URL
let url = NSURL(string: "mailto:?to=\(address)&subject=\(subject)".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)
// load the URL
UIApplication.sharedApplication().openURL(url!)
I would suggest a much more improved answer. The Slack.com mobile app does this, it detects common email clients listed on the device and shows a popup picker of 'which' email client you would like to open.
So to implement:
Google around to find the top 10 email clients (eg Mail, Google Inbox, OutLook, AirMail etc).
Get a list of installed apps on the phone either by searching all apps (but I am told you can now only find if an app is explicitly installed, so you will need detect the app).
Show a popup list if more than 1 email app is detected, requesting them 'which' app to open eg. Mail, Inbox.
This is the best solution I have seen working to date.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With