Marzi H
Marzi H

Reputation: 23

Sending email in asp.net

I want to send an email from my site's email "[email protected]". But there is an error and the email don't send. here in my code and error :

public void SendMail(string Subject, string To, string Body)
{
    SmtpClient MyMail = new SmtpClient();
    MailMessage MyMsg = new MailMessage();
    MyMail.Host = "[email protected]";
    MyMsg.To.Add(new MailAddress(To));
    MyMsg.Subject = Subject;
    MyMsg.SubjectEncoding = Encoding.UTF8;
    MyMsg.IsBodyHtml = true;
    MyMsg.From = new MailAddress("[email protected]", "myname");
    MyMsg.BodyEncoding = Encoding.UTF8;
    MyMsg.Body = Body;
    MyMail.UseDefaultCredentials = false;
    NetworkCredential MyCredentials = new NetworkCredential("info@sitename", "pass");
    MyMail.Credentials = MyCredentials;
    MyMail.Send(MyMsg);
}

This is the error: error message

Upvotes: 1

Views: 90

Answers (1)

Jim
Jim

Reputation: 6881

You are misunderstanding what the SmtpClient Host property is used for.

This line of code here is wrong...

MyMail.Host = "[email protected]";

MyMail.Host should point to your SMTP server - you're trying to set it to the FROM address.

You are already setting the FROM address in your MailMessage object, int he line shown below...

MyMsg.From = new MailAddress("[email protected]", "myname");

So, just to give you an example, I might have a server at the IP 10.1.0.5 and it runs an SMTP server on port 25. You would set your MyMail.Host = "10.1.0.5", or even better just set it in the constructor like this...

SmtpClient MyMail = new SmtpClient("10.1.0.5", 25);

Now, this is just an example - I don't know if / where you might have an SMTP server set up. But if you don't have an SMTP server set up, that's something you're missing. If you do have it set up, the Host property should be its IP or domain name.

Upvotes: 1

Related Questions