C#: Send An Email Using a SMTP Server Such As SendGrid

2/9/2015 5:15:58 PM

You can use .NET to send emails using an SMTP email server. Services such as SendGrid.com, give you access to an SMTP server to send transactional emails. The following code will use SendGrid.com's SMTP server to send emails.

//message details
string subject = "Test Subject";
string plainBody = "Dear person," + Environment.NewLine + "This is for you.";
string htmlBody = "Dear <b>bold person</b>, <br /> This is for you.";
string fromEmail = "user@example.com";
string fromName = "Test From";
string toEmail = "user@example.com";
string toName = "Test To";    

//smtp server details
string smtpServer = "smtp.sendgrid.net";
string smtpUsername = "user@example.com"; //sendgrid username
string smtpPassword = "myPassword"; //sendgrid password
int smtpPort = 587;

System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();

if (fromName != null && fromName.Length > 0)
{
	msg.From = new System.Net.Mail.MailAddress(fromEmail, fromName);
}
else
{
	msg.From = new System.Net.Mail.MailAddress(fromEmail);
}

//add recipient
msg.To.Add(new System.Net.Mail.MailAddress(toEmail));

//message subject
msg.Subject = subject.Trim();

//HTML
if (string.IsNullOrEmpty(htmlBody))
{
	htmlBody = plainBody;
	htmlBody = htmlBody.Replace(Environment.NewLine, "<br />");
}

//add plain text view
System.Net.Mail.AlternateView objPlainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(plainBody);
msg.AlternateViews.Add(objPlainView);

//add html view
System.Net.Mail.AlternateView objHtmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(htmlBody, new System.Net.Mime.ContentType("text/html"));
msg.AlternateViews.Add(objHtmlView);

bool smtpEnabledSsl = false;
if (smtpPort != 25)
{
	smtpEnabledSsl = true;
}

System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(smtpUsername, smtpPassword);
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(smtpServer, smtpPort);
client.EnableSsl = smtpEnabledSsl;
client.UseDefaultCredentials = false;
client.Credentials = credentials;
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;

client.Send(msg);