iOS 原生邮件发送 MessageUI MFMailComposeViewController
原因
因公司项目需求,在客服地方给玩家提供了客服邮箱,玩家点击后能自动跳转到邮箱发送邮件(自动填充部分数据),于是研究了下iOS自带的MessageUI里的MFMailComposeViewController。
解决
研究后做了下简单的封装,主要有以下几步
1.引入头文件
#import <MessageUI/MessageUI.h>
2.定义邮箱管理器属性
@property (nonatomic, strong) MFMailComposeViewController *mailCompose;
3.调用发送邮件
//发送邮件
-(void)sendMailToRecipients:(NSArray *)users1 CcRecipients:(NSArray *)users2 Content:(NSString *) content Title:(NSString *)title inController:(UIViewController *)controller{
if ([MFMailComposeViewController canSendMail]) {
//如果有登录,弹出系统邮箱
// 用户已设置邮件账户
// 邮件服务器
self.mailCompose = [[MFMailComposeViewController alloc] init];
// 设置邮件代理
[self.mailCompose setMailComposeDelegate:self];
// 设置邮件主题
if(title && title.length>0){
[self.mailCompose setSubject:title];
}
if(users1 && users1.count>0){
// 设置收件人
[self.mailCompose setToRecipients:users1];
}
if(users2 && users2.count>0){
// 设置抄送人
[self.mailCompose setCcRecipients:users2];
}
if(content && content.length>0)
{
//设置邮件的正文内容
[self.mailCompose setMessageBody:content isHTML:NO];
}
[controller presentViewController:self.mailCompose animated:YES completion:nil];
}else{
//创建可变的地址字符串对象:
NSMutableString *mailUrl = [[NSMutableString alloc] init];
if(users1 && users1.count>0){
//添加收件人:
NSString * alltoRecipients = [users1 componentsJoinedByString:@","];
// 注意:如有多个收件人,可以使用componentsJoinedByString方法连接,连接符为@","
[mailUrl appendFormat:@"mailto:%@",alltoRecipients];
}
if(users2 && users2.count>0){
//添加抄送人:
NSString * allccRecipients = [users2 componentsJoinedByString:@","];
// 注意:如有多个抄送人,可以使用componentsJoinedByString方法连接,连接符为@","
[mailUrl appendFormat:@"?cc=%@",allccRecipients];
}
if(title && title.length>0){
//添加邮件主题
[mailUrl appendString:@"&subject="];
[mailUrl appendString:title];
}
if(content && content.length>0){
//添加邮件内容:
[mailUrl appendString:@"&body="];
[mailUrl appendString:content];
}
//打开地址,这里会跳转至邮件发送界面:
NSString *emailPath = [mailUrl stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLQueryAllowedCharacterSet]];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:emailPath] options:@{
} completionHandler:^(BOOL success) {
}];
}
}
4.实现代理(MFMailComposeViewControllerDelegate)
- (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: // 用户点击发送
NSLog(@"Mail sent...");
break;
case MFMailComposeResultFailed: // 用户尝试保存或发送邮件失败
NSLog(@"Mail send errored: %@...", [error localizedDescription]);
break;
}
if(self.mailCompose){
[self.mailCompose dismissViewControllerAnimated:YES completion:nil];
}
}
联系作者
期待你的点赞和关注!如有疑问,联系作者。