freej17
freej17

Reputation: 371

Send mail stored in a variable

I have a simple table(MyEmail) in SQL with some emails that need to be sent, for example:

ID  Email
1   [email protected]
2   [email protected]
3   [email protected]
4   [email protected]

I made a stored procedure(GetAddress) to collect them so I can later store them into a variable:

 SELECT  Email
 FROM dbo.MyEmai

I need help with the C# part of the code:

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 
                    }

This code returns list but emails are located bellow WebApplication.MyPage. Email names. MyEmails return :

WebApplication.MyPage.Email > [email protected] 
WebApplication.MyPage.Email > [email protected] ...

And I need this WebApplication.MyPage.Email removed so only emails will be shown as strings first.

Code that sends emails:

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("[email protected]", "");


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

                            client.Send(mm);

So because of this MyEmails has an error : Error 24 Argument 2: cannot convert from 'System.Collections.Generic.List' to 'string'

Can someone help me with this?

Thanks in advance!

Upvotes: 0

Views: 168

Answers (1)

RazorShorts
RazorShorts

Reputation: 115

The MailMessage class from .Net does not accepts a List as a valid parameter. Iiterate over your collection creating multiple mailmessage.

The code should look something like this

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("[email protected]", emailadresstring, "New Mail subject", "This is Email body !");
// Do you magic with the mail message
 }

Upvotes: 3

Related Questions