Wednesday, 18 April 2012

MailComposer (Email) in IOS

#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>
// in .h of the view controller

//call 

-(void) sendMail{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    if (mailClass != nil)
    {
        if ([mailClass canSendMail])
        {
            MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
            controller.mailComposeDelegate = self;
            //Subject of the mail
            NSString *sub = self.navigationItem.title;
            [controller setSubject:sub];
            NSArray *toRecipients = [NSArray arrayWithObject:[[ArrPOList objectAtIndex:0]objectAtIndex:6]];
            [controller setToRecipients:toRecipients];
            //Body of the mail
            //body = [NSString stringWithFormat:@"Wooow"];
            NSString *body=[[NSUserDefaults standardUserDefaults]objectForKey:@"Signature"];
            [controller setMessageBody:body isHTML:NO];
            [self presentModalViewController:controller animated:YES];
            [controller release];
           
        }
        else
            [self launchMailAppOnDevice];
    }
    else
        [self launchMailAppOnDevice];
}

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Result: canceled");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Result: saved");
            break;
        case MFMailComposeResultSent:
            NSLog(@"Result: sent");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Result: failed");
            break;
        default:
            NSLog(@"Result: not sent");
            break;
    }
    [self becomeFirstResponder];
    [self dismissModalViewControllerAnimated:YES];
   
}

-(void)launchMailAppOnDevice
{
    NSString *recipients = [[ArrPOList objectAtIndex:0]objectAtIndex:6];
    NSString *body=[[NSUserDefaults standardUserDefaults]objectForKey:@"Signature"];
//    NSUserDefaults *Defaults = [NSUserDefaults standardUserDefaults];
//    [Defaults setObject:body forKey:@"Signature"];
   
    NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
    email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
   
   /* NSString *recipients = @"post@iratedphrase.com";
    NSString *body = data.text;
    NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
    email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];*/
}

No comments:

Post a Comment