无法从“字符串”转换为“ SendGrid.Helpers.Mail.EmailAddress”

时间:2018-11-19 16:30:19

标签: c# sendgrid

我正在尝试在c#asp.net应用程序中构建一些基本的电子邮件功能。我的技能有限,我正在学习。

我正在尝试向应用程序发送电子邮件地址列表。创建列表时出现以下错误:

无法从“字符串”转换为“ SendGrid.Helpers.Mail.EmailAddress”

我可以看到列表阅读器将电子邮件地址列作为字符串提供,我需要将其转换为[SendGrid.Helpers.Mail.EmailAddress],但是我不知道该怎么做。

protected async void sendButton_Click(object sender, EventArgs e)
    {
            // Prepare the email message info model
            var apiKey = System.Web.Configuration.WebConfigurationManager.AppSettings["SendGrid_API_Key"];
            var client = new SendGridClient(apiKey);
            var com = new SqlConnection("Myconn");
            com.Open();
            string qry = "SELECT EmailAddress FROM MyTable";
            var con = new SqlCommand(qry, com);

            //var recipients = new List<EmailAddress>{
            //new EmailAddress("Recipient1@test.co.uk", "User 1"),
            //new EmailAddress("Recipient2@test.co.uk", "User 2") };

            List<EmailAddress> columnData = new List<EmailAddress>();
            using (SqlCommand command = new SqlCommand(qry, com))
            {
                using (SqlDataReader bb = command.ExecuteReader())
                {
                    while (bb.Read())
                    {
                        columnData.Add(bb.GetString(0));
                    }
                }
            }
            var msg = new SendGridMessage();

            msg.SetFrom(new EmailAddress("Sender@azure.com", "Me"));


            var recipients3 = columnData;
            msg.AddTos(recipients3);

            msg.SetSubject("Without ttttt");

            msg.AddContent(MimeType.Text, "Dear Sir or Madam,!");
            msg.AddContent(MimeType.Html, "<p>Dear Sir or Madam,!</p>");

            var response = await client.SendEmailAsync(msg);
        }
    }

1 个答案:

答案 0 :(得分:0)

正如评论中指出的那样,您正在尝试将字符串添加到电子邮件地址列表中:

  while (bb.Read())
  {
      columnData.Add(bb.GetString(0)); //error is here.
  }

您需要创建一个新对象EmailAddress-使用您的检索字符串作为EmailAddress构造函数的参数:

while (bb.Read())
{
    columnData.Add(new EmailAddress(bb.GetString(0)));
}

编辑:

如果myTable中还有另一个字段,则将查询更改为:

string qry = "SELECT EmailAddress, Car FROM MyTable"; 

创建一个列表来保存汽车价值:

我假设Car列是一个字符串

var columnDataCar = new List<string>();

获取值:

while (bb.Read())
{
 columnData.Add(new EmailAddress(bb.GetString(0)));
 columnDataCar.Add(bb.GetString(1);
}

现在columnDataCar保存“汽车”字段的数据。

foreach(var item in columnDataCar)
{
 msg.AddContent(MimeType.Text, item);
}

希望有帮助。