0

I am using Django's EmailMessage class for sending auto mail, from a view. However the website literally stops showing the next render page (which is on a modal), until the Email has been sent. If I remove Email sending stuff then the website is very fast and works properly. Please guide as to how to send mail also while not forcing the user to wait for the mail sending process. My partial view codes are below for reference:

email =EmailMessage(
                'Message received',
                'You received a message....',
                settings.DEFAULT_FROM_EMAIL,
                [request.user.email],
                reply_to=['noreply@example.com'])
email.content_subtype = "html"
email.send(fail_silently=True)

return JsonResponse({"instance": rendered,"valid":True}, status=200)

Edit: Update:

I have also tried the async_to_sync function to call the email.send method as suggested in the docs. However the main flow still waits for the mail sending process.

Jayesh
  • 1,511
  • 1
  • 16
  • 37

2 Answers2

1

I have used threading and it works fine. I have edited the answer here. I am adding the code with additional parameter here as well for reference.

import threading
from threading import Thread

class EmailThread(threading.Thread):
    def __init__(self, subject, html_content, recipient_list, replyto):
        self.subject = subject
        self.recipient_list = recipient_list
        self.html_content = html_content
        self.reply_to = replyto
        threading.Thread.__init__(self)

    def run (self):
        msg = EmailMessage(self.subject, self.html_content, settings.EMAIL_HOST_USER, self.recipient_list, reply_to=self.reply_to)
        msg.content_subtype = "html"
        msg.send(fail_silently=True)

def send_html_mail(subject, html_content, recipient_list, replyto):
    EmailThread(subject, html_content, recipient_list, replyto).start()
Jayesh
  • 1,511
  • 1
  • 16
  • 37
0

so i implement the same today, only with another method. My Tool is still fast, so maybe this can help u.

def sendMail():

   subject = "Automate Info"
   message = "Hello"
   email_from = settings.EMAIL_HOST_USER

   send_mail(
        subject,
        message,
        email_from,
        recipient_list
    )

return

settings.py:

EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_USE_TLS = True
EMAIL_PORT = 25
EMAIL_HOST_USER = "yourEmail@example.com"
EMAIL_HOST_PASSWORD = "yourpassword"
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False

U can also work with a Email .html Template, there are a few ways to do this. If u want this, i can search for this and add this to the Post. I looked at this stuff today so i could find it fast. Anyway, this works fine for me and its pretty fast.

sheep64
  • 94
  • 1
  • 4