Send email to each email address in database

28 Dec

Some time ago I need something that read a email column in the database and send a generic message to the total amount of emails.

After seen this reference blog:http://forums.asp.net/t/1388722.aspx

Everything works great, I’m going to supply the code because some small things was change.

Note: The example was done in C#, I’m assuming that you create a C# web Form that create some default code.

Create this two controls:

<form id=”form1″ runat=”server”>
<div>
<asp:TextBox ID=”BodyTextBox” runat=”server”></asp:TextBox><br />
<asp:Button ID=”btnSendEmail” runat=”server” Text=”Button” OnClick=”btnSendEmail_Click” />
</div>
</form>

Code:

using System.Data.SqlClient;
using System.Net.Mail;

protected void btnSendEmail_Click(object sender, EventArgs e)
{
string strConn = ConfigurationManager.ConnectionStrings[“cs”].ConnectionString ;
using (SqlConnection objConn = new SqlConnection(strConn))
{
SqlCommand comEmailAddresses = new SqlCommand(“SELECT email from ee_email”, objConn);
objConn.Open();
using (SqlDataReader rdrEmailAddresses = comEmailAddresses.ExecuteReader())
{
while (rdrEmailAddresses.Read())
{
string emailAddress = (rdrEmailAddresses[“email”] is DBNull ? null : (string)rdrEmailAddresses[“email”]);
if (emailAddress != null)
{
bool success = false;
success = SendEmail(emailAddress);
if (!success)
{
//Handle this scenario if necessary
}
}
else
{
//Handle this scenario if necessary
continue;
}
}
}
}
}

private bool SendEmail(string emailAddress)
{

MailAddress SendFrom = new MailAddress(“username@domain.com“, “User Name“);
MailAddress SendTo = new MailAddress(emailAddress);
MailMessage Message = new MailMessage(SendFrom, SendTo);
Message.Subject = “Test email”;
Message.IsBodyHtml = true;
Message.Body = BodyTextBox.Text;
SmtpClient MessageSMTP = new SmtpClient(“yourexchangeserver”);
try
{
MessageSMTP.Send(Message);
return true;
}
catch (Exception ex)
{
//Exception handling code
return false;
}
}

Update:02-03-2010

This site one of the best on ASP.NET tutorials has a tutorial that covers mass email from database

Ref:http://aspnet101.com/tutorials.aspx?id=41

I hope this help

–evick

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: