|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +__all__ = ['AsyncSMTPClientWithResponse'] |
| 4 | + |
| 5 | +import logging |
| 6 | +from typing import TYPE_CHECKING |
| 7 | + |
| 8 | +import aiosmtplib |
| 9 | + |
| 10 | +from ..response import SMTPResponse |
| 11 | +from ...utils import sanitize_email |
| 12 | + |
| 13 | +if TYPE_CHECKING: |
| 14 | + from .aio_backend import AsyncSMTPBackend |
| 15 | + |
| 16 | +logger = logging.getLogger(__name__) |
| 17 | + |
| 18 | + |
| 19 | +class AsyncSMTPClientWithResponse: |
| 20 | + """Async SMTP client built on aiosmtplib that returns SMTPResponse objects.""" |
| 21 | + |
| 22 | + def __init__(self, parent: AsyncSMTPBackend, **kwargs): |
| 23 | + self.parent = parent |
| 24 | + self.make_response = parent.make_response |
| 25 | + |
| 26 | + self.tls = kwargs.pop('tls', False) |
| 27 | + self.ssl = kwargs.pop('ssl', False) |
| 28 | + self.debug = kwargs.pop('debug', 0) |
| 29 | + self.user = kwargs.pop('user', None) |
| 30 | + self.password = kwargs.pop('password', None) |
| 31 | + |
| 32 | + # aiosmtplib uses use_tls for implicit TLS (SMTPS) and |
| 33 | + # start_tls for STARTTLS after connect |
| 34 | + smtp_kwargs = dict(kwargs) |
| 35 | + smtp_kwargs['use_tls'] = self.ssl |
| 36 | + smtp_kwargs['start_tls'] = self.tls |
| 37 | + |
| 38 | + # aiosmtplib uses 'hostname' instead of 'host' |
| 39 | + if 'host' in smtp_kwargs: |
| 40 | + smtp_kwargs['hostname'] = smtp_kwargs.pop('host') |
| 41 | + |
| 42 | + self._smtp = aiosmtplib.SMTP(**smtp_kwargs) |
| 43 | + |
| 44 | + async def initialize(self): |
| 45 | + await self._smtp.connect() |
| 46 | + try: |
| 47 | + if self._smtp.is_ehlo_or_helo_needed: |
| 48 | + await self._smtp.ehlo() |
| 49 | + if self.user: |
| 50 | + await self._smtp.login(self.user, self.password) |
| 51 | + except Exception: |
| 52 | + await self.quit() |
| 53 | + raise |
| 54 | + |
| 55 | + async def quit(self): |
| 56 | + """Closes the connection to the email server.""" |
| 57 | + try: |
| 58 | + await self._smtp.quit() |
| 59 | + except (aiosmtplib.SMTPServerDisconnected, ConnectionError): |
| 60 | + self._smtp.close() |
| 61 | + |
| 62 | + async def _rset(self): |
| 63 | + try: |
| 64 | + await self._smtp.rset() |
| 65 | + except (aiosmtplib.SMTPServerDisconnected, ConnectionError): |
| 66 | + pass |
| 67 | + |
| 68 | + async def sendmail(self, from_addr: str, to_addrs: list[str] | str, |
| 69 | + msg: bytes, mail_options: list[str] | None = None, |
| 70 | + rcpt_options: list[str] | None = None) -> SMTPResponse | None: |
| 71 | + |
| 72 | + if not to_addrs: |
| 73 | + return None |
| 74 | + |
| 75 | + rcpt_options = rcpt_options or [] |
| 76 | + mail_options = mail_options or [] |
| 77 | + esmtp_opts = [] |
| 78 | + if self._smtp.supports_esmtp: |
| 79 | + if self._smtp.supports_extension('size'): |
| 80 | + esmtp_opts.append("size=%d" % len(msg)) |
| 81 | + for option in mail_options: |
| 82 | + esmtp_opts.append(option) |
| 83 | + |
| 84 | + response = self.make_response() |
| 85 | + |
| 86 | + from_addr = sanitize_email(from_addr) |
| 87 | + |
| 88 | + response.from_addr = from_addr |
| 89 | + response.esmtp_opts = esmtp_opts[:] |
| 90 | + |
| 91 | + try: |
| 92 | + resp = await self._smtp.mail(from_addr, options=esmtp_opts) |
| 93 | + except aiosmtplib.SMTPSenderRefused as exc: |
| 94 | + response.set_status('mail', exc.code, exc.message.encode() if isinstance(exc.message, str) else exc.message) |
| 95 | + response.set_exception(exc) |
| 96 | + await self._rset() |
| 97 | + return response |
| 98 | + |
| 99 | + response.set_status('mail', resp.code, resp.message.encode() if isinstance(resp.message, str) else resp.message) |
| 100 | + |
| 101 | + if resp.code != 250: |
| 102 | + await self._rset() |
| 103 | + response.set_exception( |
| 104 | + aiosmtplib.SMTPSenderRefused(resp.code, resp.message, from_addr)) |
| 105 | + return response |
| 106 | + |
| 107 | + if not isinstance(to_addrs, (list, tuple)): |
| 108 | + to_addrs = [to_addrs] |
| 109 | + |
| 110 | + to_addrs = [sanitize_email(e) for e in to_addrs] |
| 111 | + |
| 112 | + response.to_addrs = to_addrs |
| 113 | + response.rcpt_options = rcpt_options[:] |
| 114 | + response.refused_recipients = {} |
| 115 | + |
| 116 | + for a in to_addrs: |
| 117 | + try: |
| 118 | + resp = await self._smtp.rcpt(a, options=rcpt_options) |
| 119 | + code = resp.code |
| 120 | + resp_msg = resp.message.encode() if isinstance(resp.message, str) else resp.message |
| 121 | + except aiosmtplib.SMTPRecipientRefused as exc: |
| 122 | + code = exc.code |
| 123 | + resp_msg = exc.message.encode() if isinstance(exc.message, str) else exc.message |
| 124 | + |
| 125 | + response.set_status('rcpt', code, resp_msg, recipient=a) |
| 126 | + if (code != 250) and (code != 251): |
| 127 | + response.refused_recipients[a] = (code, resp_msg) |
| 128 | + |
| 129 | + if len(response.refused_recipients) == len(to_addrs): |
| 130 | + await self._rset() |
| 131 | + refused_list = [ |
| 132 | + aiosmtplib.SMTPRecipientRefused(code, msg.decode() if isinstance(msg, bytes) else msg, addr) |
| 133 | + for addr, (code, msg) in response.refused_recipients.items() |
| 134 | + ] |
| 135 | + response.set_exception(aiosmtplib.SMTPRecipientsRefused(refused_list)) |
| 136 | + return response |
| 137 | + |
| 138 | + resp = await self._smtp.data(msg) |
| 139 | + resp_msg = resp.message.encode() if isinstance(resp.message, str) else resp.message |
| 140 | + response.set_status('data', resp.code, resp_msg) |
| 141 | + if resp.code != 250: |
| 142 | + await self._rset() |
| 143 | + response.set_exception( |
| 144 | + aiosmtplib.SMTPDataError(resp.code, resp.message)) |
| 145 | + return response |
| 146 | + |
| 147 | + response._finished = True |
| 148 | + return response |
0 commit comments