使用SendGrid API(C#)批量发个性化邮件仅送达首个收件人问题求助
问题原因及解决方案
你的代码问题出在手动初始化msg.Personalizations为新List并直接添加项,这不符合SendGrid C# SDK的正确使用方式。SendGridMessage实例的Personalizations属性默认已经初始化了空列表,直接赋值会破坏SDK内部的状态管理逻辑,导致只有第一个个性化配置被处理。
修改后的代码
SendGridClient client = new SendGridClient(apiKey); SendGridMessage msg = new SendGridMessage(); msg.SetFrom(new EmailAddress(from, fromName)); msg.Subject = subject; msg.HtmlContent = "some content with replacement fields like [Verification Code] and [User Name]"; List<string> recipients = new List<string>(); recipients.Add("some address"); recipients.Add("second address"); // 移除手动初始化Personalizations的代码 for (int x = 0; x < recipients.Count; x++) { if (recipients[x].IndexOf("@") > -1) { Personalization personalization = new Personalization(); personalization.Tos = new List<EmailAddress> { new EmailAddress(recipients[x]) }; Dictionary<string, string> subs = new Dictionary<string, string>(); subs.Add("[Verification Code]", "ABC123"); subs.Add("[User Name]", "Mark"); personalization.Substitutions = subs; // 使用SDK提供的AddPersonalization方法添加个性化配置 msg.AddPersonalization(personalization); addressAdded = true; } } Response response = await client.SendEmailAsync(msg).ConfigureAwait(false);
关键说明
- 不要手动给
msg.Personalizations赋值新的List,保留SDK默认初始化的集合即可。 - 必须使用
msg.AddPersonalization()方法添加每个个性化配置,该方法会处理SDK内部的验证和状态维护,确保所有个性化项都被正确识别并发送。
内容的提问来源于stack exchange,提问作者nuander
相关产品推荐
相关产品推荐

