Zvonimir Tokic
Zvonimir Tokic

Reputation: 461

The specified string is not in the form required for an e-mail address, no Idea what is wrong?

I know that this question already exist, but i read all of them and I did not found answer. This is my SendEmail method.

   public bool SendEmail(PostEmail postEmail)
{
  if (string.IsNullOrEmpty(postEmail.emailTo))
  {
    return false;
  }

  using (SmtpClient smtpClient = new SmtpClient())
  {
    using (MailMessage message = new MailMessage())
    {
      message.Subject = postEmail.subject == null ? "" : postEmail.subject;
      message.Body = postEmail.body == null ? "" : postEmail.body;
      message.IsBodyHtml = postEmail.isBodyHtml;
      message.To.Add(new MailAddress(postEmail.emailTo));

      try
      {
        smtpClient.Send(message);
        return true;
      }
      catch (Exception exception)
      {
        //Log the exception to DB
        throw new FaultException(exception.Message);
      }
    }
  }

I have this error in question

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

I have no idea what could be wrong. Please any help ?

Upvotes: 0

Views: 3329

Answers (2)

Zvonimir Tokic
Zvonimir Tokic

Reputation: 461

This is correct way of defining client and sending email. The complete structure off defining was wrong, it was not just about emailTo string

namespace App.MYEmailApp.Service {

public class EmailService : IEmailService {

public void SendEmail(PostEmail postEmail)
{

  MailAddress from = new MailAddress(postEmail.emailFrom, postEmail.emailFromName);
  MailAddress to = new MailAddress(postEmail.emailTo, postEmail.emailToName);
  MailMessage message = new MailMessage(from, to);
  message.Subject = postEmail.subject;
  message.Body = postEmail.body;
  MailAddress bcc = new MailAddress("[email protected]");
  message.Bcc.Add(bcc);
  SmtpClient client = new SmtpClient();
  //client.UseDefaultCredentials = false;
  //client.Credentials.GetCredential("smtp.xxxx.com", 587, "server requires authentication");
  Console.WriteLine("Sending an e-mail message to {0} and {1}.", to.DisplayName, message.Bcc.ToString());
  try
  {
    client.Send(message);
  }
  catch (Exception ex)
  {
    Console.WriteLine("Exception caught in CreateBccTestMessage(): {0}",
                ex.ToString());
  }




}

}

public class PostEmail {

public string emailTo;
public string emailToName;
public string subject;
public string body;
public string emailFrom;
public string emailFromName;
public bool isBodyHtml;

}

}

Upvotes: 0

A S
A S

Reputation: 122

put a break point on the line

message.To.Add(new MailAddress(postEmail.emailTo));

and when the debugger hits the line when you run the code check that value of the email address in postEmail.emailTo

its most likely in a wrong format and that's what's generating the error.

Upvotes: 1

Related Questions