-1

I'm using a table (Table has the location and mail id's) to get the e-mail id based on which location we are selecting.

Trying to send the mail gives the following error:

The specified string is not in the form required for an e-mail address.

Code:

public void sendmail()
{
    SqlCommand cmd = new SqlCommand("select EmailID from Table where Location='"+Location.Text+"'",con);
    cmd.ExecuteNonQuery();
    string EmpMail = "Test@gmail.com";
    string EmpMailTo = "cmd";

    MailMessage message = new MailMessage(EmpMail, EmpMailTo);
    SmtpClient client = new SmtpClient();
    message.Subject = "Auto generated mail";
    message.IsBodyHtml = true;

    message.Body = "Test mail for auto generation";
    client.Host = "Apprelay";
    client.Send(message);
}

Can anyone please help me to fix this? Thanks in advance.

Zong
  • 6,160
  • 5
  • 32
  • 46
user2842413
  • 7
  • 1
  • 2
  • 5

1 Answers1

5
string EmpMailTo = "cmd";

I'm pretty sure cmd is not a valid email address.

My psychic debugging skills tell me that it's on this line:

MailMessage message = new MailMessage(EmpMail, EmpMailTo);

...and that it's a FormatException based on the documentation.

Try making EmpMailTo a valid email address.

tnw
  • 13,521
  • 15
  • 70
  • 111
  • am using sql query to get the mail id from a table.Query: (sqlcommand cmd = new sqlcommand("select EmailID from Location where Location='"+Location.text+"'",con) – user2842413 May 06 '14 at 19:09
  • 2
    @user2842413: No you're not, you're setting the email address to the string literal "cmd". You never actually fetch a result from your SQL query. – David May 06 '14 at 19:10
  • If you use quotes it is a string. You need to execute the command and use the result. – Peter May 06 '14 at 19:10
  • 1
    @user2842413 `string EmpMailTo = "cmd";` sets `EmpMailTo` to the *string* `cmd`. `string EmpMailTo = cmd;` wouldn't really make any sense either though – tnw May 06 '14 at 19:11
  • oh okay. Then can u guys please give me the right solution for that am new for c# – user2842413 May 06 '14 at 19:12
  • 1
    @user2842413 You need to read up on how to actually fetch data from SQL properly. Start with reading the documentation: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx – tnw May 06 '14 at 19:13
  • @user2842413 Please also read about SQL injection... this is very important if you're going to be a developer: http://stackoverflow.com/questions/6547986/how-to-prevent-a-sql-injection-escaping-strings – tnw May 06 '14 at 19:14
  • @user2842413 Yes, I told you this wouldn't work already. Like I said, you need to read about how to actually fetch data from SQL properly. Did you bother to read any of the links I sent you? – tnw May 07 '14 at 14:20