2010-08-16 126 views
2

我有這樣的數據表。如何發送電子郵件?

我有一個這樣的Excel工作表。現在我正在讀取數據並轉換成如下數據表:

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 

現在我要發送電子郵件給以上所有人。

任何人都可以幫助我如何從數據表中讀取數據,並通過指定的正文向他們發送郵件。

任何幫助將是偉大的。

謝謝。

+0

@ prince23:我認爲,這將是可取的不同標記您的問題。首先,你似乎已經關注了'SQL'部分。所以這主要是發送'email'。 (而且你用'C#'做這個事實引發了你是否想用'.NET'框架發送郵件的問題?) – stakx 2010-08-16 08:45:30

+0

可能有很多重複的問題 – 2010-08-16 10:26:41

回答

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 <[email protected]>", "Recipients Name <[email protected]>", "subject", "body"); 
// } 
client.Send(message); 
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("[email protected]"); 
    message.Body = body; 
    var smtpClient = new SmtpClient("yoursmtphost"); 
    smtpClient.Send(message); 
} 

備註1:在.NET 4.0中,SmtpClient實現IDisposable,所以一定要正確處理它。

備註2:在.NET 4.0之前的類SmtpClient中有bug類,它沒有正確發送QUIT命令到SMTP服務器。

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