Monday, February 13, 2012

Using JangoSMTP in ASP.Net

Microsoft provides classes for sending SMTP emails using the .Net Framework. This example uses System.Net.Mail to assemble then send an email using JangoSMTP.

Download the source code for this example, insert your own JangoSMTP username/password/etc and start sending tracked transactional emails in your asp.net application.

MailMessage mailMsg = new MailMessage();

// set the from address
// this must be stored in your from addresses
mailMsg.From = new MailAddress(
    "YourEmail@YourDomain.com", "Your Name");

// recipient
mailMsg.To.Add(new MailAddress(
    "ToAddress@Domain.com", "Recipient Name"));

// set the subject and message portions of the email
mailMsg.Subject = "Test Email Subject";
string text = 
    "This plain text email was sent from an ASP.Net script.";
string html = 
    "<p>This html email was sent from an ASP.Net script.</p>";
mailMsg.AlternateViews.Add(
    AlternateView.CreateAlternateViewFromString(
        text, null, MediaTypeNames.Text.Plain));
mailMsg.AlternateViews.Add(
    AlternateView.CreateAlternateViewFromString(
        html, null, MediaTypeNames.Text.Html));

// set up the SMTP client with relay.jangosmtp.net
SmtpClient smtpClient 
    = new SmtpClient("relay.jangosmtp.net", 25);
System.Net.NetworkCredential credentials = 
    new System.Net.NetworkCredential(
         "Your JangoSMTP Username", "Your JangoSMTP Password");
smtpClient.Credentials = credentials;

smtpClient.Send(mailMsg);