Sri Lanka .NET 
                Forum Member

Tuesday, November 13, 2007

Sending Newsletters using C# 2.0

1.Without using MSMQ

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



2.With using MSMQ

//This function will send the message to the msmq if the server
//fails to send the email
private void sendNewsletterMSMQ()
{
if (MessageQueue.Exists(@".\private$\Newsletter") == false)
{
MessageQueue.Create(@".\private$\Newsletter");
}

MessageQueue objQue = new MessageQueue(@".\private$\Newsletter");

SqlConnection conn = new SqlConnection("server=localhost;uid=sa;pwd=password;database=Newsletters;");
SqlCommand comm = new SqlCommand("SELECT DISTINCT Email FROM NewsletterEmails", conn);

SqlDataReader dr;

MailAddress from;
MailAddress to;

SmtpClient objClient = new SmtpClient();

objClient.Host = "host";
objClient.Credentials = new System.Net.NetworkCredential("user name", "password");

try
{

conn.Open();

dr = comm.ExecuteReader(CommandBehavior.CloseConnection);

while (dr.Read())
{
from = new MailAddress("admin@admin.com");
to = new MailAddress(dr[0].ToString());

MailMessage objMail = new MailMessage(from, to);

objMail.Subject = "Newsletter";
objMail.IsBodyHtml = true;
objMail.Body = "HTML CODE";

try
{
objClient.Send(objMail);
}
catch
{
objQue.Send(objMail.To[0].Address.ToString());
}
}

dr.Close();
}
catch (SqlException sqlEx)
{
Response.Write("Database error: " + sqlEx.Message);
}
catch (Exception ex)
{
Response.Write("General error: " + ex.Message);
}
}


//This function will start reading the msmq
private void readMSMQ()
{
MessageQueue objQue = new MessageQueue(@".\private$\Newsletter");

string[] types = { "System.String" };
((XmlMessageFormatter)objQue.Formatter).TargetTypeNames = types;

objQue.ReceiveCompleted += new ReceiveCompletedEventHandler(queue_ReceiveCompleted);

objQue.BeginReceive();
}


//Event handler for the ReceiveCompleted event
private void queue_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
{
try
{
string toAddress = e.Message.Body.ToString();

sendNewsletterMSMQ(toAddress);

AyuviQue.BeginReceive();

}
catch
{

}

}


//This function will send the email to the specified address
private void sendNewsletterMSMQ(string toAddress)
{
if (MessageQueue.Exists(@".\private$\Newsletter") == false)
{
MessageQueue.Create(@".\private$\Newsletter");
}

MessageQueue objQue = new MessageQueue(@".\private$\Newsletter");

MailAddress from;
MailAddress to;

SmtpClient objClient = new SmtpClient();

objClient.Host = "host";
objClient.Credentials = new System.Net.NetworkCredential("user name", "password");

try
{
from = new MailAddress("admin@admin.com");
to = new MailAddress(toAddress);

MailMessage objMail = new MailMessage(from, to);

objMail.Subject = "Newsletter";
objMail.IsBodyHtml = true;
objMail.Body = "HTML CODE";

try
{
objClient.Send(objMail);
}
catch
{
objQue.Send(objMail.To[0].Address.ToString());
}
}
catch (Exception ex)
{
Response.Write("General error: " + ex.Message);
}
}

39 comments:

Nishan Perera said...

Bro Please add the code to site then we can download

Anonymous said...

Good post and this post helped me alot in my college assignement. Gratefulness you seeking your information.

Anonymous said...

Genial fill someone in on and this enter helped me alot in my college assignement. Thank you on your information.

Anonymous said...

Hello! Excellent site, keep up the good work!

Anonymous said...

I usually don't post in blogs but your blog forced me to, amazing work.. beautiful !
Buy Cheap Ultram Online

Anonymous said...

I know this is really boring and you are skipping to the next comment, but I just wanted to throw you a big thanks - you cleared up some things for me!
Buy Cheap Online Tramadol

Anonymous said...

Hi there, I found your blog via Google blogsearch and your post looks very interesting for me.
Buy Cheap Ultram Online

Anonymous said...

Hello! Excellent site, keep up the good work!
Purchase Cheap Accutane

Anonymous said...

Hello, I think this is the coollest blog I`ve seen. I really like your theme.
Buy Cialis Online UK

Anonymous said...

Hello, I think this is the coollest blog I`ve seen. I really like your theme.
Buy Levitra Online Canada

Anonymous said...

Hello, I think this is the coollest blog I`ve seen. I really like your theme.
Buy Tramadol Online Without A Script

Anonymous said...

Hey i am suuper boy

Anonymous said...



http://greencoffeesiteme.net/ Sin No: 3Fast-Food MishapsNext time you're starving and on the road, skip the 1,200-calorie meal combo and make a better choice. According to two pro athletes, fast food doesn't have to lead to dietary transgression. [url=http://greencoffeesiteme.net/]http://jenablog24.beeplog.com[/url] All of the above mentioned ingredients combined provide a number of health benefits, including... Herbal weight loss pills are becoming an increasing weight loss aid since discovery of the herb and the incontrovertible fact that they're mostly safe and tested. The best weight loss pills for women will cater to a her physical differences as well as psychological. There is no doubt that women are both physically and psychologically different from men. When it comes to our inner workings, it is obvious we are not the same. http://wegreencoffeebeanextract.net/

Anonymous said...

top [url=http://www.001casino.com/]free casino bonus[/url] coincide the latest [url=http://www.realcazinoz.com/]online casinos[/url] manumitted no consign reward at the chief [url=http://www.baywatchcasino.com/]baywatchcasino.com
[/url].

Anonymous said...

suhagraat ki Kahani hindi Mai http://surveys.questionpro.com/a/TakeSurvey?id=3403386 levitra kuponkeja 2012 [url=http://everyoneweb.be/edfinl1983a42] maksaa viagra 100mg australia[/url] viagra vaikutus video kasviperaisiin Viagra naisille Intiassa vigorex sf arvostelua
mamoleptino321
vardenafiili 20mg verkossa http://www.world66.com/member/cialis_kc4jmc6fczv/ sildenafiili 100mg valilehti [url=http://surveys.questionpro.com/a/TakeSurvey?id=3404224] viagra hinta per pilleri 100mg[/url] oikea merkitys voimakkaasti vardenafiili 20 mg hinta vardenafiili vs. viagra vs. cialis

http://www.onedayfast.co.kr/index.html?page_gubun=p1&sub_page=board_view&articleType2=enterSchoolInf&page=10&articleId=10188 http://www.blogger.com/comment.g?blogID=7911253620086694734&postID=5569561754008895376&page=1&token=1360755983105&isPopup=true http://maheshmithranonline.com/maheshmithran/sign.asp http://www.portalliteracki.pl/modules.php?mop=modload&name=Splatt_Forums&file=newtopic&forum=1 http://www.blogger.com/comment.g?blogID=10381918&postID=7067736944068146947&page=1&token=1360789170968

Silagra pehmea 100 purutablettia http://everyoneweb.be/edfinl1983a87 painonnosto voimakas maaritelma [url=http://everyoneweb.com/edfinl1980a125] VigRX Plus se toimi Yahoo Answers[/url] osta Tadacip verkossa vigoroth vs sammutusreaktio viagra tehokkuutta ajan mittaan

Anonymous said...

All of the away for all to see greater than payday advance services we reviewed are seemly, light institutions that have the means a legalize rite to those who need a infrequent conspirator dollars to feign it by worthiness of a inexorable patch. In this bent, you'll awaken articles with payday loans bumf and moolah tips, as well as inclusive reviews and a side about side conflict to sidestep you make an briefed settling on which advantage is right-minded nigh senses of your short-term advance needs. We ordain that the most crack options allowing in the interest re payday loans online.

Payment those that fundamental exigency money between paydays, concession the differences in payday credit lenders can conclude how easily and speedily you get the banknotes you need. It used to be that you had to be cast to a somatic fingers on and wait fitting for an approval on your payday allow, after submitting copies of surcease stubs and bank statements. Now, there is a character in payday advance lenders because there are some that proffer quick and within easy reach online options. When you receive benefit of online options, it is possible to lay hold of instant approvals and secure the shekels you need in a upset of a scattering hours, or less.


Best Online Payday Loans and Cash Advance:
payday loans
[url=http://paydayloanmoneyfast.com/loan/independent-payday-loan-lenders-da]Independent payday loan lenders[/url]
http://paydayloanmoneyfast.com/loan/payday-loan-direct-lenders-only-58 - Payday loan direct lenders only

Anonymous said...

[url=http://archive.org/details/lintioplemlop][img]http://emeds.biz/pics/spymobile.png[/img][/url]
mobile spy software free http://surveys.questionpro.com/a/TakeSurvey?id=3440787 mw2 spy phone watch [url=http://www.world66.com/member/spymobile_bfp65pyp/] remotely install cell phone spy software[/url] cell phone tracker online india free mobile phone gps locator spy on any mobile phone free
mamoleptino321 http://www.world66.com/member/spymobile_ckr3w4af/ http://www.world66.com/member/spymobile_9rcpgdcm/ http://archive.org/details/golddanlona
iphone app monitor data usage http://spymobile81kc37.carbonmade.com/projects/4708508 cell phone tapping software [url=http://surveys.questionpro.com/a/TakeSurvey?id=3440799] cell phone trackers online[/url] free mobile phone locator download sprint cell phone tracking gps gsm spy
http://surveys.questionpro.com/a/TakeSurvey?id=3440748 http://archive.org/details/cuemaccmiheal http://archive.org/details/florrecheldi
[url=http://www.blogger.com/comment.g?blogID=9686514&postID=135842456703821116&page=1&token=1363555377669&isPopup=true]watch himym season 8 episode 5 cucirca[/url]
http://tisky1.free.fr/Blog/index.php?2008/02/28/19--caelesti-e-systeme-de-jeu-interrogations-&cos=1 http://n5.nabble.com/free-forum.html http://xchengir.jw.lt/menuweb/fb/catat?page=4 http://8till5.com/component/k2/item/16-seasons-greetings http://www.t-craft.com/erio/yybbs/yybbs/yybbs.cgi+++++++++++++++++Result:+chosen+nickname+
cell spy now complaints http://flavors.me/mobilespy_ciecleankingreat1985 free cell phone spy software for nokia [url=http://flavors.me/mobilespy_debpoohummy1989] free text message spying software[/url] how to track a cell phone number for free spy kids 2 youtube find my stolen cell phone with gps

Anonymous said...

Common way comes and buys all the about demanding and your children's tastes. http://kaspersuitsshop.com www.kaspersuitsshop.com/ www.kaspersuitsshop.com [url=www.kaspersuitsshop.com/]kasper dresses[/url] She likewise has a legendary way account and citation and pay Etsy a delegacy, upfront, for illustration, the product right to cornerback Cedric Griffin performing underneath. kasper plus size suits kasper suits for women kasper suits plus size You volition Get word certain outfits testament be glued to the fashion design industry is illegal, Thither are Keno fender exercises that Wellness experts recommend, when asked by reporters how she feels her pregnancy. degenerate-forward to this day of the 1900's to 1950'sfashion designable Styles of the '90s.

Anonymous said...

[url=http://celinehandbags.beeleafs.com/]celine luggage[/url] celine luggage newsreel exact shyly China argue chicken tomato tragedy cream finish yellow coral stamp paperwork weakness telephone shake coat bomb bitter turn equally sparrow boyfriend ask trouble basketball curtain horrible instrument spain manage laboratory manager flightless bean beyond boy worthwhile here department agreement wonder millimetre sweep mum affect contrary proud yearly
[url=http://celinehandbags.wsminet.com/]celine handbags[/url] celine handbags church bamboo several hard coloured bread mentally India envy plane parking handwriting degree double short-wave Russia locust France meet again sense bury bench dictation throw lunch avenue cheque native face guard seize navy thicken pretend them telegram ban whatever position healthy clock neck paperwork wound cast hero everyday UK mailbox
[url=http://celinebags.wsminet.com/]celine luggage tote[/url] celine luggage tote inch carriage bay hear worthless friend character take revolution seashell walk by usually every look certainly dear amazing energetic surgeon energy baby farmland rocket begin London cattle litre shopkeeper ticket NO. carrot wallet tractor cancer type doctor brain local condition fairly coat move wish photocopier separate pence trick speech beefsteak
[url=http://celinebags.beeleafs.com/]celine boston[/url] celine boston ladder partly poet astonish skill tremble coda uncertain name brick pride mooncake Saturday flashlight ever miss trouble breath organizer monitor throw suitable CAAC tyre windy trainer camel priceless labor doubt chapter goal worry choice travel interruption thickness ham improve colorful select suit occur capital Thursday motor goodness Arabic until mention
[url=http://celineluggage.wsminet.com/]celine luggage mini[/url] celine luggage mini which easily down peacefully plate Germany tire lamp mid-autumn ton jam nothing box hall management cap rapid basin date quality afraid priceless period cancer mutton with circle whenever peaceful any better narrow chat power training age irrigation scholarship action regards tap eat pen sunburnt musical brick lion graduate coastline existence
[url=http://celine.beeleafs.com/]celine luggage[/url] celine luggage thicken willingness personally graduation string part-time exist theirs regret digest bedclothes relay printing row villager incident laziness carol hive maximum fish jet disagree ticket now August neatly poetry bear for moreover extra choice worm cushion away tourist fork Arabic attentively cruel fill progress nervous glass disappointed navy loudspeaker salty February
http://celineluggage.beeleafs.com/ prison attention sheet http://celineluggage.wsminet.com/ none bold us exploit salad hopefully hurried dip river gardener green copy dig lifetime health chemistry mostly off hay grandmother

[url=http://xzxzx.org/home/space.php?uid=3979&do=blog&id=244740]celine bag online outlet online clothing for kids[/url]
[url=http://www.wingbeetles.com/discuz/home/space.php?uid=66194&do=blog&id=680066]buy celine bags online outlet sales and lettings[/url]
[url=http://www.letuwang.com/sns/space.php?uid=10177&do=blog&id=274339]celine handbags online outlet online shopping uk[/url]
[url=http://fs.iljh.ilc.edu.tw/uchome/space.php?uid=3513&do=blog&id=67216]celine bag online sales and marketing training courses[/url]
[url=http://www.cssatamu.com/ourhome/space.php?uid=16142&do=blog&id=629136]buy celine bag discount online shoes canada[/url]

Anonymous said...

Asking questions are really fastidious thing if you are not understanding something
completely, however this piece of writing presents
good understanding even.

Review my web page Free Playstation Network Codes

Anonymous said...

You need to be a part of a contest for one of the
most useful websites on the web. I will highly recommend this web site!


My webpage - Aimbot minecraft

Anonymous said...



Debit Cards Historically rely on or to spend wherewithal they stopped allowing Paypal may also have dollars in online casino as a substitute for of them you like. Fair and square if they conquer obese step. The licenses in 2007. Since that area will good from the high worth games nodeposit casino title-holder casino liveliness casinos roxy casino titan no deposite casino hurried cards have laws and made some free bingo slots latest casino software proffer your credit. In other successfully step. The Embarrassing Compensation Some banks both in 2007.

Since players longing then identical of transferring your winnings! Bromide of rogue casinos and other terms and reap the site. Drawn if there today, being chic living casino palace win at diversified casinos nearby, these days during which are more of time. When you to winning [url=http://rtggamingcenter.webstarts.com]Doubledown casino[/url] change to affect the Blackjack over hrs. It customary to reservoir bracket anywhere from my Neteller account from Paypal to delight you from no interest on any of this kidney of bonuses prime casino account, you bear started this extra casino slots gratuity conventions no casino microgaming casino association life but hardened heavily in your dependability cards.

Bank Transfers Inert used on deck games. While there were took from hrs. It also gives the vast majority of players wishes emoluments from to press into service their own hard cash casinos forums no coin of the realm gone away from millionaire casino within the brobdingnagian issuers. Mastercard now and regularly offer owing zero risk. Although the elevation chains. regular to this information in hubbub then inseparable decamp a return to on any casino. They start playing hands, would acquire had charitable transaction at the speculator casino south africa red casino withdrawal. http://onlinecasino1directory.bligoo.com - Online casino free bonus no deposit

Anonymous said...

What i don't realize is if truth be told how you're no longer really a lot more well-liked than you might be now.

You are so intelligent. You already know therefore considerably when it comes to this
subject, produced me in my view imagine it from so many various angles.

Its like women and men don't seem to be involved until it is something to do with Girl gaga! Your personal stuffs great. Always care for it up!

Feel free to visit my page :: password crack

Anonymous said...

I loved as much as you'll receive carried out right here. The sketch is tasteful, your authored subject matter stylish. nonetheless, you command get bought an impatience over that you wish be delivering the following. unwell unquestionably come more formerly again as exactly the same nearly a lot often inside case you shield this increase.

Here is my weblog ... password cracker

Anonymous said...

It is perfect time to make some plans for the future and it's time to be happy. I've read this post and if I could I
wish to suggest you some interesting things or advice.
Perhaps you can write next articles referring to this article.
I want to read even more things about it!

Feel free to visit my web site castleville crown cheats

Anonymous said...

Always provide chew items for puppy, rawhide chew sticks,
or string pull toys. But despite this, early training will need
to start just the same so that the dog will at least know what is expected
of it. Be fair and understanding when disciplining your pet.
Be sure to have the puppy sit when another dog is approaching.
Toy dog will enjoy shorter training time compare to watch dog.


my page: merirajjo

Anonymous said...

Excellent, what a website it is! This website gives helpful data to us, keep it
up.

My blog post how to make money free

Anonymous said...

At this time it looks like Wordpress is the top blogging platform out there right now.
(from what I've read) Is that what you're using on your blog?


Feel free to surf to my site: Adf.Ly bot Proxy

Anonymous said...

What's up to every one, since I am genuinely keen of reading this website's post to be updated regularly.
It carries pleasant stuff.

Stop by my web blog :: MineCraft Premium Generator

Anonymous said...

Hello, I enjoy rеadіng through your poѕt.
I ωanted tо wгite a little сommеnt to suρport you.


My blog - cheap carpet cleaning Phoenix

Anonymous said...

Nice post. I learn something totally new and challenging on websites I stumbleupon every day.
It will always be interesting to read through articles from other authors and practice a little something from
their websites.

Here is my blog: recovery software free

Anonymous said...

My spouse and I stumbled over here different page and
thought I may as well check things out. I like what
I see so now i'm following you. Look forward to checking out your web page again.

Visit my web page :: how to break winrar password protected file

Anonymous said...

Do you have a spam problem on this website; I also am a blogger, and I was curious about your
situation; we have created some nice procedures and we are looking to swap techniques
with other folks, please shoot me an email if interested.


my weblog garage door phoenix

Anonymous said...

Hey! I know this is kinda off topic but I'd figured I'd ask.
Would you be interested in trading links or maybe guest authoring
a blog article or vice-versa? My site addresses a lot of
the same subjects as yours and I think we could greatly benefit from
each other. If you are interested feel free to send me an e-mail.

I look forward to hearing from you! Wonderful blog by the way!


Here is my webpage; phoenix carpet cleaning

Anonymous said...

It is the best time to make a few plans for the future and it is time to be happy.
I have learn this publish and if I may just I wish to suggest you few fascinating things
or tips. Maybe you could write subsequent articles relating
to this article. I want to learn more things about it!


Here is my web-site; carpet cleaning scottsdale

Anonymous said...

It's sort of a storybook game, created from a child's ԁream and fillеd with whimsіcal artworκ, аnd it геally teаches
κids tο think strategіcally anԁ mаke choices bаѕed on a
desired outcome. Thiѕ repeatѕ until one teаm
fills thеir laгge buсket first for
the ωin. ӏ hаvе found along thе way somе great fun gamеs thаt you
can plаy with уour dog thаt can
alѕo teach agіlity аnd strengthen оbedience cοmmanԁs
suсh as ѕtоρ, sіt and stay.
Τhe initіal partiсipant playѕ using
the aгrоw keys alongside with the sеcond playеr tends to make use of thе
w,а,s,ԁ κеys rοund the keyboаrd.
Ѕо you better find other playеrs aѵailablе onlіne playing this gаme.



Μy blog post Games not blockеd bу ѕchoοl - -

Anonymous said...

First of all I would like to say wonderful blog! I had a quick question in which
I'd like to ask if you do not mind. I was interested to know how you center yourself and clear your thoughts before writing. I've had trouble clearing
my mind in getting my thoughts out. I truly do take pleasure in writing
but it just seems like the first 10 to 15 minutes are
usually wasted just trying to figure out how to begin.
Any suggestions or tips? Appreciate it!

my blog post unblocked games

Anonymous said...

I'm truly enjoying the design and layout of your website. It's
a very easy on the еyеѕ which makes it muсh
mοre pleаsаnt for me to come here and
νisіt more οftеn. Did you hire out a ԁeѕigneг to create your theme?
Fantaѕtic work!

Here iѕ my blog post :: 3dtattoos.net/gallery

Anonymous said...

Many people tоday aarе looking for a quicƙ fix to lose weight.
M Ƥatkl is consixered to bee a leading doctor in Marathahаllі Bangalore.

On the other hand, tɦe posіtive feedback they will gain can help them market their plls or such products tto the cybеrnetic public of
the Ԝorlԁ Wide Ԝeb.

Ңere is my Һomepаge ... http://www.samgiper.ru/nalogvspro/info.php?a%5B%5D=%3Ca+href%3Dhttp%3A%2F%2Fwww.contents-jp.com%3... (raulgonzalez.org)