summaryrefslogtreecommitdiff
path: root/django/core/mail/__init__.py
blob: 4422f708b8bdc5822540a5594fae5d7315a9d112 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
"""
Tools for sending email.
"""

import warnings

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.mail.exceptions import InvalidMailer, MailerDoesNotExist
from django.core.mail.handler import DEFAULT_MAILER_ALIAS, MailersHandler

# Imported for backwards compatibility and for the sake
# of a cleaner namespace. These symbols used to be in
# django/core/mail.py before the introduction of email
# backends and the subsequent reorganization (See #10355)
from django.core.mail.message import (
    DEFAULT_ATTACHMENT_MIME_TYPE,
    EmailAlternative,
    EmailAttachment,
    EmailMessage,
    EmailMultiAlternatives,
    forbid_multi_line_headers,
    make_msgid,
)
from django.core.mail.utils import DNS_NAME, CachedDnsName
from django.utils.deprecation import (
    RemovedInDjango70Warning,
    deprecate_posargs,
    warn_about_external_use,
)
from django.utils.functional import Promise
from django.utils.module_loading import import_string

from .deprecation import (
    AUTH_ARGS_WARNING,
    CONNECTION_ARG_WARNING,
    FAIL_SILENTLY_ARG_WARNING,
    report_using_incompatibility,
    warn_about_default_mailers_if_needed,
)

__all__ = [
    "InvalidMailer",
    "MailerDoesNotExist",
    "CachedDnsName",
    "DNS_NAME",
    "EmailMessage",
    "EmailMultiAlternatives",
    "DEFAULT_ATTACHMENT_MIME_TYPE",
    "make_msgid",
    "mailers",
    "get_connection",
    "send_mail",
    "send_mass_mail",
    "mail_admins",
    "mail_managers",
    "EmailAlternative",
    "EmailAttachment",
    # RemovedInDjango70Warning: When the deprecation ends, remove the last
    # entries.
    "BadHeaderError",
    "SafeMIMEText",
    "SafeMIMEMultipart",
    "forbid_multi_line_headers",
]


mailers = MailersHandler()


# RemovedInDjango70Warning.
@deprecate_posargs(RemovedInDjango70Warning, ["fail_silently"])
def get_connection(backend=None, *, fail_silently=False, **kwds):
    """Load an email backend and return an instance of it.

    If backend is None (default), use settings.EMAIL_BACKEND.

    Both fail_silently and other keyword arguments are used in the
    constructor of the backend.
    """
    msg = (
        "get_connection() is deprecated. See 'Migrating email to mailers' "
        "in Django's documentation for recommended replacements."
    )
    warn_about_external_use(msg, RemovedInDjango70Warning, skip_frames=1)
    warn_about_default_mailers_if_needed()

    if fail_silently:
        kwds["fail_silently"] = fail_silently

    if mailers._is_configured:
        # Support get_connection(**kwargs) from MAILERS["default"].
        if backend is not None:
            raise RuntimeError(
                "get_connection(backend, ...) is not supported with MAILERS."
            )
        return mailers.create_connection(DEFAULT_MAILER_ALIAS, _deprecated_kwargs=kwds)

    klass = import_string(backend or settings.EMAIL_BACKEND)
    return klass(**kwds)


@deprecate_posargs(
    RemovedInDjango70Warning,
    [
        "fail_silently",
        "auth_user",
        "auth_password",
        "connection",
        "html_message",
    ],
)
def send_mail(
    subject,
    message,
    from_email,
    recipient_list,
    *,
    fail_silently=False,
    auth_user=None,
    auth_password=None,
    connection=None,
    html_message=None,
    using=None,
):
    """
    Easy wrapper for sending a single message to a recipient list. All members
    of the recipient list will see the other recipients in the 'To' field.

    If from_email is None, use the DEFAULT_FROM_EMAIL setting.

    Note: The API for this method is frozen. New code wanting to extend the
    functionality should use the EmailMessage class directly.
    """
    # RemovedInDjango70Warning: change entire implementation to:
    #   email = EmailMultiAlternatives(
    #       subject, message, from_email, recipient_list
    #   )
    #   if html_message:
    #       email.attach_alternative(html_message, "text/html")
    #   return email.send(using=using)
    if fail_silently:
        warn_about_external_use(
            FAIL_SILENTLY_ARG_WARNING, RemovedInDjango70Warning, skip_frames=1
        )
    if auth_user is not None or auth_password is not None:
        warn_about_external_use(
            AUTH_ARGS_WARNING, RemovedInDjango70Warning, skip_frames=1
        )
    if connection is not None:
        warn_about_external_use(
            CONNECTION_ARG_WARNING, RemovedInDjango70Warning, skip_frames=1
        )

    if using is not None:
        report_using_incompatibility(
            connection, fail_silently, auth_user, auth_password
        )
    elif connection is None:
        options = {"fail_silently": fail_silently}
        if auth_user is not None:
            options["username"] = auth_user
        if auth_password is not None:
            options["password"] = auth_password
        connection = get_connection(**options)
    else:
        if fail_silently:
            raise TypeError(
                "fail_silently cannot be used with a connection. "
                "Pass fail_silently to get_connection() instead."
            )
        if auth_user is not None or auth_password is not None:
            raise TypeError(
                "auth_user and auth_password cannot be used with a connection. "
                "Pass auth_user and auth_password to get_connection() instead."
            )
    mail = EmailMultiAlternatives(
        subject, message, from_email, recipient_list, connection=connection
    )
    if html_message:
        mail.attach_alternative(html_message, "text/html")

    return mail.send(using=using)


@deprecate_posargs(
    RemovedInDjango70Warning,
    [
        "fail_silently",
        "auth_user",
        "auth_password",
        "connection",
    ],
)
def send_mass_mail(
    datatuple,
    *,
    fail_silently=False,
    auth_user=None,
    auth_password=None,
    connection=None,
    using=None,
):
    """
    Given a datatuple of (subject, message, from_email, recipient_list), send
    each message to each recipient list. Return the number of emails sent.

    If from_email is None, use the DEFAULT_FROM_EMAIL setting.

    Note: The API for this method is frozen. New code wanting to extend the
    functionality should use the EmailMessage class directly.
    """
    # RemovedInDjango70Warning: change entire implementation to:
    #   messages = [...]
    #   mailer = mailers.default if using is None else mailers[using]
    #   return mailer.send_messages(messages)
    if fail_silently:
        warn_about_external_use(
            FAIL_SILENTLY_ARG_WARNING, RemovedInDjango70Warning, skip_frames=1
        )
    if auth_user is not None or auth_password is not None:
        warn_about_external_use(
            AUTH_ARGS_WARNING, RemovedInDjango70Warning, skip_frames=1
        )
    if connection is not None:
        warn_about_external_use(
            CONNECTION_ARG_WARNING, RemovedInDjango70Warning, skip_frames=1
        )

    if using is not None:
        report_using_incompatibility(
            connection, fail_silently, auth_user, auth_password
        )
        connection = mailers[using]
    elif connection is None:
        options = {"fail_silently": fail_silently}
        if auth_user is not None:
            options["username"] = auth_user
        if auth_password is not None:
            options["password"] = auth_password
        connection = get_connection(**options)
    else:
        if fail_silently:
            raise TypeError(
                "fail_silently cannot be used with a connection. "
                "Pass fail_silently to get_connection() instead."
            )
        if auth_user is not None or auth_password is not None:
            raise TypeError(
                "auth_user and auth_password cannot be used with a connection. "
                "Pass auth_user and auth_password to get_connection() instead."
            )
    messages = [
        EmailMessage(subject, message, sender, recipient, connection=connection)
        for subject, message, sender, recipient in datatuple
    ]
    return connection.send_messages(messages)


# RemovedInDjango70Warning: fail_silently and connection args.
def _send_server_message(
    *,
    setting_name,
    subject,
    message,
    html_message=None,
    fail_silently=False,
    connection=None,
    using=None,
):
    # RemovedInDjango70Warning: everything before `recipients = getattr(...)`.
    # skip_frames=2: this helper's caller + its @deprecate_posargs decorator.
    if fail_silently:
        warn_about_external_use(
            FAIL_SILENTLY_ARG_WARNING, RemovedInDjango70Warning, skip_frames=2
        )
    if connection is not None:
        warn_about_external_use(
            CONNECTION_ARG_WARNING, RemovedInDjango70Warning, skip_frames=2
        )

    if using is not None:
        report_using_incompatibility(connection, fail_silently)
    elif connection is not None and fail_silently:
        raise TypeError(
            "fail_silently cannot be used with a connection. "
            "Pass fail_silently to get_connection() instead."
        )
    # ... end of RemovedInDjango70Warning.

    recipients = getattr(settings, setting_name)
    if not recipients:
        return

    # RemovedInDjango70Warning.
    if all(isinstance(a, (list, tuple)) and len(a) == 2 for a in recipients):
        warnings.warn(
            f"Using (name, address) pairs in the {setting_name} setting is deprecated."
            " Replace with a list of email address strings.",
            RemovedInDjango70Warning,
            stacklevel=2,
        )
        recipients = [a[1] for a in recipients]

    if not isinstance(recipients, (list, tuple)) or not all(
        isinstance(address, (str, Promise)) for address in recipients
    ):
        raise ImproperlyConfigured(
            f"The {setting_name} setting must be a list of email address strings."
        )

    mail = EmailMultiAlternatives(
        subject="%s%s" % (settings.EMAIL_SUBJECT_PREFIX, subject),
        body=message,
        from_email=settings.SERVER_EMAIL,
        to=recipients,
        connection=connection,
    )
    if html_message:
        mail.attach_alternative(html_message, "text/html")
    mail.send(using=using, fail_silently=fail_silently)


# RemovedInDjango70Warning: fail_silently and connection args.
@deprecate_posargs(
    RemovedInDjango70Warning, ["fail_silently", "connection", "html_message"]
)
def mail_admins(
    subject,
    message,
    *,
    fail_silently=False,
    connection=None,
    html_message=None,
    using=None,
):
    """Send a message to the admins, as defined by the ADMINS setting."""
    _send_server_message(
        setting_name="ADMINS",
        subject=subject,
        message=message,
        html_message=html_message,
        fail_silently=fail_silently,
        connection=connection,
        using=using,
    )


# RemovedInDjango70Warning: fail_silently and connection args.
@deprecate_posargs(
    RemovedInDjango70Warning, ["fail_silently", "connection", "html_message"]
)
def mail_managers(
    subject,
    message,
    *,
    fail_silently=False,
    connection=None,
    html_message=None,
    using=None,
):
    """Send a message to the managers, as defined by the MANAGERS setting."""
    _send_server_message(
        setting_name="MANAGERS",
        subject=subject,
        message=message,
        html_message=html_message,
        fail_silently=fail_silently,
        connection=connection,
        using=using,
    )


# RemovedInDjango70Warning.
_deprecate_on_import = {
    "BadHeaderError": "BadHeaderError is deprecated. Replace with ValueError.",
    "SafeMIMEText": (
        "SafeMIMEText is deprecated. The return value"
        " of EmailMessage.message() is an email.message.EmailMessage."
    ),
    "SafeMIMEMultipart": (
        "SafeMIMEMultipart is deprecated. The return value"
        " of EmailMessage.message() is an email.message.EmailMessage."
    ),
}


# RemovedInDjango70Warning.
def __getattr__(name):
    try:
        msg = _deprecate_on_import[name]
    except KeyError:
        raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from None
    else:
        # Issue deprecation warnings at time of import.
        from django.core.mail import message

        warnings.warn(msg, category=RemovedInDjango70Warning)
        return getattr(message, name)