Send email to each email address in database

Hi,

I'm trying to write a web form which allows my client to put their raw html into a textbox and then click send and it will send the email to each individual email address in the database.

I want it to send the emails individually not compile a long list of emails in BCC field so i know I'm going to need a foreach loop. Just not sure where to go from here:

email.aspx

Message
<asp:TextBox ID="BodyTextBox" runat="server" TextMode="MultiLine" /><br />

<asp:Button ID="EmailButton" runat="server" Text="Send email" OnClick="EmailButton_Click" /><br />

 

email.aspx.cs

protected void EmailButton_Click(object sender, EventArgs e)
    {

string strConn = ConfigurationManager.ConnectionStrings["MSSQLConnection"].ToString();
SqlConnection objConn = new SqlConnection(strConn);
SqlCommand objCommand = new SqlCommand("SELECT email FROM tableOne", objConn);
objConn.Open();

try
{

MailAddress SendFrom = new MailAddress("no-reply@mydomain.com", "Joe Bloggs");
MailAddress SendTo = ??? 

MailMessage Message = new MailMessage(SendFrom, SendTo);
Message.Subject = "Test email";
Message.IsBodyHtml = true;
Message.Body = BodyTextBox.Text;
               
SmtpClient MessageSMTP = new SmtpClient();
MessageSMTP.Send(Message);

           }


        catch (Exception ex)
        {

        }

    }

 

Any help would be greatly appreciated. Thanks

0
sainz23
2/23/2009 4:25:18 PM
asp.net.getting-started 91979 articles. 4 followers. Follow

5 Replies
905 Views

Similar Articles

[PageSpeed] 6
Get it on Google Play
Get it on Apple App Store

Foreach(Datarow dr in Dt.rows)

{

message.bcc.add(dr["Email"].tostring()); // If you have only Email in your datatable

mailmsg.Bcc.Add(new MailAddress(dr["Email"], Dr["DisplayName"])); // If you have both Email and display name in you datatable

}


Better Post your code before asking some thing, some one. So that person helping u will understand u r problem Clearly

Yahoo IM : dotnetruler

I am trying to keep Frequently Asked Questions in my blog
0
dotnetruler
2/23/2009 4:45:32 PM

 First of all, why do u want to send emails one by one? If u send too many emails in a small interval, your IP will be blocked by ISPs for potential spamming. So its advisable to send emails at one shot if there is no change in the content. Add all the recepients in BCC and send the mails..

 

if u are adamant and u wan to send emails one by one, do this

first read all the emails to a datareader //google how to fill the reader.

now code

 

 
while(reader.Read())

{
MailAddress SendFrom = new MailAddress("no-reply@mydomain.com", "Joe Bloggs");
MailAddress SendTo = reader["toaddress"]; //this might not be correct . u need to refer correct syntax.
 MailMessage Message = new MailMessage(SendFrom, SendTo );
Message.Subject = "Test email";
Message.IsBodyHtml = true;
Message.Body = BodyTextBox.Text;
SmtpClient MessageSMTP = new SmtpClient();
}
 

Please: Don't forget to click "Mark as Answer" on the post that helped you. That way future readers will know which post solved your issue.

http://blog.nishanthnair.com
0
nishanthnair
2/23/2009 4:53:15 PM

Something like this should do the trick:

  protected void btnSendEmail_Click(object sender, EventArgs e)
  {
    string strConn = ConfigurationManager.ConnectionStrings["MSSQLConnection"].ToString();
    using (SqlConnection objConn = new SqlConnection(strConn))
    {
      SqlCommand comEmailAddresses = new SqlCommand("SELECT...", objConn);
      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("no-reply@mydomain.com", "Joe Bloggs");
    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();
    try
    {
      MessageSMTP.Send(Message);
      return true;
    }
    catch (Exception ex)
    {
      //Exception handling code
      return false;
    }
  }

I haven't tested this, so give it a go and let me know about any errors you get.

One thing is that the code assumes you have your application configured to work with a mail server in web.config. If not, give me a shout and I'll tell you what you need to put in there.

Cheers

David

0
Dovdimus
2/23/2009 4:54:16 PM

Hi, thanks Dovdimus

I tried your code and got the following error:

ExecuteReader requires an open and available Connection. The connection's current state is closed.

So i just added an   objConn.Open(); and close as below and it worked great, gonna do some testing later and post my results, but initially it looks great, thank you so much!

 

    protected void EmailButton_Click(object sender, EventArgs e)
    {
       
        string strConn = ConfigurationManager.ConnectionStrings["MSSSQLConnection"].ToString();
        using (SqlConnection objConn = new SqlConnection(strConn))
           

        {
          SqlCommand comEmailAddresses = new SqlCommand("SELECT .....", 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;
              }
            }
          }
            objConn.Close();

        }
      }

      private bool SendEmail(string emailAddress)
      {
        MailAddress SendFrom = new MailAddress("no-reply@mydomain.com", "My Clients name");
        MailAddress SendTo = new MailAddress(emailAddress);
        MailMessage Message = new MailMessage(SendFrom, SendTo);
        Message.Subject = "Blah blah blah";
        Message.IsBodyHtml = true;
        Message.Body = BodyTextBox.Text;
        SmtpClient MessageSMTP = new SmtpClient();
        try
        {
          MessageSMTP.Send(Message);
          return true;
        }
        catch (Exception ex)
        {
          //Exception handling code
          return false;
        }
      }

0
sainz23
2/24/2009 2:16:57 PM

Ah cool, good work.

In case you haven't seen them before, those using blocks:

using (SqlConnection conEmailAddresses = new SqlConnection(strConn))

{

 //blah blah

}

Are for automatically disposing of resources. When code execution leaves the using block (even in the case of an exception being thrown, I believe), the SqlConnection (or whatever object)'s Dispose method is called. Well handy.

Cheers

David

0
Dovdimus
2/24/2009 2:33:37 PM
Reply:

Similar Artilces:

Getting email address in gridview row and send email
Hi guys, How do i get the email address in my gridview rows?  I wanna get all the email address of all of my records in the gridview and use the email address to send an email to the owner. Thanks,*A newbie C# programmer* hi have a look at threse related : http://forums.asp.net/p/1119999/1746089.aspx#1746089http://forums.asp.net/t/1062163.aspxhttp://www.velocityreviews.com/forums/t93436-gridview-hyperlink-column-mailto-event.html Regards,Anas Ghanem.Note:Please Don't hesitate to click "Report Abuse" link if you noticed something wrong on the forums (l...

Send email to email address and update DNN database (hmmm???)
Hello friends! We currently have a transport client that receives a number of emails per day detailing traffic conditions from another government body (Mainroads). The marketing manager of Main Roads sends these emails to approximately 50 people around the state who process them in their own unique way. What I am wanting to do is setup an email address (eg MainRoads@OurClient.com). The Main Roads marketing manager will then include this address in her ‘to’ list. When our server receives this email it will then be parsed and transferred (the mail server/web server are on differen...

Get email address from DB and send email using VB
OK every time I figure something out on my own, there's 10 more things I can't seem to figure out. I feel like a VB moron. Ha. Anyway. Here's what I need to do...1. Retrieve the email addresses from my database table of people whose memberships to my organization has expired in the past month.2. Somehow plug those email addresses into a code to send them a prewritten, preformatted email.I have found an article on how to send an email using VB coding. I just don't know how I would send one email to every person whose membership has expired in the past month. Ideally, I'd like to be able to lo...

Non existing email address cancels sending to other email addresses
Hello ppl.. My WebApp sends emails to a series of email addresses without any problem... the problem is that when i send a email to a series of email addresses which contains a non existing email account... the email doesn't go at all.. Do you know what's the problem and what can be the resolution? Thanks in advance Bracoute How are you running the email process? Is it running in multiple threads so that more than 1 is sending at a time? If not, this should take care of that. Perhaps checking the email addresses for validation before allowing them to be entered into the databas...

EMail address removed from address book remains when I send EMail to a list
I don't understand why I can't remove an EMail address from a mailing list. An address I removed from a mailing list remains when I send EMail to a list. Consequently unwanted mail is sent and I receive bounce messages in return - - since it is no longer valid. What is required to remove an entry from a mailing list and rely that it won't be included as if I had not removed it? -- Regards, TOM BLACKWELL TOM BLACKWELL wrote: > > I don't understand why I can't remove an EMail address from a mailing list. > > An ad...

new data type: email address. validating email addresses at the database
Recently we had a problem where a bunch of email communications were not sent by our application because one email address, in the group, was not a valid email address. We develop in PB. The email message and email addresses are sent in batch to a black box which handles the details. In this instance, the message did not go out to any recepients because one email address was not valid. I was wondering if we might need a new email address data type? We would then not be able to save invalid email addresses to the database. Also, until we see the email address data type, an...

default email address for sending email
How do I set this? Thanks David K melbourne.au On 7/29/2006 3:49 PM, D Kinston wrote the following and I, Dennis Marks, have replied at the bottom: > How do I set this? > > Thanks > > David K > melbourne.au Click tools/account settings. Click the specific account in the left pane of the new window. Fill in appropriate boxes in the right pane. -- Dennis M. Marks Disclaimer: The above is my opinion. I do not guarantee it. Be sure to back up any files involved and use at your own risk. Batteries not included. Not for internal use. Don't ru...

sending to email addresses @email.com
Hello, I am experiencing strange errors.. but only on one particular email suffix i can email any address but as soon as i get xxxxx@email.com i get an error any one had the same error ? Thanks When do you get the error? What does the error say?-- Mike PopeASP.NET User EducationThis posting is provided "AS IS" with no warranties, and confers no rights. Is it possible that you are banned or on some kind of spammer list for them?...

what if email address is wrong when sending email ?
 Hi Guys, Is there any way to get error info when sending email if to or cc email address is wrong? I am using asp.net with c# and using local SMTP server. Thanks in advance. Justin  define "wrong". If you mean it's not a valid FORMAT, meaning no @ and no "." then yes... you can.If you mean that the account doesn't existing...then Nope.... you can't. You can validate the email address to make sure that it is in a valid format, but your ASP.NET application only handles sending the email to the SMTP server.  You can't get a...

Default email address for sending emails
Hi, My default email address has been suspended, and now I need to set TB up to use a different email address as the default one for sending emails. Can you tell me where to do this? Catherine Catherine wrote, On 23/07/08 14:14: > Hi, > > My default email address has been suspended, and now I need to set TB up > to use a different email address as the default one for sending emails. > Can you tell me where to do this? > > Catherine First question , are all accounts setup to use 'Use default server' in their Account Settings > Mail accou...

DNN only sending email to Domain email addresses
My DNN seems to be only sending email to email addresses within my domain name. i.e. support@mydomain.com etc... I've added the admin email account to my domain, my admin account uses this email account. Only bulk email to the domain name email addresses are getting email, only password reminders are being sent to domain name email addresses. I am using the Portal Store 6.4 and If I create a customer with a email address using my domain name this customer receives confirmation of his order. However if I create a customer with an email address such as someone@yahoo.com (using a rea...

error sending emails with a period in email address
I'm running Groupwise 7 and using Outlook 2003 as a conduit for another program. If I send an email with a period(john.doe@comcast.net) in it through outlook or the program, it errors out with: The message that you sent was undeliverable to the following: john.oe.@comcast.net (551 not our customer) Possibly truncated original message follows: Sending it through Groupwise is fine. Any ideas? Thanks. This is a known bug with the beta version of the connector, I don't know what version of the OLC you are using, but this has been fixed in the SP1 release. O...

Using Email Interface
Hi-- I recently set up a version of Bugzilla for my company (v 3.0.2) and I want to use the email interface so I can submit bugs via email. I know how to format an email in order to do this, but I don't know what email address to send it to. Where do I find this email address/how can I set it up? Thanks rmandal@gmail.com wrote: > Hi-- > > I recently set up a version of Bugzilla for my company (v 3.0.2) and I > want to use the email interface so I can submit bugs via email. I know > how to format an email in order to do this, but I don't know what &g...

Send 1 email to 60000 email addresses
I have received a request to take a list of email addresses (about 60000) and send a message to all of them. Will GroupWise even support this? I am on GroupWise 6.5.7 (6.5.6 with Security Updates). I do not have an API gateway installed. Any ideas? Sure. Will your INTERNET connection support this? "Rhonda Richardson" <rrichardson@kcumb.edu> wrote in message news:1xZNg.3068$lb5.1592@prv-forum2.provo.novell.com... >I have received a request to take a list of email addresses (about 60000) >and send a message to all of them. > > Will GroupWis...

Web resources about - Send email to each email address in database - asp.net.getting-started

Database - Wikipedia, the free encyclopedia
A database is an organized collection of data . The data are typically organized to model aspects of reality in a way that supports processes ...

Database - Wikipedia, the free encyclopedia
... requiring information. For example, modelling the availability of rooms in hotels in a way that supports finding a hotel with vacancies. Database ...

Social Side of Code, Database CI and REST API Testing in Methods & Tools Winter 2015 issue
... for software developers, testers and project managers – has published its Winter 2015 issue that discusses the social side of code, database ...

A look ahead at the state of the database in 2016
... identity management, anti-phishing education, and so forth. Ultimately, hackers want access to the contents of an enterprise's database. Security ...

Huge database of 191 million U.S. voters found on the open Internet
... such bulk information online, a recent discovery seems to indicate. According to VentureBeat , a security researcher found the exposed database ...

Top US School District Switches to Rimini Street for Oracle Database and Oracle E-Business Suite Support ...
Douglas County School District using savings from Rimini Street independent support to develop district-wide data visualization capabilities ...

IDG Contributor Network: Shrinking an already ginormous SharePoint database transaction log
Last month, I wrote about how to avoid having ginormous transaction logs within SharePoint databases. But what if it’s too late, and your files ...

Massive Voter Database Left Open For Public Consumption
Gosh, we could have avoided all the angst about the Clinton/Sanders voter database breach if only we'd known about this major database , accessible ...

18 million targeted voter records exposed by database error
A second database containing voter records has been exposed due to a configuration error. While the first held records that some dismissed inconsequential ...

Former Ohio cop uses cop database to stalk victim
... stalked her like an average person would, but stalked her in the way that only a police officer could: he stalked her utilizing a police database ...

Resources last updated: 1/22/2016 4:29:35 AM