How to fill email with To and Subject in iPhone? - objective-c

I have a button in my app called contact Us! Is there a way to open up the Eamil client in iPhone filled with To and Subject that I provide?

You will want to use the MFMailComposeViewController class. Here's the relevant part from Apple's MailComposer example:
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Hello from California!"];
// Set up recipients
NSArray *toRecipients = [NSArray arrayWithObject:#"first#example.com"];
[picker setToRecipients:toRecipients];
[self presentModalViewController:picker animated:YES];
[picker release];
The MailComposer sample also shows you how to open the external mail app:
NSString *recipients = #"mailto:first#example.com&subject=Hello from California!";
NSString *body = #"&body=It is raining in sunny California!";
NSString *email = [NSString stringWithFormat:#"%#%#", recipients, body];
email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];

Check out MFMailComposeViewController. You can set the Subject, To Field, and even populate the body with HTML.

Sure you can.
- (void)emailExport:(NSString *)filePath
{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
// Set the subject of email
[picker setSubject:#"My desired subject"];
// Add email addresses
// Notice three sections: "to" "cc" and "bcc"
NSString *valueForEmail = #"myEmail#gmail.com";
NSString *valueForCCEmail = #"myCcEmail";
if( valueForEmail == nil || [valueForEmail isEqualToString:#""])
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Please set an email address before sending a time entry!" message:nil delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
else {
[picker setToRecipients:[NSArray arrayWithObjects:valueForEmail, nil]];
}
if(valueForCCEmail != nil || ![valueForCCEmail isEqualToString:#""])
{
[picker setCcRecipients:[NSArray arrayWithObjects:valueForCCEmail, nil]];
}
// Fill out the email body text
NSString *emailBody = #"My email body text.";
// This is not an HTML formatted email
[picker setMessageBody:emailBody isHTML:NO];
// Show email view
[self presentModalViewController:picker animated:YES];
// Release picker
[picker release];
}

Related

Adding NSData attachment to Twitter as an image post

Currently my app gives the option to save to device, or email, the latter attaching the image automatically to the mail, I am looking to add a post to twitter option, simply attaching the image and posting to Twitter, I have done this a few times with other apps, but cannot seem to get this one working.
Here is the process for email;
-(void)displayComposerSheet
{
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
mail.mailComposeDelegate = self;
[mail setSubject:#""];
NSString* path =[NSHomeDirectory() stringByAppendingPathComponent:#"Documents/email.png"];
[mSplashView SaveResultImage:path];
[mail addAttachmentData:[NSData dataWithContentsOfFile:path] mimeType:#"image/png" fileName:#"Attached image"];
NSString *msg = [NSString stringWithFormat:#"I made this image!", [UIDevice currentDevice].model];
NSString* mailcontent = [NSString stringWithFormat:#"<br> %# <br>", msg];
[mail setMessageBody:mailcontent isHTML:YES];
[self presentModalViewController:mail animated:YES];
[mail release];
}
I am struggling to see how I can use similar to attach the image to Twitter, I currently use this code, but it crashes when attempting to post;
TWTweetComposeViewController *twitter = [[TWTweetComposeViewController alloc] init];
[self presentViewController:twitter animated:YES completion:nil];
NSString* path =[NSHomeDirectory() stringByAppendingPathComponent:#"Documents/email.png"];
[mSplashView SaveResultImage:path];
[twitter setInitialText:#"I made this image!"];
[twitter addURL:[NSData dataWithContentsOfFile:path]];
twitter.completionHandler = ^(TWTweetComposeViewControllerResult res) {
if(res == TWTweetComposeViewControllerResultDone) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Thank you" message:#"Posted successfully to Twitter." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
if(res == TWTweetComposeViewControllerResultCancelled) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Cancelled" message:#"You Cancelled posting the Tweet." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
[self dismissViewControllerAnimated:YES completion:nil];
};
}
Normally I could simply call [twitter addImage:]; but unfortunately it seems the image is not grabbed correctly without going through the processes above in the mail sheet.
You can't pass NSData for -addURL: method.
If your image store on disk, you can create image with [UIImage imageWithContentsOfFile:imagePath] method. Next add it with -addImage:
NSString* path =[NSHomeDirectory() stringByAppendingPathComponent:#"Documents/imgtweet.png"];
[UIImagePNGRepresentation(imageView.image) writeToFile:path atomically:YES];
//NSLog(#"path %#",path);
UIImage *new_image = [UIImage imageWithContentsOfFile:path];
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
SLComposeViewController *tweetSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
[tweetSheet setInitialText:self.txtContent.text];
[tweetSheet addImage:new_image];
[self presentViewController:tweetSheet animated:YES completion:nil];
}
Using Previous Answer,Thanks :)
Happy coding :)

MFMailComposer Dismissing immediately after launch

I am trying to launch the MFMailComposer on the iOS 7 simulator and as soon as it comes up it immediately dissmises itself and I get the following error in the debugger.
_serviceViewControllerReady:error: Error Domain=NSCocoaErrorDomain Code=4097 "The operation couldn’t be completed. (Cocoa error 4097.)"
Here is my code
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
switch (buttonIndex) {
case 0:
break;
case 1:{
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
mailViewController.mailComposeDelegate = self;
[mailViewController setSubject:[NSString stringWithFormat:#"%# Totals Report",_teamStats.relationshipTeam.teamName]];
[mailViewController setMessageBody:#"\n\n\n\n\nSent From HoopMetrics" isHTML:NO];
// Attach a doc to the email
NSData* data = [_teamStats.relationshipTeam pdfDataFromString:_teamStats.teamTotalsAsString];
[mailViewController addAttachmentData:data mimeType:#"application/pdf" fileName:#"Totals Report"];
[self presentViewController:mailViewController animated:YES completion:nil];
}
else{
HMAlertView*alert = [[HMAlertView alloc]initWithTitle:#"No Email" message:#"Please, set up an email account on your device" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}
break;
}
I faced the same problem. Just turn off appearance customization for UINavigationBar or UIBarButtonItem or some another element that MFMailComposeViewController may use.
You can get around this with the following hack using performSelector:
- (IBAction)sendEmail:(id)sender {
[self performSelector:#selector(showEmailComposer) withObject:nil afterDelay:0.0];
}
-(void) showEmailComposer{
MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
//Set recipients...other stuff
[mailViewController setToRecipients:recipients];
[mailViewController setSubject:subject];
[mailViewController setMessageBody:body isHTML:isHTML];
mailViewController.title = #"Email VC Title";
mailViewController.mailComposeDelegate = delegate;
[self presentViewController:mailViewController
animated:YES
completion:NULL];
}

Undeclared identifier 'mailComposeController'

Here is my .m code:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *emailCell = [tableView cellForRowAtIndexPath:indexPath];
if ([emailCell.textLabel.text isEqualToString:#"Contact Developer"]) {
NSLog(#"Email button pressed...");
if([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:#"A Message from MobileTuts+"];
NSArray *toRecipients = [NSArray arrayWithObjects:#"fisrtMail#example.com", #"secondMail#example.com", nil];
[mailer setToRecipients:toRecipients];
NSString *emailBody = #"Have you seen the MobileTuts+ web site?";
[mailer setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:mailer animated:YES];
[mailer release];
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
switch (result)
{
case MFMailComposeResultCancelled:
NSLog(#"Mail cancelled: you cancelled the operation and no email message was queued.");
break;
case MFMailComposeResultSaved:
NSLog(#"Mail saved: you saved the email message in the drafts folder.");
break;
case MFMailComposeResultSent:
NSLog(#"Mail send: the email message is queued in the outbox. It is ready to send.");
break;
case MFMailComposeResultFailed:
NSLog(#"Mail failed: the email message was not saved or queued, possibly due to an error.");
break;
default:
NSLog(#"Mail not sent.");
break;
}
// Remove the mail view
[self dismissModalViewControllerAnimated:YES];
}
}
else {
UIAlertView *emailAlert = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"Please make sure you have an email address configured in your Mail app."
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[emailAlert show];
[emailAlert release];
}
}
}
I have imported everything correctly in .h and .m, but the email won't close... I have tried as suggested on Stack Overflow to fiddle with the mailer.mailComposeDelegate = self; but I am still getting an undeclared identifier error. How do I fix this? Thanks.
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
Move this function out of the tableview delegate method. You should learn some basics. You cannot have a method within another method. If you need then you can call the method by [self callingFunctionName];
In you case,
if ([emailCell.textLabel.text isEqualToString:#"Contact Developer"]) {
NSLog(#"Email button pressed...");
[self sendEmail];
}
-(void)sendEmail{
if([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:#"A Message from MobileTuts+"];
NSArray *toRecipients = [NSArray arrayWithObjects:#"fisrtMail#example.com", #"secondMail#example.com", nil];
[mailer setToRecipients:toRecipients];
NSString *emailBody = #"Have you seen the MobileTuts+ web site?";
[mailer setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:mailer animated:YES];
[mailer release];
}
}
This will open the mail composer. When you send, cancel or save the mail, the delegate function
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
will automatically be called.

Unable to send email through my app

I am new to iphone development. I am building an app through which i can send the email.I am using the following code
- (IBAction)btnsendPressAction:(id)sender {
if([MFMailComposeViewController canSendMail]){
MFMailComposeViewController *mailer=[[MFMailComposeViewController alloc]init];
mailer.mailComposeDelegate=self;
[mailer setSubject:#"A Message for testing"];
NSArray *toRecipients = [NSArray arrayWithObjects:#"rajshetty2125#gmail.com", #"secondMail#example.com", nil];
[mailer setToRecipients:toRecipients];
UIImage *image=[UIImage imageNamed:#"logo.png"];
NSData *imageData=UIImagePNGRepresentation(image);
[mailer addAttachmentData:imageData mimeType:#"image/png" fileName:#"logo.png"];
NSString *emailBody=#"This is test email";
[mailer setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:mailer animated:YES];
mailer.modalPresentationStyle = UIModalPresentationPageSheet ;
}
else{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"failure" message:#"Alert" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}
My problem is mailComposeController delegate is not getting called and I am not able to send email through my app.I went through many links , but every where I found the same method. Can anyone help me on this ?
You won't be able to send email from Simulator. You can only check this functionality on iOS device with any account configured in Mail application.
Here use this link and your add(configured) an account in device then only you can send the mail.
This snippet is working for me:
if ([MFMailComposeViewController canSendMail]) {
self.mailController = [[MFMailComposeViewController alloc] init];
[self.mailController setSubject:#"Invitation"];
[self.mailController setMessageBody:#"Message" isHTML:NO];
self.mailController.mailComposeDelegate = self;
[self presentModalViewController:self.mailController animated:YES];
}
but make sure that you're implement delegate in interface
#interface MyClass() <MFMailComposeViewControllerDelegate>
and check your callback method:
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
}
hey i am not sure but may be it's helpful, replace your last line
mailer.modalPresentationStyle = UIModalPresentationPageSheet ;
with
[self presentModalViewController: mailer animated:YES];

Error found - too many arguments to method call expected 1 have 2 - in app email

There seems to be an error with my coding, and it says that there are to many nils or something
I need help
MFMailComposeViewController *composer = [[MFMailComposeViewController alloc]init];
if ([MFMailComposeViewController canSendMail]) {
[composer setToRecipients:[NSArray arrayWithObject:#"nicole#aandtlegal.com", nil]];
[composer setSubject:nil];[composer setMailComposeDelegate:self];
[composer setMessageBody:nil isHTML:YES];
[composer setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
Try this code:
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Hello!"];
NSArray *toRecipients = [NSArray arrayWithObject:#"example#example.com"];
[picker setToRecipients:toRecipients];
NSString *emailBody = [NSString stringWithString:#"Hello!"];
[picker setMessageBody:emailBody isHTML:YES];
picker.navigationBar.barStyle = UIBarStyleBlack;
[self presentModalViewController:picker animated:YES];
[picker release];