How to create an Email queue mechanism in ASP.NET In case of network goes down? -
i developing website using asp.net. in there sending emails users.
currently using code send email asynchronously user. emails sending in background.
public static void sendemail(string path, string emailto) { thread emailthread = new thread(delegate() { try { string body = string.empty; using (streamreader reader = new streamreader(path)) { body = reader.readtoend(); } mailmessage mail = new mailmessage(); mail.from = new mailaddress("test@test.com"); mail.to.add(emailto); mail.subject = "test email"; mail.body += body; mail.isbodyhtml = true; smtpclient smtpclient = new smtpclient("smtp.test.com"); smtpclient.port = 587; smtpclient.deliverymethod = smtpdeliverymethod.network; smtpclient.usedefaultcredentials = false; smtpclient.credentials = new system.net.networkcredential("test@test.com", "test"); smtpclient.enablessl = true; smtpclient.sendcompleted += (s, e) => { smtpclient.dispose(); mail.dispose(); }; try { smtpclient.send(mail); } catch (exception ex) { /* exception handling code here */ } } catch (exception) { throw; } }); emailthread.isbackground = true; emailthread.start(); }
so above code working fine. 1 day got problem. when press send button @ same time internet connection down. email didn't fired. thats time realize email function need mechanism queue emails , send users 1 one according order in queue. if email got undelivered or if network gets down retry it. how achieve mechanism?
decouple queuing of emails sending them. e.g.:
- create database table outgoing emails, column sent date.
- whenever want send outgoing email, insert table null sent date.
- have background task run every x seconds check emails null sent date, try sending them, , update sent date if successful. hint: easy way queue recurring tasks in asp.net have @ this.
this stripped bone simple example, can expand on it.
Comments
Post a Comment