iOS 應用內調用并發(fā)送郵件
- 目前有兩種方法 mailto: 和 MFMailComposeViewController
1. 使用 mailto:
- 會跳轉到應用外并打開系統(tǒng)郵件
NSURL *url = [NSURL URLWithString:@"mailto:yourEmail"];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
} else {
NSLog(@"打開郵箱出現(xiàn)錯誤");
}
2. MFMailComposeViewController
- 該方式需要已設置好郵件賬戶络它,否則無法打開
- 可設置主題弊决、收件人粱年、抄送人搂蜓、發(fā)送內容
- 首先需要導入 #import <MessageUI/MFMailComposeViewController.h>
#pragma mark - 發(fā)送郵件
- (void)sendEmail {
MFMailComposeViewController *mailVC = [MFMailComposeViewController new];
if (!mailVC) {
// 在設備還沒有添加郵件賬戶的時候规求,為空
NSLog(@"暫未設置郵箱賬戶,請先到系統(tǒng)設置添加賬戶");
return;
}
//代理 MFMailComposeViewControllerDelegate
mailVC.mailComposeDelegate = self;
//郵件主題
[mailVC setSubject:@"反饋/建議"];
//收件人
[mailVC setToRecipients:@[@"yourEmail"]];
[self presentViewController:mailVC animated:YES completion:nil];
}
// 實現(xiàn)代理方法
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
// MFMailComposeResultCancelled
// MFMailComposeResultSaved
// MFMailComposeResultSent
// MFMailComposeResultFailed
if (result == MFMailComposeResultSent) {
NSLog(@"發(fā)送成功");
} else if (result == MFMailComposeResultFailed) {
NSLog(@"發(fā)送失敗");
}
[controller dismissViewControllerAnimated:YES completion:nil];
}