Console app to send form emails in C=
If you want to send form emails from the command line, based on data returned from a SQL server, then this bit of code might be what you;re looking for. I’m omitting the SMTP settings and Database settings, but it should be clear where they go.
private static void Main(string[] args)
{
var strBaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
var fs = new FileStream(strBaseDirectory + @”\content.txt”, FileMode.Open);
var sr = new StreamReader(fs);
var strTemplate = sr.ReadToEnd();// email and subject columns are mandatory
var strSQL = “select ‘someone’ as name, ‘xxxx@hotmail.com’ as email, ‘test’ as subject”;
var ds = ExecuteSQL(strSQL);
var intProgress = 0;
foreach (DataRow dr in ds.Tables[“sql”].Rows)
{
var strBody = strTemplate;
foreach (DataColumn dc in ds.Tables[“sql”].Columns)
{
strBody = strBody.Replace(“$” + dc.ColumnName + “$”, dr[dc.ColumnName].ToString());
}
sendEmail(dr[“email”].ToString(), dr[“subject”].ToString(), strBody);
Console.Clear();
intProgress++;
Console.Write(“Sent ” + intProgress + ” of ” + ds.Tables[“sql”].Rows.Count);
}
Console.ReadLine();
}
This calls two other functions, sendEmail and executeSQL which are: – I’m using Amazon SES, but any SMTP host would work fine here.
public static void sendEmail(string to, string subject, string body)
{
var client = new SmtpClient
{
Port = 587,
Host = “email-smtp.eu-west-1.amazonaws.com”,
EnableSsl = true,
Timeout = 10000,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(
“xxxxx”,
“xxxxx”)
};
var mm = new MailMessage(“xxxx@gmail.com”, to, subject, body)
{
BodyEncoding = UTF8Encoding.UTF8,
IsBodyHtml = true,
DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
};
client.Send(mm);
Thread.Sleep(1000);
}
And my ExecuteSQL is:
public static DataSet ExecuteSQL(string sql)
{
DataSet dataSet = null;
const String sqlConnection =
“Data Source=WWW.xxxxx.COM;Initial Catalog=xxxxx;User Id=xxxx;Password=xxxx”;
using (var conn = new SqlConnection(sqlConnection))
{
var command = new SqlCommand(sql) {Connection = conn};
var adapter = new SqlDataAdapter(command);
dataSet = new DataSet();
adapter.Fill(dataSet, “sql”);
}
return dataSet;
}
– Then , I’ve added a file called content.txt, and set its build action to “copy to output directory” with the content
Hi, $name$
This is a test email with some <b>HTML</b> content
😉