发送存储在变量中的邮件

时间:2018-07-20 11:42:44

标签: c# sql-server stored-procedures

我在SQL中有一个简单的表(MyEmail),其中包含一些需要发送的电子邮件,例如:

ID  Email
1   name@yahoo.com
2   something2@yahoo.com
3   name3@google.com
4   something4@yahoo.com

我制作了一个存储过程(GetAddress)来收集它们,以便以后可以将它们存储到变量中:

 SELECT  Email
 FROM dbo.MyEmai

我需要代码的C#部分的帮助:

var MyEmails = new List<Email>();
                    SqlCommand cmdEmails = new SqlCommand("GetAddress", connection);
                    SqlDataReader rdEmails = cmdEmails.ExecuteReader();
                    while (rdEmails.Read())
                    {
                        MyEmails.Add(new Email() { MyEmails = rdEmails[0].ToString() }); // as an example 
                    }

此代码返回列表,但电子邮件位于WebApplication.MyPage下。 电子邮件名称。 MyEmails返回:

WebApplication.MyPage.Email > name@yahoo.com 
WebApplication.MyPage.Email > something2@yahoo.com ...

我需要删除此WebApplication.MyPage.Email,以便仅电子邮件首先显示为字符串。

发送电子邮件的代码:

SmtpClient client = new SmtpClient();
                            client.Port = 112;

                            client.Host = "my-smtp";
                            client.Timeout = 10000;
                            client.DeliveryMethod = SmtpDeliveryMethod.Network;
                            client.UseDefaultCredentials = false;

                            client.Credentials = new System.Net.NetworkCredential("myEmail@provider.com", "");


                            MailMessage mm = new MailMessage(LocalName, LocalName + MyEmails, "New Mail subject", "This is Email body !");

                            client.Send(mm);

因此,由于此MyEmails出现错误:错误24参数2:无法从'System.Collections.Generic.List'转换为'string'

有人可以帮我吗?

谢谢!

1 个答案:

答案 0 :(得分:3)

.Net中的MailMessage类不接受列表作为有效参数。遍历您的集合,创建多个邮件消息。

代码应如下所示

foreach (var emailadressObject in myEmails)
{
// get your emailadres string from your object..
// Bit confusion using a collection MyEmails and a Property in you mail objetc with MyEmails
var emailadresstring = emailadressObject.MyEmails; 
    var message = new MailMessage("from@me.com", emailadresstring, "New Mail subject", "This is Email body !");
// Do you magic with the mail message
 }