Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send email and roll back changes?

Tags:

c#

.net

I am creating a complaint registration form for user in asp.net MVC. The complaint is send to user email address and complaint is save into SQL server 2017 database. I need a suggestion. my question is, How do I handle email and database?

condition 1 - what if database fails to save data but email is sending.
condition 2 - what if database save data to table but fails to send email.

How I did,

public void MyFunction()
{
    try {
       var db = DbContext();
       //some code
       //The number of state entries written to database
       int entities = db.SaveChanges();
       if (entities > 0)
       {
          SendEmail();//what fails to send email and complaint is created. 
       }
    }
    catch(Exception ex)
    {
        //exception is handle
    }
}

When db.SaveChanges() is done, it return how many tables are written to database. From my homework, Second condition is most important.

The Result I want is, both process of creation and sending email is handle smoothly.

Is I am on right path or not?

Any suggestion is appreciated.

like image 440
no name Avatar asked Oct 14 '25 04:10

no name


1 Answers

What I would do in this case is have the emails saved to a table in the database, and implement a service that reads from that table and sends any unsent emails with a retry count for each entry.

That way you can retry sending the email at any time if it fails.

like image 121
Armand Avatar answered Oct 16 '25 17:10

Armand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!