In Python has a built-in smtp mail transmission module, Django was simply encapsulated On this basis, we can make it easier and more flexible to send mail in Django environment.
All functions are django.core.mail in.
A simple example of the recording
1. Configuration
First obtain authorization code mailbox (Sina-mail, for example)
Then settings.py configuration
= EMAIL_BACKEND ' django.core.mail.backends.smtp.EmailBackend ' EMAIL_HOST = ' smtp.sina.com ' # middle "sina" read mail service you use EMAIL_PORT = 465 EMAIL_HOST_USER = ' email accounts ' EMAIL_HOST_PASSWORD = ' authorization code ' EMAIL_USE_SSL = True the DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
"" " EMAIL_USE_TLS EMAIL_USE_SSL and by default set to False, one needs to be configured is True, but not both set to True. Usually port 587 corresponding to TLS, port 465 corresponds to SSL (reinforcing TSL) "" "
2. Routing
from django.urls import path from email import views urlpatterns = [ path('admin/', admin.site.urls), path('send_email/', views.send_email) ]
3. view
from myemail Import Settings from the django.core.mail Import EmailMultiAlternatives # This may send HTML, if only send the text, can be introduced send_mail DEF SEND_EMAIL (Request): Subject = ' test message ' # message subject FROM_EMAIL = settings.EMAIL_HOST_USER # sender e-mail to = ' [email protected] ' # recipient's mailbox TEXT_CONTENT = ' If you see this message, explain your email server does not provide HTML linking feature ' # replace the contents of a mailbox if the target can not accept HTML html_content = "<a href='http://www.baidu.com'> search </a> " # HTML mail content msg = EmailMultiAlternatives (Subject, TEXT_CONTENT, FROM_EMAIL, [to]) msg.attach_alternative (html_content, ' text / html ' ) # to the mail binding html content mag.send () return HttpResponse ( ' message has been sent ' )