iOS開發(fā)使用郵件功能通常有以下兩種方式:
iOS系統(tǒng)框架提供的兩種發(fā)送Email的方法:openURL 和 MFMailComposeViewController。借助這兩個方法,我們可以輕松的在應(yīng)用里加入如用戶反饋這類需要發(fā)送郵件的功能。
1.使用openURL
使用openURL調(diào)用系統(tǒng)郵箱客戶端是我們在IOS3.0以下實現(xiàn)發(fā)郵件功能的主要手段漱受。缺點:在發(fā)送郵件的過程會導(dǎo)致程序暫時退出應(yīng)用想自己提供界面讓用戶輸入短信收件人地址、短信內(nèi)容姚建、主體止状、附件等短信內(nèi)容,則可使用
#pragma mark- 發(fā)郵件- (IBAction)email:(id)sender {?
NSMutableString *mailUrl = [[NSMutableString alloc]init];? ? //添加收件人 NSArray *toRecipients = [NSArray arrayWithObject: @"10086@qq.com"]; [mailUrl appendFormat:@"mailto:%@", [toRecipients componentsJoinedByString:@","]]; ?//添加抄送 ? ?NSArray *ccRecipients = [NSArray arrayWithObjects:@"one@qq.com", @"two@qq.com", nil];? ? [mailUrl appendFormat:@"?cc=%@", [ccRecipients componentsJoinedByString:@","]];? ? //添加密送 ? NSArray *bccRecipients = [NSArray arrayWithObjects:@"third@qq.com", nil];[mailUrl appendFormat:@"&bcc=%@", [bccRecipients componentsJoinedByString:@","]];? ? //添加主題 [mailUrl appendString:@"&subject= Hello"];? ? //添加郵件內(nèi)容 ?[mailUrl appendString:@"&body=emailbody!"]; ?NSString* email = [mailUrl stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; ? ?[[UIApplication sharedApplication] openURL: [NSURL URLWithString:email]]; ? ?
}
2.使用MFMailComposeViewController
MFMailComposeViewController是在IOS3.0新增的一個接口阳仔,它在MessageUI.framework中忧陪。通過調(diào)用MFMailComposeViewController,可以把郵件發(fā)送窗口集成到我們的應(yīng)用里近范,發(fā)送郵件就不需要退出程序了,建議使用嘶摊。
.項目中引入MessageUI.framework;
.實現(xiàn)MFMailComposeViewControllerDelegate顺又,處理郵件發(fā)送事件更卒;
.調(diào)出郵件發(fā)送窗口前先使用MFMailComposeViewController里的“+ (BOOL)canSendMail”方法檢查用戶是否設(shè)置了郵件賬戶;
.初始化MFMailComposeViewController稚照,構(gòu)造郵件體
例子:
#pragma mark - 調(diào)用系統(tǒng)郵箱
- (void)sendEmailAction
{
// 郵件服務(wù)器
MFMailComposeViewController *mailCompose = [[MFMailComposeViewController alloc] init];
// 設(shè)置郵件代理
[mailCompose setMailComposeDelegate:self];
// 設(shè)置郵件主題
? [mailCompose setSubject:@"Hello"];
// 設(shè)置收件人
[mailCompose setToRecipients:@[@"10086@qq.com"]];
// 設(shè)置抄送人
? [mailCompose setCcRecipients:@[@"郵箱號碼"]];
// 設(shè)置密抄送
?[mailCompose setBccRecipients:@[@"郵箱號碼"]];
// 設(shè)置郵件的正文內(nèi)容
NSString *emailContent = @"";
// 是否為HTML格式
[mailCompose setMessageBody:emailContent isHTML:NO];
// 彈出郵件發(fā)送視圖
[self presentViewController:mailCompose animated:YES completion:nil];
}
#pragma mark - 發(fā)送郵件代理方法
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error
{
switch (result)
{
case MFMailComposeResultCancelled: // 用戶取消編輯
? ? ? ? ? NSLog(@"Mail send canceled...");
break;
case MFMailComposeResultSaved: // 用戶保存郵件
? ? ? ? ? ?NSLog(@"Mail saved...");
break;
case MFMailComposeResultSent: // 用戶點擊發(fā)送
? ? ? ? ? ? NSLog(@"Mail sent...");
break;
case MFMailComposeResultFailed: // 用戶嘗試保存或發(fā)送郵件失敗
? ? ? ? ? ? NSLog(@"Mail send errored: %@...", [error localizedDescription]);
break;
}
// 關(guān)閉郵件發(fā)送視圖
[self dismissViewControllerAnimated:YES completion:nil];
}