I want to send email if user does something and because of his action some entry is made in the db. I want to do the send email function from my models.py. Is it possible??
CodePudding user response:
Yes, there are many ways you can send your mail when some action is performed in the database. You can use Django's signals post_save feature. Using signals, you can send emails to your user without any other editing in your code/view.
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.core.mail import EmailMessage
@receiver(pre_save, sender=MyModel) # here MyModel is name of your model
def send_email(sender, instance, **kwargs):
email = EmailMessage('your title', 'body', to=[email])
email.send()
# your code to send email
...
You also have to have your email setting in your settings.py file. I'm giving those here also.
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'Your email id'
EMAIL_HOST_PASSWORD = 'your password'
EMAIL_PORT = 587