Vivek
Vivek

Reputation: 1

how to implement automatically send email when MySQL column get updated (django+MySql)

I have models like Id, Name, email, Status. And created serializers and views.

I am updating the Status values by PUT method. How to implement an automatic email notification to smtp.example.com with the changed Status value.

Ex: Status column value is 'abc' I am updating value 'abc' to 'xyz' using PUT. I want an email should automatically send to particular email-id belongs to that row using primary key Id.

Django backend PUT method

    if request.method=='GET':
        employees = Employees.objects.all()
        employees_serializer=EmployeeSerializer(employees,many=True)
        return JsonResponse(employees_serializer.data,safe=False)
    elif request.method=='POST':
        employee_data=JSONParser().parse(request)
        employees_serializer=EmployeeSerializer(data=employee_data)
        if employees_serializer.is_valid():
            employees_serializer.save()

I want to implement 
```if(employee_data(after update !== employee_data(before update):
     sendmail()

can some one help here with some proper logic and code.

Upvotes: 0

Views: 251

Answers (1)

Rajat Jog
Rajat Jog

Reputation: 317

Say that you have send_email() function or thread implemented seperately as follows:

from django.core.mail import send_mail
def send_email(subject, message, sender, to):
   return send_mail(subject, message, sender, to)

Then in your PUT/UPDATE view function you can call this function as follows:

def update(self, request):
   ... # your operations here
   if (state changed):
     subject = ""
     message= "state: {state} [your message]" 
     send_mail(subject, message, sender, to=[user.email])
     return Response(200)

Upvotes: 1

Related Questions