0

I have created a form with a list box called lstCompany which displays search data, search textboxes are the "Name" and "PostCode" of company. I have a table called tblCompany which contains CompanyNo(primary key) with company details in the database including email. I would like to know how I can send email to the companies that I search on the list box. I have done the code which only sends email to one person who i put in code. Below is the code for send button

        var fromAddress = new MailAddress("myemail", "name");
        var toAddress = new MailAddress("other person's email", "name");
        const string fromPassword = "password";
        const string subject = "Testing";
        const string body = "Testing";

        var smtp = new SmtpClient
        {
            Host = "smtp.gmail.com",
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
        };
        using (var message = new MailMessage(fromAddress, toAddress)
        {
            Subject = subject,
            Body = body
        })
        {
            smtp.Send(message);
            MessageBox.Show("Your email has been sent!");
        }
    }
  • Are you asking how to send to multiple person? If so, The to address is a collection, so you can add as many as you want – XtremeBytes Apr 16 '15 at 18:21
  • Yes, I would like to send it to multiple people but from the list box in the form. I want it to select people from the table automatically as in the code above, I had to type it in manually. – user4778129 Apr 16 '15 at 18:33
  • why can't you read the data from the listbox? I am not getting your question. – XtremeBytes Apr 16 '15 at 18:36
  • Did you try to add a selected index changed event to your listbox in order to populate your toAdress? – Fjodr Apr 16 '15 at 19:05
  • The code you provided is taking care of send an email. Please provide the code of the actual list box, and the event or handler (ie. click of button) where you are trying to send to those addresses so we can analize your problem. – zed Apr 16 '15 at 19:21

1 Answers1

1

try something like this:

private MailMessage m = new MailMessage();

protected void ListTo_SelectedIndexChanged(object sender, EventArgs e)
{
     m.To.Add(new MailAddress("adress@mail.com"));
}

If you your listbox manages multi selection, you may prefer:

protected void Button_Click(object sender, EventArgs e)
{            
    MailMessage m = new MailMessage();

    foreach (ListItem item in ListBox1.Items)
    {
        if (item.Selected)
            m.To.Add(new MailAddress(item.Value));
    }
}
Fjodr
  • 919
  • 13
  • 32