Sending a Form to HTML Email Using C# and asp.net 4.0

Sending a Form to HTML Email Using C# and asp.net 4.0

I often find myself needing to set up a form to email page on a website. For whatever reason, I am not able to always use the same code. So my latest code is included here. This code sends an HTML email from an asp.net 4 website using C#.


using System;
using System.Net;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Text;

public partial class contact : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
txtFirstName.Focus();
}

protected void btnSendMail_Click(object sender, EventArgs e)
{
string strEmail = txtEmail.Text;
string strFirstName = txtFirstName.Text;
string strLastName = txtLastName.Text;
string strFullName = (strFirstName + ” ” + strLastName);
string strAddress = txtAddress.Text;
string strCity = txtCity.Text;
string strState = txtState.Text;
string strZip = txtZip.Text;
string strPhone = txtPhone.Text;
string strRequest = txtRequest.Text;

MailAddress fromaddress = new MailAddress(txtEmail.Text, strFullName);
MailAddress toaddress = new MailAddress(“your email address here”);
MailMessage eMessage = new MailMessage(fromaddress, toaddress);
eMessage.From = fromaddress;
eMessage.To.Add(toaddress);
//eMessage.Bcc.Add(“bcc email address here if desired”);

StringBuilder ebody = new StringBuilder();
System.Net.Mail.SmtpClient Smtp = new System.Net.Mail.SmtpClient(“your smtp server here”);
Smtp.EnableSsl = false; //enable if your server requires it
NetworkCredential credentials = new NetworkCredential(“email@yourdomain.com”, “password for email@yourdomain.com”);
Smtp.Credentials = credentials;

ebody.Append(“

“);
ebody.Append(strFirstName);
ebody.Append(“

First Name
Last Name “);
ebody.Append(strLastName);
ebody.Append(“
Street Address “);
ebody.Append(strAddress);
ebody.Append(“
City “);
ebody.Append(strCity);
ebody.Append(“
State “);
ebody.Append(strState);
ebody.Append(“
Zip “);
ebody.Append(strZip);
ebody.Append(“
Daytime Phone “);
ebody.Append(strPhone);
ebody.Append(“
Email Address “);
ebody.Append(strEmail);
ebody.Append(“
Information Requested “);
ebody.Append(strRequest);
ebody.Append(“

“);

eMessage.Body = ebody.ToString();
eMessage.Subject = “Static Subject for Your Emails”;
eMessage.Priority = System.Net.Mail.MailPriority.High;
eMessage.IsBodyHtml = true;

try
{
Smtp.Send(eMessage);
Response.Redirect(“emailsent.aspx”);//generic page to send users to when email is sent
}

catch (Exception exc)
{
Response.Write(“Send failure: ” + exc.ToString());
}
}
}

Hopefully, this will help someone.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.