or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

exceptions.mdhigh-level-api.mdindex.mdsmtp-client.mdutilities.md

index.mddocs/

0

# aiosmtplib

1

2

An asyncio SMTP client for Python that provides asynchronous email sending capabilities. Built on top of Python's asyncio framework, aiosmtplib enables non-blocking email operations in asynchronous applications while supporting authentication, TLS/SSL encryption, and comprehensive SMTP features.

3

4

## Package Information

5

6

- **Package Name**: aiosmtplib

7

- **Language**: Python

8

- **Installation**: `pip install aiosmtplib`

9

- **Requires Python**: >=3.9

10

- **License**: MIT

11

12

## Core Imports

13

14

```python

15

import aiosmtplib

16

from aiosmtplib import SMTP, send

17

```

18

19

Import specific exceptions, types, and utilities:

20

21

```python

22

from aiosmtplib import (

23

SMTPResponse,

24

SMTPStatus,

25

SMTPException,

26

SMTPConnectError,

27

SMTPAuthenticationError,

28

# Other exceptions as needed

29

)

30

```

31

32

Import utility functions from specific modules:

33

34

```python

35

from aiosmtplib.auth import auth_plain_encode, auth_login_encode, auth_crammd5_verify

36

from aiosmtplib.email import extract_recipients, extract_sender, flatten_message, parse_address, quote_address

37

from aiosmtplib.esmtp import parse_esmtp_extensions

38

```

39

40

## Basic Usage

41

42

```python

43

import asyncio

44

import aiosmtplib

45

from email.message import EmailMessage

46

47

async def send_basic_email():

48

# Simple high-level API usage

49

message = EmailMessage()

50

message["From"] = "sender@example.com"

51

message["To"] = "recipient@example.com"

52

message["Subject"] = "Test Email"

53

message.set_content("Hello from aiosmtplib!")

54

55

# Send using the high-level send() function

56

await aiosmtplib.send(

57

message,

58

hostname="smtp.gmail.com",

59

port=587,

60

start_tls=True,

61

username="your-email@gmail.com",

62

password="your-password"

63

)

64

65

async def send_with_client():

66

# Using the SMTP client class for persistent connections

67

smtp = aiosmtplib.SMTP(hostname="localhost", port=1025)

68

await smtp.connect()

69

70

try:

71

await smtp.sendmail(

72

"sender@example.com",

73

["recipient@example.com"],

74

"Subject: Test\n\nHello World!"

75

)

76

finally:

77

smtp.close()

78

79

# Run the async function

80

asyncio.run(send_basic_email())

81

```

82

83

## Architecture

84

85

aiosmtplib provides multiple layers of abstraction for different use cases:

86

87

- **High-level API**: `send()` function for simple one-off email sending with automatic connection management

88

- **Client API**: `SMTP` class for persistent connections, advanced features, and fine-grained control

89

- **Utility Functions**: Helper functions for authentication, email parsing, and ESMTP extension handling

90

- **Exception Hierarchy**: Comprehensive error handling with specific exception types for different failure modes

91

92

The library handles connection management, TLS/SSL encryption, authentication protocols (CRAM-MD5, PLAIN, LOGIN), and provides full compatibility with Python's email module for message construction.

93

94

## Capabilities

95

96

### High-Level Email Sending

97

98

Simple function for sending emails with automatic connection management and cleanup. Ideal for one-off email sending scenarios where you don't need persistent connections.

99

100

```python { .api }

101

async def send(

102

message: Union[EmailMessage, Message, str, bytes],

103

/,

104

*,

105

sender: Optional[str] = None,

106

recipients: Optional[Union[str, Sequence[str]]] = None,

107

mail_options: Optional[Sequence[str]] = None,

108

rcpt_options: Optional[Sequence[str]] = None,

109

hostname: Optional[str] = "localhost",

110

port: Optional[int] = None,

111

username: Optional[Union[str, bytes]] = None,

112

password: Optional[Union[str, bytes]] = None,

113

local_hostname: Optional[str] = None,

114

source_address: Optional[tuple[str, int]] = None,

115

timeout: Optional[float] = 60,

116

use_tls: bool = False,

117

start_tls: Optional[bool] = None,

118

validate_certs: bool = True,

119

client_cert: Optional[str] = None,

120

client_key: Optional[str] = None,

121

tls_context: Optional[ssl.SSLContext] = None,

122

cert_bundle: Optional[str] = None,

123

socket_path: Optional[SocketPathType] = None,

124

sock: Optional[socket.socket] = None,

125

) -> tuple[dict[str, SMTPResponse], str]: ...

126

```

127

128

[High-Level API](./high-level-api.md)

129

130

### SMTP Client Class

131

132

Full-featured async SMTP client class providing persistent connections, context manager support, and comprehensive SMTP command implementations. Perfect for applications requiring multiple email operations or fine-grained control.

133

134

```python { .api }

135

class SMTP:

136

def __init__(

137

self,

138

*,

139

hostname: Optional[str] = None,

140

port: Optional[int] = None,

141

username: Optional[Union[str, bytes]] = None,

142

password: Optional[Union[str, bytes]] = None,

143

local_hostname: Optional[str] = None,

144

source_address: Optional[tuple[str, int]] = None,

145

timeout: Optional[float] = 60,

146

use_tls: bool = False,

147

start_tls: Optional[bool] = None,

148

validate_certs: bool = True,

149

client_cert: Optional[str] = None,

150

client_key: Optional[str] = None,

151

tls_context: Optional[ssl.SSLContext] = None,

152

cert_bundle: Optional[str] = None,

153

socket_path: Optional[SocketPathType] = None,

154

sock: Optional[socket.socket] = None,

155

) -> None: ...

156

157

# Connection management

158

async def connect(...) -> SMTPResponse: ...

159

def close(self) -> None: ...

160

161

# Properties

162

@property

163

def is_connected(self) -> bool: ...

164

@property

165

def supported_auth_methods(self) -> list[str]: ...

166

167

# High-level email sending

168

async def sendmail(...) -> tuple[dict[str, SMTPResponse], str]: ...

169

async def send_message(...) -> tuple[dict[str, SMTPResponse], str]: ...

170

171

# Authentication

172

async def login(username: Union[str, bytes], password: Union[str, bytes]) -> SMTPResponse: ...

173

async def auth_plain(...) -> SMTPResponse: ...

174

async def auth_login(...) -> SMTPResponse: ...

175

async def auth_crammd5(...) -> SMTPResponse: ...

176

177

# SMTP/ESMTP commands

178

async def helo(...) -> SMTPResponse: ...

179

async def ehlo(...) -> SMTPResponse: ...

180

async def starttls(...) -> SMTPResponse: ...

181

async def mail(...) -> SMTPResponse: ...

182

async def rcpt(...) -> SMTPResponse: ...

183

async def data(...) -> SMTPResponse: ...

184

async def rset() -> SMTPResponse: ...

185

async def quit() -> SMTPResponse: ...

186

async def noop() -> SMTPResponse: ...

187

async def vrfy(...) -> SMTPResponse: ...

188

async def expn(...) -> SMTPResponse: ...

189

async def help() -> str: ...

190

191

# Utility methods

192

def supports_extension(extension: str) -> bool: ...

193

async def execute_command(*args: bytes) -> SMTPResponse: ...

194

def get_transport_info(key: str) -> Any: ...

195

```

196

197

[SMTP Client](./smtp-client.md)

198

199

### Exception Handling

200

201

Comprehensive exception hierarchy for handling different types of SMTP errors, from connection issues to authentication failures and server responses.

202

203

```python { .api }

204

class SMTPException(Exception): ...

205

class SMTPConnectError(SMTPException, ConnectionError): ...

206

class SMTPTimeoutError(SMTPException, TimeoutError): ...

207

class SMTPAuthenticationError(SMTPResponseException): ...

208

class SMTPRecipientRefused(SMTPResponseException): ...

209

class SMTPSenderRefused(SMTPResponseException): ...

210

```

211

212

[Exception Handling](./exceptions.md)

213

214

### Utility Functions

215

216

Helper functions for authentication, email message processing, and ESMTP extension parsing. Useful for custom implementations and debugging.

217

218

```python { .api }

219

def auth_plain_encode(username: str, password: str) -> bytes: ...

220

def extract_recipients(message: Union[EmailMessage, Message]) -> list[str]: ...

221

def parse_esmtp_extensions(message: str) -> tuple[dict[str, str], list[str]]: ...

222

```

223

224

[Utilities](./utilities.md)

225

226

## Types

227

228

```python { .api }

229

class SMTPResponse(NamedTuple):

230

"""Server response containing status code and message."""

231

code: int

232

message: str

233

234

class SMTPStatus(IntEnum):

235

"""SMTP status codes for response handling."""

236

invalid_response = -1

237

system_status_ok = 211

238

help_message = 214

239

ready = 220

240

closing = 221

241

auth_successful = 235

242

completed = 250

243

will_forward = 251

244

cannot_vrfy = 252

245

auth_continue = 334

246

start_input = 354

247

domain_unavailable = 421

248

mailbox_unavailable = 450

249

error_processing = 451

250

insufficient_storage = 452

251

tls_not_available = 454

252

unrecognized_command = 500

253

unrecognized_parameters = 501

254

command_not_implemented = 502

255

bad_command_sequence = 503

256

parameter_not_implemented = 504

257

domain_does_not_accept_mail = 521

258

access_denied = 530

259

auth_failed = 535

260

mailbox_does_not_exist = 550

261

user_not_local = 551

262

storage_exceeded = 552

263

mailbox_name_invalid = 553

264

transaction_failed = 554

265

syntax_error = 555

266

267

SocketPathType = Union[str, bytes, os.PathLike[str]]

268

```

269

270

## Constants

271

272

```python { .api }

273

SMTP_PORT: int = 25

274

SMTP_TLS_PORT: int = 465

275

SMTP_STARTTLS_PORT: int = 587

276

DEFAULT_TIMEOUT: float = 60

277

```