我想让一个API调用发送到收件人列表,并自定义每个电子邮件。我已经把一般代码算出来了。换人在起作用。但这只发送到第一个电子邮件地址,即使我有2个不同的电子邮件地址的个性化。
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
List<string> recipients = new List<string>();
recipients.Add("some address");
recipients.Add("second address");
msg.Personalizations = new List<Personalization>();
for (int x = 0; x < recipients.Count; x++) {
if (recipients[x].IndexOf("@") > -1) {
//msg.AddTo(recipients[x]);
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;
msg.Personalizations.Add(personalization);
addressAdded = true;
}
}
Response response = await client.SendEmailAsync(msg).ConfigureAwait(false);我做错了什么?有关于这个的文件吗?
发布于 2022-12-02 02:00:04
IsValidEmail方法:
public static bool IsValidEmail(string email)
{
try
{
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == email;
}
catch
{
return false;
}
}SendEmail方法:
SendGridClient client = new SendGridClient(apiKey);
SendGridMessage msg = new SendGridMessage();
msg.SetFrom(new EmailAddress(from, fromName));
msg.Subject = subject;
msg.HtmlContent = "<strong> C# is the Best! </strong>";
List<string> recipients = new List<string>();
recipients.Add("some address");
recipients.Add("second address");
msg.Personalizations = new List<Personalization>();
foreach (string recipient in recipients)
{
if (IsValidEmail(recipient))
{
Personalization personalization = new Personalization();
personalization.Tos = new List<EmailAddress>();
personalization.Tos.Add(new EmailAddress(recipient));
msg.Personalizations.Add(personalization);
Dictionary<string, string> subs = new Dictionary<string, string>();
subs.Add("{{UserName}}", "Mark");
subs.Add("{{VerificationCode}}","ABC123");
personalization.Substitutions = subs;
msg.Personalizations.Add(personalization);
addressAdded = true;
}
// This Worked
if (addressAdded)
{
Response response = await client.SendEmailAsync(msg);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Headers.ToString());
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
}
}https://stackoverflow.com/questions/74649439
复制相似问题