使用RestSharp调用Mandrill发邮件遇「Please enter an array」错误求助
Fixing "Please enter an array" Error When Calling Mandrill Send-Template API with RestSharp
我来帮你排查下这个Mandrill API调用的问题,你的错误提示 "Please enter an array" 主要是由几个配置错误导致的,下面是具体分析和修复方案:
问题根源分析
- 错误的API端点:你当前调用的是
messages/send.json(用于普通邮件发送),但发送模板邮件必须使用messages/send-template.json端点。 - 手动序列化导致的格式问题:你把
EmailMessage手动序列化成字符串后传入message字段,Mandrill期望这个字段是一个JSON对象,而不是字符串化的对象,这会导致API无法正确解析请求内容。 - 缺少必填参数:Mandrill的
send-templateAPI要求template_content参数是一个数组(即使没有需要替换的模板内容,也得传空数组),你的代码完全遗漏了这个参数,这是触发"Please enter an array"错误的核心原因。
Step-by-Step 修复方案
下面是修改后的完整代码,每一处改动都做了注释说明:
public List<EmailResult> SendMessageTemplate(MandrillApi mapiResponse, string templateName, EmailMessage emailMessage) { if (mapiResponse != null && !string.IsNullOrEmpty(mapiResponse.ApiKey) && !string.IsNullOrEmpty(mapiResponse.BaseUrl) && !string.IsNullOrEmpty(templateName) && emailMessage != null) { List<EmailResult> emailResult = new List<EmailResult>(); // 1. 切换到模板发送的专属API端点 var restRequest = new RestSharp.RestRequest { RequestFormat = DataFormat.Json, Method = RestSharp.Method.POST, Resource = "messages/send-template.json" }; // 2. 直接传递对象让RestSharp自动序列化,同时添加必填的template_content空数组 restRequest.AddBody(new { key = mapiResponse.ApiKey, template_name = templateName, template_content = new object[] { }, // 必填参数:即使无内容也要传空数组 message = emailMessage // 直接传对象,避免手动序列化导致的格式错误 }); var restClient = new RestSharp.RestClient(mapiResponse.BaseUrl); var response = restClient.Execute(restRequest); emailResult = JsonConvert.DeserializeObject<List<EmailResult>>(response.Content); return emailResult; } else return null; }
为什么之前的尝试无效?
你提到把emailMessage放入列表转数组后返回[],这是因为你错误地将message字段设置成了数组,但Mandrill的send-template API中message是单个对象,而**template_content才是需要数组格式的参数**。同时,错误的API端点也会导致请求无法被正确处理。
额外验证建议
- 确认
EmailMessage对象中的to字段是有效的数组(从你提供的序列化JSON看,这个字段格式是正确的) - 检查Mandrill API密钥和BaseUrl是否配置正确,无拼写错误
内容的提问来源于stack exchange,提问作者Shubham Khandelwal
相关产品推荐
相关产品推荐

