Search code examples
c#emailsmtpclient

Can we send mails from localhost using asp.net and c#?


i am using using System.Net.Mail;

and following code to send mail

MailMessage message = new MailMessage();
        SmtpClient client = new SmtpClient();

        // Set the sender's address
        message.From = new MailAddress("fromAddress");

     // Allow multiple "To" addresses to be separated by a semi-colon
        if (toAddress.Trim().Length > 0)
        {
            foreach (string addr in toAddress.Split(';'))
            {
                message.To.Add(new MailAddress(addr));
            }
        }
      // Allow multiple "Cc" addresses to be separated by a semi-colon
        if (ccAddress.Trim().Length > 0)
        {
            foreach (string addr in ccAddress.Split(';'))
            {
                message.CC.Add(new MailAddress(addr));
            }
        }
        // Set the subject and message body text
        message.Subject = subject;
        message.Body = messageBody;

        // Set the SMTP server to be used to send the message
        client.Host = "YourMailServer";

        // Send the e-mail message
        client.Send(message);

for Host i am providing client.Host = "localhost";

for this its falling with error

No connection could be made because the target machine actively refused it some_ip_address_here

and when i use client.Host = "smtp.gmail.com";

i get following error

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

i am not able to send mail through localhost. Please help me out, i am new to c# please correct me in code where i am going wrong..?


Solution

  • Here is some code that works for sending mail via gmail (code from somewhere here on stackoverflow. It is similar to the code here: Gmail: How to send an email programmatically):

    using (var client = new SmtpClient("smtp.gmail.com", 587)
    {
      Credentials = new NetworkCredential("[email protected]", "yourpassword"),
      EnableSsl = true
    })
    {
      client.Send("[email protected]", "[email protected]", "subject", message);
    }