Sending E-Mail to Multiple Users from a Database
By Doug Seven
Published: 11/9/2001
Reader Level: Beginner
Rated: 5.00 by 1 member(s).
Tell a Friend
Rate this Article
Printable Version
Discuss in the Forums

The Question:

Anyone done this yet... I am interested in making a mail list system that will query database for email address for users and send out a generic e-mail.

The Answer:

This can be done using the System.Web.Mail namespace. This namespace has two classes you will use to accomplish this, MailMessage and SmtpMail. The MailMessage class represents a single e-mail message, and the SmtpMail class is used to send the MailMessage using the configured SMTP server.

The following code should be used in a method or event handler where the e-mail address are retreived from a database. Here you loop through the e-mail addresses, changing the "To" property of the MailMessage and sending it.

[VB]
'cmd is a SqlCommand that gets email addresses

Dim _r As SqlDataReader = cmd.ExecuteReader()
Dim _mm As System.Web.Mail.MailMessage = New System.Web.Mail.MailMessage()
_mm.From = "me@mydomain.com"
_mm.Body = "This is my e-mail message"
While _r.Read()
   _mm.To = _r("Email")
   System.Web.Mail.SmtpMail.Send(_mm)
Loop

[C#]
//cmd is a SqlCommand that gets email addresses

SqlDataReader _r = cmd.ExecuteReader();
System.Web.Mail.MailMessage _mm = new System.Web.Mail.MailMessage();
_mm.From = "me@mydomain.com";
_mm.Body = "This is my e-mail message";
while ( _r.Read() )
{
   _mm.To = _r["Email"];
   System.Web.Mail.SmtpMail.Send(_mm);
}

*Note: This thype of function is limited to the timeout settings of a Web request, so it will only work for up to around 1,000 e-mail addresses.



Marketplace
(Sponsored Links)
What are the green links?
   



 
Copyright © 2007 CMP Tech LLC |
Privacy Policy (4/10/06) | Your California Privacy Rights (4/10/06) | Terms of Service | Advertising Info | About Us | Help