Debian Codegraph @

django/core/mail/backends/smtp.py

raw
1 """SMTP email backend class."""
2
3 import smtplib
4 import ssl
5 import threading
6
7 from django.conf import settings
8 from django.core.mail.backends.base import BaseEmailBackend
9 from django.core.mail.message import sanitize_address
10 from django.core.mail.utils import DNS_NAME
11 from django.utils.functional import cached_property
12
13
14 class EmailBackend(BaseEmailBackend):
15 """
16 A wrapper that manages the SMTP network connection.
17 """
18
19 def __init__(
20 self,
21 host=None,
22 port=None,
23 username=None,
24 password=None,
25 use_tls=None,
26 fail_silently=False,
27 use_ssl=None,
28 timeout=None,
29 ssl_keyfile=None,
30 ssl_certfile=None,
31 **kwargs,
32 ):
33 super().__init__(fail_silently=fail_silently)
34 self.host = host or settings.EMAIL_HOST
35 self.port = port or settings.EMAIL_PORT
36 self.username = settings.EMAIL_HOST_USER if username is None else username
37 self.password = settings.EMAIL_HOST_PASSWORD if password is None else password
38 self.use_tls = settings.EMAIL_USE_TLS if use_tls is None else use_tls
39 self.use_ssl = settings.EMAIL_USE_SSL if use_ssl is None else use_ssl
40 self.timeout = settings.EMAIL_TIMEOUT if timeout is None else timeout
41 self.ssl_keyfile = (
42 settings.EMAIL_SSL_KEYFILE if ssl_keyfile is None else ssl_keyfile
43 )
44 self.ssl_certfile = (
45 settings.EMAIL_SSL_CERTFILE if ssl_certfile is None else ssl_certfile
46 )
47 if self.use_ssl and self.use_tls:
48 raise ValueError(
49 "EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive, so only set "
50 "one of those settings to True."
51 )
52 self.connection = None
53 self._partial_connection = None
54 self._lock = threading.RLock()
55
56 @property
57 def connection_class(self):
58 return smtplib.SMTP_SSL if self.use_ssl else smtplib.SMTP
59
60 @cached_property
61 def ssl_context(self):
62 if self.ssl_certfile or self.ssl_keyfile:
63 ssl_context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT)
64 ssl_context.load_cert_chain(self.ssl_certfile, self.ssl_keyfile)
65 return ssl_context
66 else:
67 return ssl.create_default_context()
68
69 def open(self):
70 """
71 Ensure an open connection to the email server. Return whether or not a
72 new connection was required (True or False) or None if an exception
73 passed silently.
74 """
75 if self.connection:
76 # Nothing to do if the connection is already open.
77 return False
78
79 # If a connection was partially opened before, close it.
80 if self._partial_connection is not None:
81 self._close_connection(self._partial_connection)
82 self._partial_connection = None
83
84 # If local_hostname is not specified, socket.getfqdn() gets used.
85 # For performance, we use the cached FQDN for local_hostname.
86 connection_params = {"local_hostname": DNS_NAME.get_fqdn()}
87 if self.timeout is not None:
88 connection_params["timeout"] = self.timeout
89 if self.use_ssl:
90 connection_params["context"] = self.ssl_context
91 try:
92 self._partial_connection = self.connection_class(
93 self.host, self.port, **connection_params
94 )
95
96 # TLS/SSL are mutually exclusive, so only attempt TLS over
97 # non-secure connections.
98 if not self.use_ssl and self.use_tls:
99 self._partial_connection.starttls(context=self.ssl_context)
100 if self.username and self.password:
101 self._partial_connection.login(self.username, self.password)
102
103 # Don't set connection until it's fully configured.
104 self.connection = self._partial_connection
105 self._partial_connection = None
106
107 return True
108 except OSError:
109 if not self.fail_silently:
110 raise
111
112 def _close_connection(self, connection):
113 try:
114 connection.quit()
115 except (ssl.SSLError, smtplib.SMTPServerDisconnected):
116 # This happens when calling quit() on a TLS connection
117 # sometimes, or when the connection was already disconnected
118 # by the server.
119 connection.close()
120 except smtplib.SMTPException:
121 if self.fail_silently:
122 return
123 raise
124
125 def close(self):
126 """Close the connection to the email server."""
127 if self._partial_connection is not None:
128 try:
129 self._close_connection(self._partial_connection)
130 finally:
131 self._partial_connection = None
132 if self.connection is not None:
133 try:
134 self._close_connection(self.connection)
135 finally:
136 self.connection = None
137
138 def send_messages(self, email_messages):
139 """
140 Send one or more EmailMessage objects and return the number of email
141 messages sent.
142 """
143 if not email_messages:
144 return 0
145 with self._lock:
146 new_conn_created = self.open()
147 if not self.connection or new_conn_created is None:
148 # We failed silently on open().
149 # Trying to send would be pointless.
150 return 0
151 num_sent = 0
152 try:
153 for message in email_messages:
154 sent = self._send(message)
155 if sent:
156 num_sent += 1
157 finally:
158 if new_conn_created:
159 self.close()
160 return num_sent
161
162 def _send(self, email_message):
163 """A helper method that does the actual sending."""
164 if not email_message.recipients():
165 return False
166 encoding = email_message.encoding or settings.DEFAULT_CHARSET
167 from_email = sanitize_address(email_message.from_email, encoding)
168 recipients = [
169 sanitize_address(addr, encoding) for addr in email_message.recipients()
170 ]
171 message = email_message.message()
172 try:
173 self.connection.sendmail(
174 from_email, recipients, message.as_bytes(linesep="\r\n")
175 )
176 except smtplib.SMTPException:
177 if not self.fail_silently:
178 raise
179 return False
180 return True