开发者

How to send an email?

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    kiran@example.com     happy birthday   
234  ram      ram@example.com       happy birthday  
345  anu      anitha@example.com    how is the day going
357  rashmi   rashmi@example.com    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.


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("from@yourdomain.com");
    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.


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 <from@domain.com>", "Recipients Name <to@domain.com>", "subject", "body");
// }
client.Send(message);


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));
    }
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜