Question

what I'm trying to achieve in my code below is to send an email for each email address that can be found in my database. My problem is when I click my send button an errors says that "The specified string is not in the form required for an e-mail address." on the mail.Bcc.Add(MyVar.Text) line.

private void sendmail()
    {
        Label MyVar = new Label();
        foreach (DataRowView UserEmail in SelectUserProfile.Select(DataSourceSelectArguments.Empty))
        {
            MyVar.Text = "";
            MyVar.Text += UserEmail["EMAIL"].ToString() + "; ";
        }

        //This line takes the last ; off of the end of the string of email addresses
        MyVar.Text += MyVar.Text.Substring(0, (MyVar.Text.Length - 2));

        MailMessage mail = new MailMessage();

        mail.Bcc.Add(MyVar.Text);
        mail.From = new MailAddress("syntaxbugerror@gmail.com");
        mail.Subject = "New Member Application";
        mail.Body = "Good day, in this e-mail you can find a word document attached in which it contains new membership application details.";
        mail.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Credentials = new System.Net.NetworkCredential("myusername@gmail.com", "mypassword");
        smtp.EnableSsl = true;
        smtp.Send(mail);
    }

Ernie

Was it helpful?

Solution

Why are you buliding a string of the BCC email addresses?

The Bcc is a collection, so just treat it as such. I'm not really sure what you're doing with the label or why, so just ignoring that for now, something like this should work

MailMessage mail = new MailMessage();

foreach (DataRowView UserEmail in SelectUserProfile.Select(DataSourceSelectArguments.Empty))
{
   MyVar.Text = "";
   MyVar.Text += UserEmail["EMAIL"].ToString() + "; ";

   try
   {
       mail.Bcc.Add(UserEmail["EMAIL"].ToString());
   }
   catch(FormatException fe)
   {
      // Do something with the invalid email address error.
    }
}

OTHER TIPS

Your logic flow doesn't make sense. You're parsing together emails and then attempting to unparse your email addresses through some flawed logic. Instead, create your mail message and then loop through your email addresses, adding each to the BCC.

// Create Message (...)
foreach(...)
{
   mail.Bcc.Add(UserEmail["EMAIL"].ToString()); 
}
// Finalize and send (...)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top