2

I have the following code that causes 'The SMTP host was not specified.' Any ideas why this happen? Many thanks

var mailMessage = new System.Net.Mail.MailMessage();
mailMessage.To.Add(new MailAddress("myemail@hotmail.co.uk"));
mailMessage.From = new MailAddress("atest@test.com");

mailMessage.Subject = "my test subject";
mailMessage.Body = "my test body";
mailMessage.IsBodyHtml = true;

var smtpClient = new SmtpClient { EnableSsl = true };
object userState = mailMessage;
smtpClient.Send(mailMessage);

I've tried the following now and it still fails

            var client = new SmtpClient("smtp.gmail.com", 587)
            {
                Credentials = new NetworkCredential("me@gmail.com", "password"),
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
               UseDefaultCredentials = false
            };

            var mail = new MailMessage("test@example.com", "me@gmail.com", "hello", "there");
            mail.Body = "Hello";
            mail.Subject = "hi";
            client.Send(mail);
James Radford
  • 1,815
  • 4
  • 25
  • 40
  • I'm not sure but, may be you should set your port number as 587 – Saeed Amiri Feb 20 '12 at 13:12
  • If it says the SMTP host was not specified, I'll bet you... didn't specify the SMTP host. See http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx, watch out for the `Host`property. – Roy Dictus Feb 20 '12 at 13:52

5 Answers5

2

Because you have not specified the smtpClient.Host property.

Jared Shaver
  • 1,339
  • 8
  • 12
1

You don't appear to have defined a server to send through, unless you have done this in your application config.

<system.net>
        <mailSettings>
            <smtp>
                <network host="127.0.0.1" port="25"/>
            </smtp>
        </mailSettings>
    </system.net>

You need to specify your settings rather than the local ones I used in the example above.

RubbleFord
  • 7,456
  • 9
  • 50
  • 80
1
var client = new SmtpClient(smtpServer, 25)
{
    Credentials = new NetworkCredential(userName, password),
    EnableSsl = false
};

MailMessage mail = new MailMessage(sender, receiver, head, body);
client.Send(mail);

You should specify your Smtp Server as shown above.


Or you can specify it at web.config file.

<mailSettings>
  <smtp>
    <network 
       host="server" 
       port="portNumber"
       userName="username"
       password="password" />
  </smtp>
</mailSettings>
emre nevayeshirazi
  • 18,983
  • 12
  • 64
  • 81
0

Did you add mailSettings in web.config? Please check the below link by Scott.

http://weblogs.asp.net/scottgu/archive/2005/12/10/432854.aspx

Ravi Vanapalli
  • 9,805
  • 3
  • 33
  • 43
0

Enable SSL before you send the message

smtpClient.EnableSsl=true;
Mubarek
  • 2,691
  • 1
  • 15
  • 24