Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send mail through C# asp.net for contact form

Tags:

c#

email

asp.net

I am trying to create contact form to send email (from and to will be from user interface):

try {
   MailMessage mail = new MailMessage();
   SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
   mail.From = new MailAddress("fromadd");
   mail.To.Add("toadd");
   mail.Subject = "Test Mail";
   mail.Body = "This is for testing SMTP mail from GMAIL";
   SmtpServer.Port = 587;
   SmtpServer.Credentials = new System.Net.NetworkCredential("username","password");
   SmtpServer.EnableSsl = true;

   SmtpServer.Send(mail);
   MessageBox.Show("mail Send");
}
catch (Exception ex) {
   MessageBox.Show(ex.ToString());
}

This works for only Gmail - however, I would like to make it work for any email provider - how would I go about this?

like image 564
user1785946 Avatar asked Oct 30 '12 14:10

user1785946


People also ask

Can we send email using C++?

Send Outlook Emails using C++Create an object of SmtpClient. Set host, username, password, and port number. Set security options. Send email using SmtpClient->Send() method.


1 Answers

You should configure the SmtpClient in the web.config:

<configuration>
  <system.net>
    <mailSettings>
      <smtp deliveryMethod="network">
        <network
          host="localhost"
          port="25"
          defaultCredentials="true"
        />
      </smtp>
    </mailSettings>
  </system.net>
</configuration>

Then in your code you can do:

    try
    {
        MailMessage mail = new MailMessage();
        mail.From = new MailAddress("fromadd");
        mail.To.Add("toadd");
        mail.Subject = "Test Mail";
        mail.Body = "This is for testing SMTP mail from GMAIL";

        SmtpClient SmtpServer = new SmtpClient();            
        SmtpServer.Send(mail);
        MessageBox.Show("mail Send");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
like image 152
SBurris Avatar answered Oct 07 '22 16:10

SBurris