如何发送电子邮件?

我有这样的数据表。

我有这样的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 

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

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

任何帮助都会很棒。

谢谢。

您可以使用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之前的SmtpClient类中存在一个错误 ,它没有正确地将QUIT命令发送到SMTP服务器。

 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 ", "Recipients Name ", "subject", "body"); // } client.Send(message); 
 private IEnumerable> 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( 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)); } } 

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

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