iOS(Objective-C):Outlook URL打开含特殊字符的HTML邮件体内容损坏求助
问题描述
- 通过
ms-outlook://compose协议调用Outlook撰写邮件时,HTML正文中包含 、&、&等特殊字符时,正文内容显示损坏 - 尝试使用
stringByAddingPercentEncodingWithAllowedCharacters方法,问题未解决 - 将
&替换为and可正常显示,但业务需要保留原&字符
原代码片段
NSString *strTest = [NSString stringWithFormat:@"ms-outlook://compose?to=%@&subject=%@&body=%@", emailTo,emailSubject,emailBody]; NSURL *openurlTest = [NSURL URLWithString:[strTest stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; NSURL *openurl = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; if ([[UIApplication sharedApplication] canOpenURL:openurlTest]) { if ([[UIApplication sharedApplication] canOpenURL:openurlTest]) { [[UIApplication sharedApplication] openURL:openurlTest options:@{} completionHandler:nil]; } }
问题表现
截图显示邮件正文内的特殊字符(如 )被错误解析,导致内容乱码、截断,原本的HTML格式被破坏。
解决方案
问题根源在于先拼接未编码的参数到URL字符串,再整体转义,会导致参数内容中的&被误识别为URL的参数分隔符,而非正文内容的一部分。正确做法是单独对每个参数做URL编码,再拼接成完整URL。
修正后的代码
// 单独对每个参数进行URL编码 NSString *encodedTo = [emailTo stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; NSString *encodedSubject = [emailSubject stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; NSString *encodedBody = [emailBody stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; // 拼接编码后的参数生成URL NSString *strTest = [NSString stringWithFormat:@"ms-outlook://compose?to=%@&subject=%@&body=%@", encodedTo, encodedSubject, encodedBody]; NSURL *openurlTest = [NSURL URLWithString:strTest]; if ([[UIApplication sharedApplication] canOpenURL:openurlTest]) { [[UIApplication sharedApplication] openURL:openurlTest options:@{} completionHandler:nil]; }
说明
- 使用
URLQueryAllowedCharacterSet编码单个参数,会自动将参数中的特殊字符(如&转译为%26)转换为符合URL规范的格式,避免被误解析为URL结构符号 - 先编码再拼接的方式,能确保Outlook收到参数后正确解码,还原原始HTML内容,保留
&、 等特殊字符 - 原代码中重复判断
canOpenURL的逻辑可简化,无需重复校验
内容的提问来源于stack exchange,提问作者A.T
相关产品推荐
相关产品推荐

