Friday, September 7, 2012

Sending email from C# code using the GMail SMTP server

Here's how you send email through your Gmail account using C#.

using System;
using System.Net.Mail;
public static class EmailUtility
{
public static void SendEmail(string from, string[] to, string[] cc, string subject, string body, bool isHTML)
{
MailMessage message = new MailMessage
{
Subject = subject,
Body = body,
IsBodyHtml = isHTML,
From = new MailAddress(from),
};
Array.ForEach(to, c => message.To.Add(c));
Array.ForEach(cc, c => message.CC.Add(c));
SmtpClient SmtpMailer = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
Timeout = 50000,
EnableSsl = true
};
SmtpMailer.Credentials = new System.Net.NetworkCredential("youremail@gmail.com", "yourgmailpassword");
SmtpMailer.Send(message);
}
}
view raw EmailUtility.cs hosted with ❤ by GitHub

Wednesday, September 5, 2012

Utility to perform a parameterized SQL Query using ADO.NET

Here's a quick utility method to perform an ADO.NET SQL query. The main tricks are the use of a regular expression to parse out the parameters and the use of a queue to conveniently get the next parameter.

using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.Collections;
public static class SqlUtility
{
public static T ExecuteScalar<T>(string connStr, string query, params object[] queryParams)
{
using (var con = new SqlConnection(connStr))
using (var cmd = new SqlCommand(query, con))
{
var queue = new Queue(queryParams);
var matches = Regex.Matches(query, @"@\w+");
foreach (Match match in matches)
cmd.Parameters.AddWithValue(match.Value, queue.Dequeue());
con.Open();
T result = (T)cmd.ExecuteScalar();
return result;
}
}
}
view raw SqlUtility.cs hosted with ❤ by GitHub