call today Call Today 320.281.0605

Sending email on Rackspace Cloud using asp.net

January 20, 2010

I have hosted with the Rackspace Cloud now for about two years.  I really couldn’t be happier with them and would recommend them to anyone.  The one thing I have seemed to have issues with is sending emails from my web applications. After talking with support and doing some testing I have a solution that should last.

Here is an example of a basic contact form.

First set the smtp information in the web.config

<system.net>
 <mailSettings>
 <smtp>
 <network host="mail.emailsrvr.com" userName="info@mydomain.com" password="mypassword" port="25"/>
 </smtp>
 </mailSettings>
 </system.net>

I put this at the very bottom of the web.config just before the closing tag.

Note that the userName and password must be of a valid email address of the domain you are sending from. Make sure to set this up through their control panel.

I also add in the appSettings of the web.config the email addresses of whom to send it to and the subject line. Just best practices.

<appSettings>
 <add key="mailTo" value="joel@mydomain.com"/>
 <add key="mailSubject" value="Contact Form inquiry"/>
 </appSettings>

Now my example is of an asp.net web application in c#. I am going to assume everyone knows how to setup the page, lets go to the code-behind.

You will need to add these three lines to your using block.

using System.Web.Configuration;
using System.Text;
using System.Net.Mail;
The submit button handler:
 /// <summary>
 /// Handles the contact form submit
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void imtbtnSubmit_Click(object sender, ImageClickEventArgs e)
 {
 StringBuilder body = new StringBuilder();
 body.AppendFormat("Company Name: {0}{1}", txtCompany.Text, Environment.NewLine);
 body.AppendFormat("Contact Name: {0}{1}", txtName.Text, Environment.NewLine);
 body.AppendFormat("Phone: {0}{1}", txtPhone.Text, Environment.NewLine);
 body.AppendFormat("Email: {0}{1}", txtEmail.Text, Environment.NewLine);
 body.AppendLine();
 body.AppendLine("Message");
 body.AppendLine(txtMessage.Text);

 MailMessage message = new MailMessage(txtEmail.Text, WebConfigurationManager.AppSettings["mailTo"], WebConfigurationManager.AppSettings["mailSubject"], body.ToString());

 SmtpClient client = new SmtpClient();
 client.Send(message);

 pnlForm.Visible = false;
 lblMessage.Visible = true;
 }

Pretty simple stuff, the import part is system.net in the web.config, making sure you have the correct host and port  and a valid email.

You would think they would have this in their knowledge base, but as of this writing they don’t. I hope this helps someone.

One Response to “Sending email on Rackspace Cloud using asp.net”

  1. [...] the button handler I add the logic to simply email the submitted form to a desired email.  See my previous post on how to do [...]

Leave a Reply

Security Code:

Download Full Movie Online Lamictal