summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRonny V. <ronny.vedrilla@ambient.digital>2024-09-11 18:04:43 +0200
committerNatalia <124304+nessita@users.noreply.github.com>2024-09-11 13:10:45 -0300
commitc12fe0a7243881aabe9ad6b04a447d0f7a496add (patch)
tree7390ec69314ef169bf39b069d948813e88df9b66
parent590f5e09f001736aa1fe3f7f086f8a5ab5e4bfdb (diff)
[5.1.x] Added example of email sending with additional capabilities to docs/topics/email.txt.
Co-authored-by: Mike Edmunds <medmunds@gmail.com> Backport of f4813211e2d8017b56b7447f56ad17df3fae9aa3 from main.
-rw-r--r--docs/topics/email.txt40
1 files changed, 37 insertions, 3 deletions
diff --git a/docs/topics/email.txt b/docs/topics/email.txt
index 212911002f..75a50f40a1 100644
--- a/docs/topics/email.txt
+++ b/docs/topics/email.txt
@@ -12,10 +12,11 @@ development, and to provide support for platforms that can't use SMTP.
The code lives in the ``django.core.mail`` module.
-Quick example
-=============
+Quick examples
+==============
-In two lines::
+Use :func:`send_mail` for straightforward email sending. For example, to send a
+plain text message::
from django.core.mail import send_mail
@@ -27,6 +28,39 @@ In two lines::
fail_silently=False,
)
+When additional email sending functionality is needed, use
+:class:`EmailMessage` or :class:`EmailMultiAlternatives`. For example, to send
+a multipart email that includes both HTML and plain text versions with a
+specific template and custom headers, you can use the following approach::
+
+ from django.core.mail import EmailMultiAlternatives
+ from django.template.loader import render_to_string
+
+ # First, render the plain text content.
+ text_content = render_to_string(
+ "templates/emails/my_email.txt",
+ context={"my_variable": 42},
+ )
+
+ # Secondly, render the HTML content.
+ html_content = render_to_string(
+ "templates/emails/my_email.html",
+ context={"my_variable": 42},
+ )
+
+ # Then, create a multipart email instance.
+ msg = EmailMultiAlternatives(
+ "Subject here",
+ text_content,
+ "from@example.com",
+ ["to@example.com"],
+ headers={"List-Unsubscribe": "<mailto:unsub@example.com>"},
+ )
+
+ # Lastly, attach the HTML content to the email instance and send.
+ msg.attach_alternative(html_content, "text/html")
+ msg.send()
+
Mail is sent using the SMTP host and port specified in the
:setting:`EMAIL_HOST` and :setting:`EMAIL_PORT` settings. The
:setting:`EMAIL_HOST_USER` and :setting:`EMAIL_HOST_PASSWORD` settings, if