Search code examples
djangodjango-email

Sending email notification in Django


I'm building a simple blog application. I have my blog up and running on development server. Now I wish to send mail to all the subscribers every time a new blog post is created by me/ admin. I know to use Django's sending_email library but I can't figure out how to automate the process, i.e, how to send the email using send_email() automatically every time I create another ' blog_post' object?

Note : I'm creating new 'blog_post'objects using Django's admin interface, so basically when I 'save' the object, I want to send the email.

I'm new to Django, any suggestion, guidance would be of great help

Code below : signals.py

@receiver(signals.post_save, sender=Post)
def send_post_mail(sender, instance, created, **kwargs):
    print('signal send')
    subject = "Thank you for registering with us"
    send_mail(subject, 'Body', '[email protected]', 
    ['[email protected]'], fail_silently=False,)

Models.py

class Post(models.Model):
STATUS_CHOICES = (
    ('draft', 'Draft'),
    ('published', 'Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, 
                        unique = True)
author = models.ForeignKey(User,
                           related_name='blog_posts', 
 on_delete=models.CASCADE)
audio = models.URLField(max_length = 200, default = 
"spotify:episode:0Vbl7RvX3KE0lSkRmy9Wjj") 
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)

apps.py

    from django.apps import AppConfig


   class BlogConfig(AppConfig):
         name = 'blog'


         def ready(self):
         import blog.signals

views.py

     def post_list(request):
        posts = Post.objects.order_by('-publish')
        return render(request, 'template.html', context = {'post':posts})

blog/urls.py

urlpatterns = [
#path('', views.Postlist, name='main-view'),
path('', views.get_name, name='main-form-view'),
path('<slug:slug>', views.detail_post, name='detail-post')

]

settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'seder's account password'
EMAIL_USE_TLS = False

init.py

default_app_config = 'blog.apps.BlogConfig'

Edit : It worked after configuring app.py and init.py as shown above.


Solution

    1. Create a file with name signals.py in same folder as your models.py.
    2. Add following imports to signals.py
    from django.dispatch import receiver
    from django.db.models import signals
    from .models import Blog_post
    
    1. Create a method and use your email library
    @receiver(signals.post_save, sender=Blog_post)
    def send_mail(sender, instance, created, **kwargs):
        # to test if the signal is working
        print('signal send')
        # replace it with your code once it works
    
    1. Add signals to apps.py in same folder as your models.py
    from django.apps import AppConfig
    
    
    class YourAppConfig(AppConfig):
        name = 'yourapp'
    
        # Add this to use signals
        def ready(self):
            from . import signals