问题
When django sends an email, it takes from a few milli-seconds to a few seconds depending upon the smtp server. So the problem that i am facing is when django starts sending email it freezes there. The user would have to wait till the mail has been sent. I was wondering if i could simply return the html page and in the background the email could be sent without making the user wait for it.
skeleton is that right before the page is being rendered, email is being sent. So, I want to render the page first and then send the email in the background.
回答1:
I have done something like this in my project that uses threads:
class EmailThread(Thread):
def __init__(self, myemail):
self.myemail = myemail
Thread.__init__(self)
def run(self):
self.myemail.send()
class MyEmailMessage(EmailMessage):
def send_async(self, fail_silently=False):
thread = EmailThread(self)
thread.start()
# send email
email = MyEmailMessage(...)
email.send_async()
回答2:
There is also a nice project called django-mailer. It saves the mails in your database and you send them asynchronously via crontab or celery.
来源:https://stackoverflow.com/questions/35429708/dont-freeze-on-sending-mail-django