iOS开发中实现邮件和短信发送的简单示例
发送邮件
1.导入库文件:MessageUI.framework
2.引入头文件
3.实现代理<MFMailComposeViewControllerDelegate>和<UINavigationControllerDelegate>
代码示例:
-(void)didClickSendEmailButtonAction{ if([MFMailComposeViewControllercanSendMail]==YES){ MFMailComposeViewController*mailVC=[[MFMailComposeViewControlleralloc]init]; // 设置代理(与以往代理不同,不是"delegate",千万不能忘记呀,代理有3步) mailVC.mailComposeDelegate=self; // 收件人 NSArray*sendToPerson=@[@"humingtao2014@gmail.com"]; [mailVCsetToRecipients:sendToPerson]; // 抄送 NSArray*copyToPerson=@[@"humingtao2013@126.com"]; [mailVCsetCcRecipients:copyToPerson]; // 密送 NSArray*secretToPerson=@[@"563821250@qq.com"]; [mailVCsetBccRecipients:secretToPerson]; // 主题 [mailVCsetSubject:@"helloworld"]; [selfpresentViewController:mailVCanimated:YEScompletion:nil]; [mailVCsetMessageBody:@"魑魅魍魉,哈哈呵呵嘿嘿霍霍"isHTML:NO]; }else{ NSLog(@"此设备不支持邮件发送"); } } -(void)mailComposeController:(MFMailComposeViewController*)controllerdidFinishWithResult:(MFMailComposeResult)resulterror:(NSError*)error{ switch(result){ caseMFMailComposeResultCancelled: NSLog(@"取消发送"); break; caseMFMailComposeResultFailed: NSLog(@"发送失败"); break; caseMFMailComposeResultSaved: NSLog(@"保存草稿文件"); break; caseMFMailComposeResultSent: NSLog(@"发送成功"); break; default: break; } [selfdismissViewControllerAnimated:YEScompletion:nil]; } // 系统发送,模拟器不支持,要用真机测试 -(void)didClickSendSystemEmailButtonAction{ NSURL*url=[NSURLURLWithString:@"humingtao2014@gmail.com"]; if([[UIApplicationsharedApplication]canOpenURL:url]==YES){ [[UIApplicationsharedApplication]openURL:url]; }else{ NSLog(@"此设备不支持"); } }
发送短信
前面三步引入配置和邮件发送一样
// 调用系统API发送短信 -(void)didClickSendMessageButtonAction{ if([MFMessageComposeViewControllercanSendText]==YES){ MFMessageComposeViewController*messageVC=[[MFMessageComposeViewControlleralloc]init]; // 设置代理<MFMessageComposeViewControllerDelegate> messageVC.messageComposeDelegate=self; // 发送ToWho messageVC.recipients=@[@"18757289870"]; messageVC.body=@"helloworld"; [selfpresentViewController:messageVCanimated:YEScompletion:nil]; }else{ NSLog(@"此设备不支持"); } } -(void)messageComposeViewController:(MFMessageComposeViewController*)controllerdidFinishWithResult:(MessageComposeResult)result{ switch(result){ caseMessageComposeResultCancelled: NSLog(@"取消发送"); break; caseMessageComposeResultFailed: NSLog(@"发送失败"); break; caseMessageComposeResultSent: NSLog(@"发送成功"); break; default: break; } [selfdismissViewControllerAnimated:YEScompletion:nil]; } // 调用系统应用程序发送消息 -(void)didClickSendMessage2ButtonAction{ NSURL*url=[NSURLURLWithString:@"sms:18656348970"]; if([[UIApplicationsharedApplication]canOpenURL:url]==YES){ [[UIApplicationsharedApplication]openURL:url]; }else{ NSLog(@"失败"); } }