/
smtp.py
1459 lines (1230 loc) · 52.8 KB
/
smtp.py
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Main SMTP client class.
Implements SMTP, ESMTP & Auth methods.
"""
import asyncio
import email.message
import socket
import ssl
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Type, Union
from .auth import auth_crammd5_verify, auth_login_encode, auth_plain_encode
from .email import (
extract_recipients,
extract_sender,
flatten_message,
parse_address,
quote_address,
)
from .errors import (
SMTPAuthenticationError,
SMTPConnectError,
SMTPConnectTimeoutError,
SMTPException,
SMTPHeloError,
SMTPNotSupported,
SMTPRecipientRefused,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPSenderRefused,
SMTPServerDisconnected,
SMTPTimeoutError,
SMTPConnectResponseError,
)
from .esmtp import parse_esmtp_extensions
from .protocol import SMTPProtocol
from .response import SMTPResponse
from .typing import Default, SMTPStatus, SocketPathType, _default
__all__ = ("SMTP", "SMTP_PORT", "SMTP_TLS_PORT", "SMTP_STARTTLS_PORT")
SMTP_PORT = 25
SMTP_TLS_PORT = 465
SMTP_STARTTLS_PORT = 587
DEFAULT_TIMEOUT = 60
class SMTP:
"""
Main SMTP client class.
Basic usage:
>>> event_loop = asyncio.get_event_loop()
>>> smtp = aiosmtplib.SMTP(hostname="127.0.0.1", port=1025)
>>> event_loop.run_until_complete(smtp.connect())
(220, ...)
>>> sender = "root@localhost"
>>> recipients = ["somebody@localhost"]
>>> message = "Hello World"
>>> send = smtp.sendmail(sender, recipients, "Hello World")
>>> event_loop.run_until_complete(send)
({}, 'OK')
Keyword arguments can be provided either on :meth:`__init__` or when
calling the :meth:`connect` method. Note that in both cases these options,
except for ``timeout``, are saved for later use; subsequent calls to
:meth:`connect` will use the same options, unless new ones are provided.
``timeout`` is saved for later use when provided on :meth:`__init__`, but
not when calling the :meth:`connect` method.
"""
# Preferred methods first
AUTH_METHODS: Tuple[str, ...] = (
"cram-md5",
"plain",
"login",
)
def __init__(
self,
*,
hostname: Optional[str] = "localhost",
port: Optional[int] = None,
username: Optional[Union[str, bytes]] = None,
password: Optional[Union[str, bytes]] = None,
local_hostname: Optional[str] = None,
source_address: Optional[Tuple[str, int]] = None,
timeout: Optional[float] = DEFAULT_TIMEOUT,
use_tls: bool = False,
start_tls: Optional[bool] = None,
validate_certs: bool = True,
client_cert: Optional[str] = None,
client_key: Optional[str] = None,
tls_context: Optional[ssl.SSLContext] = None,
cert_bundle: Optional[str] = None,
socket_path: Optional[SocketPathType] = None,
sock: Optional[socket.socket] = None,
) -> None:
"""
:keyword hostname: Server name (or IP) to connect to. Defaults to "localhost".
:keyword port: Server port. Defaults ``465`` if ``use_tls`` is ``True``,
``587`` if ``start_tls`` is ``True``, or ``25`` otherwise.
:keyword username: Username to login as after connect.
:keyword password: Password for login after connect.
:keyword local_hostname: The hostname of the client. If specified, used as the
FQDN of the local host in the HELO/EHLO command. Otherwise, the result of
:func:`socket.getfqdn`. **Note that getfqdn will block the event loop.**
:keyword source_address: Takes a 2-tuple (host, port) for the socket to bind to
as its source address before connecting. If the host is '' and port is 0,
the OS default behavior will be used.
:keyword timeout: Default timeout value for the connection, in seconds.
Defaults to 60.
:keyword use_tls: If True, make the initial connection to the server
over TLS/SSL. Mutually exclusive with ``start_tls``; if the server uses
STARTTLS, ``use_tls`` should be ``False``.
:keyword start_tls: Flag to initiate a STARTTLS upgrade on connect.
If ``None`` (the default), upgrade will be initiated if supported by the
server.
If ``True``, and upgrade will be initiated regardless of server support.
If ``False``, no upgrade will occur.
Mutually exclusive with ``use_tls``.
:keyword validate_certs: Determines if server certificates are
validated. Defaults to ``True``.
:keyword client_cert: Path to client side certificate, for TLS.
:keyword client_key: Path to client side key, for TLS.
:keyword tls_context: An existing :py:class:`ssl.SSLContext`, for TLS.
Mutually exclusive with ``client_cert``/``client_key``.
:keyword cert_bundle: Path to certificate bundle, for TLS verification.
:keyword socket_path: Path to a Unix domain socket. Not compatible with
hostname or port. Accepts str, bytes, or a pathlike object.
:keyword sock: An existing, connected socket object. If given, none of
hostname, port, or socket_path should be provided.
:raises ValueError: mutually exclusive options provided
"""
self.protocol: Optional[SMTPProtocol] = None
self.transport: Optional[asyncio.BaseTransport] = None
# Kwarg defaults are provided here, and saved for connect.
self.hostname = hostname
self.port = port
self._login_username = username
self._login_password = password
self._local_hostname = local_hostname
self.timeout = timeout
self.use_tls = use_tls
self._start_tls_on_connect = start_tls
self.validate_certs = validate_certs
self.client_cert = client_cert
self.client_key = client_key
self.tls_context = tls_context
self.cert_bundle = cert_bundle
self.socket_path = socket_path
self.sock = sock
self.source_address = source_address
self.loop: Optional[asyncio.AbstractEventLoop] = None
self._connect_lock: Optional[asyncio.Lock] = None
self.last_helo_response: Optional[SMTPResponse] = None
self._last_ehlo_response: Optional[SMTPResponse] = None
self.esmtp_extensions: Dict[str, str] = {}
self.supports_esmtp = False
self.server_auth_methods: List[str] = []
self._sendmail_lock: Optional[asyncio.Lock] = None
self._validate_config()
async def __aenter__(self) -> "SMTP":
if not self.is_connected:
await self.connect()
return self
async def __aexit__(
self, exc_type: Type[BaseException], exc: BaseException, traceback: Any
) -> None:
if isinstance(exc, (ConnectionError, TimeoutError)):
self.close()
return
try:
await self.quit()
except (SMTPServerDisconnected, SMTPResponseException, SMTPTimeoutError):
pass
@property
def is_connected(self) -> bool:
"""
Check if our transport is still connected.
"""
return bool(self.protocol is not None and self.protocol.is_connected)
@property
def local_hostname(self) -> str:
"""
Get the system hostname to be sent to the SMTP server.
Simply caches the result of :func:`socket.getfqdn`.
"""
if self._local_hostname is None:
self._local_hostname = socket.getfqdn()
return self._local_hostname
@property
def last_ehlo_response(self) -> Union[SMTPResponse, None]:
return self._last_ehlo_response
@last_ehlo_response.setter
def last_ehlo_response(self, response: SMTPResponse) -> None:
"""
When setting the last EHLO response, parse the message for supported
extensions and auth methods.
"""
extensions, auth_methods = parse_esmtp_extensions(response.message)
self._last_ehlo_response = response
self.esmtp_extensions = extensions
self.server_auth_methods = auth_methods
self.supports_esmtp = True
@property
def is_ehlo_or_helo_needed(self) -> bool:
"""
Check if we've already received a response to an EHLO or HELO command.
"""
return self.last_ehlo_response is None and self.last_helo_response is None
@property
def supported_auth_methods(self) -> List[str]:
"""
Get all AUTH methods supported by the both server and by us.
"""
return [auth for auth in self.AUTH_METHODS if auth in self.server_auth_methods]
def _update_settings_from_kwargs(
self,
hostname: Optional[Union[str, Default]] = _default,
port: Optional[Union[int, Default]] = _default,
username: Optional[Union[str, bytes, Default]] = _default,
password: Optional[Union[str, bytes, Default]] = _default,
local_hostname: Optional[Union[str, Default]] = _default,
source_address: Optional[Union[Tuple[str, int], Default]] = _default,
use_tls: Optional[bool] = None,
start_tls: Optional[Union[bool, Default]] = _default,
validate_certs: Optional[bool] = None,
client_cert: Optional[Union[str, Default]] = _default,
client_key: Optional[Union[str, Default]] = _default,
tls_context: Optional[Union[ssl.SSLContext, Default]] = _default,
cert_bundle: Optional[Union[str, Default]] = _default,
socket_path: Optional[Union[SocketPathType, Default]] = _default,
sock: Optional[Union[socket.socket, Default]] = _default,
) -> None:
"""Update our configuration from the kwargs provided.
This method can be called multiple times.
"""
if hostname is not _default:
self.hostname = hostname
if use_tls is not None:
self.use_tls = use_tls
if start_tls is not _default:
self._start_tls_on_connect = start_tls
if validate_certs is not None:
self.validate_certs = validate_certs
if port is not _default:
self.port = port
if username is not _default:
self._login_username = username
if password is not _default:
self._login_password = password
if local_hostname is not _default:
self._local_hostname = local_hostname
if source_address is not _default:
self.source_address = source_address
if client_cert is not _default:
self.client_cert = client_cert
if client_key is not _default:
self.client_key = client_key
if tls_context is not _default:
self.tls_context = tls_context
if cert_bundle is not _default:
self.cert_bundle = cert_bundle
if socket_path is not _default:
self.socket_path = socket_path
if sock is not _default:
self.sock = sock
def _validate_config(self) -> None:
if self._start_tls_on_connect and self.use_tls:
raise ValueError("The start_tls and use_tls options are not compatible.")
if self.tls_context is not None and self.client_cert is not None:
raise ValueError(
"Either a TLS context or a certificate/key must be provided"
)
if self.sock is not None and any([self.hostname, self.port, self.socket_path]):
raise ValueError(
"The socket option is not compatible with hostname, port or socket_path"
)
if self.socket_path is not None and any([self.hostname, self.port]):
raise ValueError(
"The socket_path option is not compatible with hostname/port"
)
if self._local_hostname is not None and (
"\r" in self._local_hostname or "\n" in self._local_hostname
):
raise ValueError(
"The local_hostname param contains prohibited newline characters"
)
if self.hostname is not None and (
"\r" in self.hostname or "\n" in self.hostname
):
raise ValueError(
"The hostname param contains prohibited newline characters"
)
def _get_default_port(self) -> int:
"""
Return an appropriate default port, based on options selected.
"""
if self.use_tls:
return SMTP_TLS_PORT
elif self._start_tls_on_connect:
return SMTP_STARTTLS_PORT
return SMTP_PORT
async def connect(
self,
*,
hostname: Optional[Union[str, Default]] = _default,
port: Optional[Union[int, Default]] = _default,
username: Optional[Union[str, bytes, Default]] = _default,
password: Optional[Union[str, bytes, Default]] = _default,
local_hostname: Optional[Union[str, Default]] = _default,
source_address: Optional[Union[Tuple[str, int], Default]] = _default,
timeout: Optional[Union[float, Default]] = _default,
use_tls: Optional[bool] = None,
start_tls: Optional[Union[bool, Default]] = _default,
validate_certs: Optional[bool] = None,
client_cert: Optional[Union[str, Default]] = _default,
client_key: Optional[Union[str, Default]] = _default,
tls_context: Optional[Union[ssl.SSLContext, Default]] = _default,
cert_bundle: Optional[Union[str, Default]] = _default,
socket_path: Optional[Union[SocketPathType, Default]] = _default,
sock: Optional[Union[socket.socket, Default]] = _default,
) -> SMTPResponse:
"""
Initialize a connection to the server. Options provided to
:meth:`.connect` take precedence over those used to initialize the
class.
:keyword hostname: Server name (or IP) to connect to. Defaults to "localhost".
:keyword port: Server port. Defaults ``465`` if ``use_tls`` is ``True``,
``587`` if ``start_tls`` is ``True``, or ``25`` otherwise.
:keyword username: Username to login as after connect.
:keyword password: Password for login after connect.
:keyword local_hostname: The hostname of the client. If specified, used as the
FQDN of the local host in the HELO/EHLO command. Otherwise, the result of
:func:`socket.getfqdn`. **Note that getfqdn will block the event loop.**
:keyword source_address: Takes a 2-tuple (host, port) for the socket to bind to
as its source address before connecting. If the host is '' and port is 0,
the OS default behavior will be used.
:keyword timeout: Default timeout value for the connection, in seconds.
Defaults to 60.
:keyword use_tls: If True, make the initial connection to the server
over TLS/SSL. Mutually exclusive with ``start_tls``; if the server uses
STARTTLS, ``use_tls`` should be ``False``.
:keyword start_tls: Flag to initiate a STARTTLS upgrade on connect.
If ``None`` (the default), upgrade will be initiated if supported by the
server.
If ``True``, and upgrade will be initiated regardless of server support.
If ``False``, no upgrade will occur.
Mutually exclusive with ``use_tls``.
:keyword validate_certs: Determines if server certificates are
validated. Defaults to ``True``.
:keyword client_cert: Path to client side certificate, for TLS.
:keyword client_key: Path to client side key, for TLS.
:keyword tls_context: An existing :py:class:`ssl.SSLContext`, for TLS.
Mutually exclusive with ``client_cert``/``client_key``.
:keyword cert_bundle: Path to certificate bundle, for TLS verification.
:keyword socket_path: Path to a Unix domain socket. Not compatible with
hostname or port. Accepts str, bytes, or a pathlike object.
:keyword sock: An existing, connected socket object. If given, none of
hostname, port, or socket_path should be provided.
:raises ValueError: mutually exclusive options provided
"""
self._update_settings_from_kwargs(
hostname=hostname,
port=port,
local_hostname=local_hostname,
source_address=source_address,
use_tls=use_tls,
start_tls=start_tls,
validate_certs=validate_certs,
client_cert=client_cert,
client_key=client_key,
tls_context=tls_context,
cert_bundle=cert_bundle,
socket_path=socket_path,
sock=sock,
username=username,
password=password,
)
self._validate_config()
self.loop = asyncio.get_running_loop()
if self._connect_lock is None:
self._connect_lock = asyncio.Lock()
await self._connect_lock.acquire()
# Set default port last in case use_tls or start_tls is provided,
# and only if we're not using a socket.
if self.port is None and self.sock is None and self.socket_path is None:
self.port = self._get_default_port()
try:
response = await self._create_connection(
timeout=self.timeout if timeout is _default else timeout
)
await self._maybe_start_tls_on_connect()
await self._maybe_login_on_connect()
except Exception as exc:
self.close() # Reset our state to disconnected
raise exc
return response
async def _create_connection(self, timeout: Optional[float]) -> SMTPResponse:
if self.loop is None:
raise RuntimeError("No event loop set")
protocol = SMTPProtocol(loop=self.loop)
tls_context: Optional[ssl.SSLContext] = None
ssl_handshake_timeout: Optional[float] = None
if self.use_tls:
tls_context = self._get_tls_context()
ssl_handshake_timeout = timeout
if self.sock is not None:
connect_coro = self.loop.create_connection(
lambda: protocol,
sock=self.sock,
ssl=tls_context,
ssl_handshake_timeout=ssl_handshake_timeout,
)
elif self.socket_path is not None:
connect_coro = self.loop.create_unix_connection(
lambda: protocol,
path=self.socket_path, # type: ignore
ssl=tls_context,
ssl_handshake_timeout=ssl_handshake_timeout,
)
else:
if self.hostname is None:
raise RuntimeError("No hostname provided; default should have been set")
if self.port is None:
raise RuntimeError("No port provided; default should have been set")
connect_coro = self.loop.create_connection(
lambda: protocol,
host=self.hostname,
port=self.port,
ssl=tls_context,
ssl_handshake_timeout=ssl_handshake_timeout,
local_addr=self.source_address,
)
try:
transport, _ = await asyncio.wait_for(connect_coro, timeout=timeout)
except (TimeoutError, asyncio.TimeoutError) as exc:
raise SMTPConnectTimeoutError(
f"Timed out connecting to {self.hostname} on port {self.port}"
) from exc
except OSError as exc:
raise SMTPConnectError(
f"Error connecting to {self.hostname} on port {self.port}: {exc}"
) from exc
self.protocol = protocol
self.transport = transport
try:
response = await protocol.read_response(timeout=timeout)
except SMTPServerDisconnected as exc:
raise SMTPConnectError(
f"Error connecting to {self.hostname} on port {self.port}: {exc}"
) from exc
except SMTPTimeoutError as exc:
raise SMTPConnectTimeoutError(
"Timed out waiting for server ready message"
) from exc
if response.code != SMTPStatus.ready:
raise SMTPConnectResponseError(response.code, response.message)
return response
def _connection_lost(self, waiter: "asyncio.Future[None]") -> None:
self.close()
async def _maybe_start_tls_on_connect(self) -> None:
"""
Depending on config, upgrade the connection via STARTTLS.
"""
if self._start_tls_on_connect is True:
await self.starttls()
# If _start_tls_on_connect hasn't been set either way,
# try to STARTTLS if supported, with graceful failure handling
elif self._start_tls_on_connect is None:
already_using_tls = self.get_transport_info("sslcontext") is not None
if not (self.use_tls or already_using_tls):
await self._ehlo_or_helo_if_needed()
if self.supports_extension("starttls"):
await self.starttls()
async def _maybe_login_on_connect(self) -> None:
"""
Depending on config, login after connecting.
"""
if self._login_username is not None:
login_password = (
self._login_password if self._login_password is not None else ""
)
await self.login(self._login_username, login_password)
async def execute_command(
self, *args: bytes, timeout: Optional[Union[float, Default]] = _default
) -> SMTPResponse:
"""
Check that we're connected, if we got a timeout value, and then
pass the command to the protocol.
:raises SMTPServerDisconnected: connection lost
"""
if self.protocol is None:
raise SMTPServerDisconnected("Server not connected")
response = await self.protocol.execute_command(
*args, timeout=self.timeout if timeout is _default else timeout
)
# If the server is unavailable, be nice and close the connection
if response.code == SMTPStatus.domain_unavailable:
self.close()
return response
def _get_tls_context(self) -> ssl.SSLContext:
"""
Build an SSLContext object from the options we've been given.
"""
if self.tls_context is not None:
context = self.tls_context
else:
# SERVER_AUTH is what we want for a client side socket
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
context.check_hostname = bool(self.validate_certs)
if self.validate_certs:
context.verify_mode = ssl.CERT_REQUIRED
else:
context.verify_mode = ssl.CERT_NONE
if self.cert_bundle is not None:
context.load_verify_locations(cafile=self.cert_bundle)
if self.client_cert is not None:
context.load_cert_chain(self.client_cert, keyfile=self.client_key)
return context
def close(self) -> None:
"""
Closes the connection.
"""
if self.transport is not None and not self.transport.is_closing():
self.transport.close()
if self._connect_lock is not None and self._connect_lock.locked():
self._connect_lock.release()
self.protocol = None
self.transport = None
# Reset ESMTP state
self._reset_server_state()
def get_transport_info(self, key: str) -> Any:
"""
Get extra info from the transport.
Supported keys:
- ``peername``
- ``socket``
- ``sockname``
- ``compression``
- ``cipher``
- ``peercert``
- ``sslcontext``
- ``sslobject``
:raises SMTPServerDisconnected: connection lost
"""
if not (self.is_connected and self.transport):
raise SMTPServerDisconnected("Server not connected")
return self.transport.get_extra_info(key)
# Base SMTP commands #
async def helo(
self,
*,
hostname: Optional[str] = None,
timeout: Optional[Union[float, Default]] = _default,
) -> SMTPResponse:
"""
Send the SMTP HELO command.
Hostname to send for this command defaults to the FQDN of the local
host.
:raises SMTPHeloError: on unexpected server response code
"""
response = self.last_helo_response = await self.execute_command(
b"HELO", (hostname or self.local_hostname).encode("ascii"), timeout=timeout
)
if response.code != SMTPStatus.completed:
raise SMTPHeloError(response.code, response.message)
return response
async def help(self, *, timeout: Optional[Union[float, Default]] = _default) -> str:
"""
Send the SMTP HELP command, which responds with help text.
:raises SMTPResponseException: on unexpected server response code
"""
await self._ehlo_or_helo_if_needed()
response = await self.execute_command(b"HELP", timeout=timeout)
if response.code not in (
SMTPStatus.system_status_ok,
SMTPStatus.help_message,
SMTPStatus.completed,
):
raise SMTPResponseException(response.code, response.message)
return response.message
async def rset(
self, *, timeout: Optional[Union[float, Default]] = _default
) -> SMTPResponse:
"""
Send an SMTP RSET command, which resets the server's envelope
(the envelope contains the sender, recipient, and mail data).
:raises SMTPResponseException: on unexpected server response code
"""
await self._ehlo_or_helo_if_needed()
response = await self.execute_command(b"RSET", timeout=timeout)
if response.code != SMTPStatus.completed:
raise SMTPResponseException(response.code, response.message)
return response
async def noop(
self, *, timeout: Optional[Union[float, Default]] = _default
) -> SMTPResponse:
"""
Send an SMTP NOOP command, which does nothing.
:raises SMTPResponseException: on unexpected server response code
"""
await self._ehlo_or_helo_if_needed()
response = await self.execute_command(b"NOOP", timeout=timeout)
if response.code != SMTPStatus.completed:
raise SMTPResponseException(response.code, response.message)
return response
async def vrfy(
self,
address: str,
/,
*,
options: Optional[Iterable[str]] = None,
timeout: Optional[Union[float, Default]] = _default,
) -> SMTPResponse:
"""
Send an SMTP VRFY command, which tests an address for validity.
Not many servers support this command.
:raises SMTPResponseException: on unexpected server response code
"""
await self._ehlo_or_helo_if_needed()
if options is None:
options = []
parsed_address = parse_address(address)
if any(option.lower() == "smtputf8" for option in options):
if not self.supports_extension("smtputf8"):
raise SMTPNotSupported("SMTPUTF8 is not supported by this server")
addr_bytes = parsed_address.encode("utf-8")
else:
addr_bytes = parsed_address.encode("ascii")
options_bytes = [option.encode("ascii") for option in options]
response = await self.execute_command(
b"VRFY", addr_bytes, *options_bytes, timeout=timeout
)
if response.code not in (
SMTPStatus.completed,
SMTPStatus.will_forward,
SMTPStatus.cannot_vrfy,
):
raise SMTPResponseException(response.code, response.message)
return response
async def expn(
self,
address: str,
/,
*,
options: Optional[Iterable[str]] = None,
timeout: Optional[Union[float, Default]] = _default,
) -> SMTPResponse:
"""
Send an SMTP EXPN command, which expands a mailing list.
Not many servers support this command.
:raises SMTPResponseException: on unexpected server response code
"""
await self._ehlo_or_helo_if_needed()
if options is None:
options = []
parsed_address = parse_address(address)
if any(option.lower() == "smtputf8" for option in options):
if not self.supports_extension("smtputf8"):
raise SMTPNotSupported("SMTPUTF8 is not supported by this server")
addr_bytes = parsed_address.encode("utf-8")
else:
addr_bytes = parsed_address.encode("ascii")
options_bytes = [option.encode("ascii") for option in options]
response = await self.execute_command(
b"EXPN", addr_bytes, *options_bytes, timeout=timeout
)
if response.code != SMTPStatus.completed:
raise SMTPResponseException(response.code, response.message)
return response
async def quit(
self, *, timeout: Optional[Union[float, Default]] = _default
) -> SMTPResponse:
"""
Send the SMTP QUIT command, which closes the connection.
Also closes the connection from our side after a response is received.
:raises SMTPResponseException: on unexpected server response code
"""
response = await self.execute_command(b"QUIT", timeout=timeout)
if response.code != SMTPStatus.closing:
raise SMTPResponseException(response.code, response.message)
self.close()
return response
async def mail(
self,
sender: str,
/,
*,
options: Optional[Iterable[str]] = None,
encoding: str = "ascii",
timeout: Optional[Union[float, Default]] = _default,
) -> SMTPResponse:
"""
Send an SMTP MAIL command, which specifies the message sender and
begins a new mail transfer session ("envelope").
:raises SMTPSenderRefused: on unexpected server response code
"""
await self._ehlo_or_helo_if_needed()
if options is None:
options = []
quoted_sender = quote_address(sender)
addr_bytes = quoted_sender.encode(encoding)
options_bytes = [option.encode("ascii") for option in options]
response = await self.execute_command(
b"MAIL", b"FROM:" + addr_bytes, *options_bytes, timeout=timeout
)
if response.code != SMTPStatus.completed:
raise SMTPSenderRefused(response.code, response.message, sender)
return response
async def rcpt(
self,
recipient: str,
/,
*,
options: Optional[Iterable[str]] = None,
encoding: str = "ascii",
timeout: Optional[Union[float, Default]] = _default,
) -> SMTPResponse:
"""
Send an SMTP RCPT command, which specifies a single recipient for
the message. This command is sent once per recipient and must be
preceded by 'MAIL'.
:raises SMTPRecipientRefused: on unexpected server response code
"""
await self._ehlo_or_helo_if_needed()
if options is None:
options = []
quoted_recipient = quote_address(recipient)
addr_bytes = quoted_recipient.encode(encoding)
options_bytes = [option.encode("ascii") for option in options]
response = await self.execute_command(
b"RCPT", b"TO:" + addr_bytes, *options_bytes, timeout=timeout
)
if response.code not in (SMTPStatus.completed, SMTPStatus.will_forward):
raise SMTPRecipientRefused(response.code, response.message, recipient)
return response
async def data(
self,
message: Union[str, bytes],
/,
*,
timeout: Optional[Union[float, Default]] = _default,
) -> SMTPResponse:
"""
Send an SMTP DATA command, followed by the message given.
This method transfers the actual email content to the server.
:raises SMTPDataError: on unexpected server response code
:raises SMTPServerDisconnected: connection lost
"""
await self._ehlo_or_helo_if_needed()
# As data accesses protocol directly, some handling is required
if self.protocol is None:
raise SMTPServerDisconnected("Connection lost")
if timeout is _default:
timeout = self.timeout
if isinstance(message, str):
message = message.encode("ascii")
return await self.protocol.execute_data_command(message, timeout=timeout)
# ESMTP commands #
async def ehlo(
self,
*,
hostname: Optional[str] = None,
timeout: Optional[Union[float, Default]] = _default,
) -> SMTPResponse:
"""
Send the SMTP EHLO command.
Hostname to send for this command defaults to the FQDN of the local
host.
:raises SMTPHeloError: on unexpected server response code
"""
if hostname is None:
hostname = self.local_hostname
response = await self.execute_command(
b"EHLO", hostname.encode("ascii"), timeout=timeout
)
self.last_ehlo_response = response
if response.code != SMTPStatus.completed:
raise SMTPHeloError(response.code, response.message)
return response
def supports_extension(self, extension: str, /) -> bool:
"""
Tests if the server supports the ESMTP service extension given.
"""
return extension.lower() in self.esmtp_extensions
async def _ehlo_or_helo_if_needed(self) -> None:
"""
Call self.ehlo() and/or self.helo() if needed.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.
"""
if self.is_ehlo_or_helo_needed:
try:
await self.ehlo()
except SMTPHeloError as exc:
if self.is_connected:
await self.helo()
else:
raise exc
def _reset_server_state(self) -> None:
"""
Clear stored information about the server.
"""
self.last_helo_response = None
self._last_ehlo_response = None
self.esmtp_extensions = {}
self.supports_esmtp = False
self.server_auth_methods = []
async def starttls(
self,
*,
server_hostname: Optional[str] = None,
validate_certs: Optional[bool] = None,
client_cert: Optional[Union[str, Default]] = _default,
client_key: Optional[Union[str, Default]] = _default,
cert_bundle: Optional[Union[str, Default]] = _default,
tls_context: Optional[Union[ssl.SSLContext, Default]] = _default,
timeout: Optional[Union[float, Default]] = _default,
) -> SMTPResponse:
"""
Puts the connection to the SMTP server into TLS mode.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.
If the server supports TLS, this will encrypt the rest of the SMTP
session. If you provide the keyfile and certfile parameters,
the identity of the SMTP server and client can be checked (if
validate_certs is True). You can also provide a custom SSLContext
object. If no certs or SSLContext is given, and TLS config was
provided when initializing the class, STARTTLS will use to that,
otherwise it will use the Python defaults.
:raises SMTPException: server does not support STARTTLS
:raises SMTPServerDisconnected: connection lost
:raises ValueError: invalid options provided
"""
await self._ehlo_or_helo_if_needed()
if self.protocol is None:
raise SMTPServerDisconnected("Server not connected")
if self.get_transport_info("sslcontext") is not None:
raise SMTPException("Connection already using TLS")
self._update_settings_from_kwargs(
validate_certs=validate_certs,
client_cert=client_cert,
client_key=client_key,
cert_bundle=cert_bundle,
tls_context=tls_context,
)
self._validate_config()
if server_hostname is None:
server_hostname = self.hostname
if timeout is _default:
timeout = self.timeout
tls_context = self._get_tls_context()
if not self.supports_extension("starttls"):
raise SMTPException("SMTP STARTTLS extension not supported by server.")
response = await self.protocol.start_tls(