tags:

views:

147

answers:

4

hi, i have an datatable like this.

i have an excel sheet like this. now i am reading the data from that and converting into an datatable like this

id   Name     MailID                Body

123  kirna    [email protected]     happy birthday   
234  ram      [email protected]       happy birthday  
345  anu      [email protected]    how is the day going
357  rashmi   [email protected]    work need  to be completed

now i to send email to all the above person.

can any one help me how i can read data from datatable and send mail to them with the body what is been specified.

any help would be great

thanks

+3  A: 
System.Net.Mail.SmtpClient client = 
    new System.Net.Mail.SmtpClient("yoursmtp.server.com");
// foreach row in datatable{
System.Net.Mail.MailMessage message = 
    new System.Net.Mail.MailMessage("Your Name <[email protected]>", "Recipients Name <[email protected]>", "subject", "body");
// }
client.Send(message);
Albin Sunnanbo
+5  A: 

You could use the SmtpClient class:

foreach (DataRow row in datatable.Rows)
{
    var name = (string)row["Name"];
    var email = (string)row["MailID"];
    var body = (string)row["Body"];

    var message = new MailMessage();
    message.To.Add(email);
    message.Subject = "This is the Subject";
    message.From = new MailAddress("[email protected]");
    message.Body = body;
    var smtpClient = new SmtpClient("yoursmtphost");
    smtpClient.Send(message);
}

Remark1: In .NET 4.0, SmtpClient implements IDisposable, so make sure to properly dispose it.

Remark2: There's a bug in SmtpClient class prior to .NET 4.0 which doesn't properly send the QUIT command to the SMTP server.

Darin Dimitrov
+3  A: 
private IEnumerable<Tuple<string,string,string>> GetMessages()
{
using (var connection = new SqlConnection("connection string")
using (var command = connection.CreateCommand())
{
    command.CommandText = "SELECT Name, MailID, Body FROM table";

    connection.Open()
    using (var reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            yield return new Tuple<string,string,string>(
                reader.GetString(0), // name
                reader.GetString(1) // email
                reader.GetString(2)); // body
        }
    }
}
}

foreach(var tuple in GetMessages())
{
    SendMessage(tuple.Item1, tuple.Item2, tuple.Item3);
}

private void SendMessage(string name, string email, string body)
{
    using (var smtpClient = new SmtpClient("smtp.example.com"))
    {
         smtpClient.Send(new MailMessage(
             name, // from
             email, // to
             "Subject",
             body));
    }
}
abatishchev
A: 

You can send email from Data base .These articles might help you .

http://msdn.microsoft.com/en-us/library/ms190307.aspx
http://msdn.microsoft.com/en-us/library/ms189505.aspx

Alex