iOS 發郵件兩種方式


#import <MessageUI/MessageUI.h>

頭文件.h中引入以上header

並加上delegate <MFMailComposeViewControllerDelegate>


.m實現

-(void)sendEMail:(NSString *)email

{

    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));

    if (mailClass != nil) {

        if ([mailClass canSendMail]) {

            [self displayMailPicker:email];

        } else {

            [self launchMailAppOnDevice:email];

        }

    } else {

        [self launchMailAppOnDevice:email];

    }

}


- (void)launchMailAppOnDevice:(NSString *)emaleAddress

{

    NSString *recipients = [NSString stringWithFormat:@"mailto:%@&subject=my email!", emaleAddress];

    NSString *body = @"&body=email body!";

    

    NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];

    email = [email stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

    

    [[UIApplication sharedApplication] openURL: [NSURL URLWithString:email]];

}


//調出郵件發送窗口

- (void)displayMailPicker:(NSString *)emaleAddress

{

    MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc] init];

    mailPicker.mailComposeDelegate = self;

    //添加收件人

    NSArray *toRecipients = [NSArray arrayWithObject:emaleAddress];

    [mailPicker setToRecipients: toRecipients];

    //添加右鍵內容

    [mailPicker setMessageBody:@"" isHTML:YES];

    [self presentModalViewController: mailPicker animated:YES];

}


#pragma mark - MFMailComposeViewControllerDelegate

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error

{    //關閉郵件發送窗口

    [self dismissModalViewControllerAnimated:YES];

    NSString *msg;

    switch (result) {

        case MFMailComposeResultCancelled:

            msg = @"用戶取消編輯郵件";

            break;

        case MFMailComposeResultSaved:

            msg = @"用戶成功保存郵件";

            break;

        case MFMailComposeResultSent:

            msg = @"用戶點擊發送,將郵件放到隊列中,還沒發送";

            break;

        case MFMailComposeResultFailed:

            msg = @"用戶試圖保存或者發送郵件失敗";

            break;

        default:

            msg = @"";

            break;

    }

    NSLog(@"%@", msg);

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章