Sending emails with C#.net

Sending emails with c#.net was actually surprisingly easy (note that I only tested it on an asp.net form in Server 2003). Adding attachments etc was also surprisingly easy (no need to worry about mime boundaries etc).
Pre-Reqs:
The machine that the application is running on must be running an SMTP service (this can be set up with the Server Configuration Wizard). Once this is set up, you must allow relay access from localhost…

  1. Go to: start > settings > control panel > Administrative Tools > Internet Information Services
  2. Expand the ” (local computer)” node
  3. Right click on your SMTP server > go to “Properties”
  4. Click “Access” tab
  5. Under Relay Restrictions, click the “Relay” button
  6. Click “Add”
  7. Select “Single Computer” and enter IP address 127.0.0.1
  8. Hit OK, OK, OK (until the properties dialog is closed)

Actually Sending Emails
Add “using System.Web.Mail;” to the top of the relevant file

MailMessage mail = new MailMessage();
mail.To = "test@example.com";
mail.From = "from@example.com";
mail.Subject = "Contact from website";
mail.Body = "Email body";
SmtpMail.SmtpServer = "localhost";
SmtpMail.Send(mail);

I wont go on too much about sending attachments – its all pretty well explained at http://www.codersource.net/csharp_sending_emails.aspx
Stop press – sending with .net 2
http://msdn2.microsoft.com/en-US/library/system.net.mail.mailmessage.aspx
Note
If you are using windows SMTP be sure that any line ending characters in the message are of the form \r\n and not just \n. I have had issues in the past with relay servers failing to send wrongly formatted line endings. Apparently 822bis (not sure what this is) specifically prohibits other uses of LF.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>