如何发送电子邮件?

时间:2010-08-16 08:38:55

标签: c# .net sql email ado.net

我有这样的数据表。

我有一张像这样的Excel表格。现在我正在从中读取数据并转换为这样的数据表:

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

现在我发送电子邮件给上述所有人。

任何人都可以帮助我如何从数据表中读取数据并使用指定的正文向他们发送邮件。

任何帮助都会很棒。

感谢。

4 个答案:

答案 0 :(得分:5)

您可以使用SmtpClient类:

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

备注1:在.NET 4.0中,SmtpClient实现IDisposable,因此请务必正确处理它。

备注2:.NET 4.0之前的bug类中有一个SmtpClient,它没有正确地将QUIT命令发送到SMTP服务器。

答案 1 :(得分:3)

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

答案 2 :(得分:3)

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

答案 3 :(得分:0)

您可以从数据库发送电子邮件。这些文章可能对您有帮助。

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