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
|
<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Twisted Mail Tutorial: Building an SMTP Client from Scratch</title>
</head>
<body>
<h1>Twisted Mail Tutorial: Building an SMTP Client from Scratch</h1>
<h2>Stuff</h2>
<p>This tutorial will walk you through the creation of an extremely
simple SMTP client application. By the time the tutorial is complete,
you will understand how to create and start a TCP client speaking the
SMTP protocol, have it connect to an appropriate mail exchange server,
and transmit a message for delivery.</p>
<p>For the majority of this tutorial, <code>twistd</code> will be used
to launch the application. Near the end we will explore other
possibilities for starting a Twisted application. Until then, make
sure that you have <code>twistd</code> installed and conveniently
accessible for use in running each of the example <code>.tac</code>
files.</p>
<h3>SMTP Client 1</h3>
<p>The first step is to create <a href="smtpclient-1.tac">the most
minimal <code>.tac</code> file</a> possible for use by
<code>twistd</code>.</p>
<blockquote><code>
from twisted.application import service
</code></blockquote>
<p>The first line of the <code>.tac</code> file imports
<code>twisted.application.service</code>, a module which contains many
of the basic <em>service</em> classes and helper functions available
in Twisted. In particular, we will be using the
<code>Application</code> function to create a new <em>application
service</em>. An <em>application service</em> simply acts as a
central object on which to store certain kinds of deployment
configuration.</p>
<blockquote><code>
application = service.Application("SMTP Client Tutorial")
</code></blockquote>
<p>The second line of the <code>.tac</code> file creates a new
<em>application service</em> and binds it to the local name
<code>application</code>. <code>twistd</code> requires this local
name in each <code>.tac</code> file it runs. It uses various pieces
of configuration on the object to determine its behavior. For
example, <code>"SMTP Client Tutorial"</code> will be used as the name
of the <code>.tap</code> file into which to serialize application
state, should it be necessary to do so.</p>
<p>That does it for the first example. We now have enough of a
<code>.tac</code> file to pass to <code>twistd</code>. If we run <a
href="smtpclient-1.tac">smtpclient-1.tac</a> using the
<code>twistd</code> command line:</p>
<blockquote><code>
twistd -ny smtpclient-1.tac
</code></blockquote>
<p>we are rewarded with the following output:</p>
<blockquote><pre class="shell">
exarkun@boson:~/mail/tutorial/smtpclient$ twistd -ny smtpclient-1.tac
18:31 EST [-] Log opened.
18:31 EST [-] twistd 2.0.0 (/usr/bin/python2.4 2.4.1) starting up
18:31 EST [-] reactor class: twisted.internet.selectreactor.SelectReactor
18:31 EST [-] Loading smtpclient-1.tac...
18:31 EST [-] Loaded.
</pre></blockquote>
<p>As we expected, not much is going on. We can shutdown this server
by issueing <code>^C</code>:</p>
<blockquote><pre class="shell">
18:34 EST [-] Received SIGINT, shutting down.
18:34 EST [-] Main loop terminated.
18:34 EST [-] Server Shut Down.
exarkun@boson:~/mail/tutorial/smtpclient$
</pre></blockquote>
<h3>SMTP Client 2</h3>
<p>The first version of our SMTP client wasn't very interesting. It
didn't even establish any TCP connections! The <a
href="smtpclient-2.tac">second version</a> will come a little bit
closer to that level of complexity. First, we need to import a few
more things:</p>
<blockquote><code><pre class="python">
from twisted.application import internet
from twisted.internet import protocol
</pre></code></blockquote>
<p><code>twisted.application.internet</code> is another
<em>application service</em> module. It provides services for
establishing outgoing connections (as well as creating network
servers, though we are not interested in those parts for the moment).
<code>twisted.internet.protocol</code> provides base implementations
of many of the core Twisted concepts, such as <em>factories</em> and
<em>protocols</em>.</p>
<p>The next line of <a href="smtpclient-2.tac">smtpclient-2.tac</a>
instantiates a new <em>client factory</em>.</p>
<blockquote><code>
smtpClientFactory = protocol.ClientFactory()
</code></blockquote>
<p><em>Client factories</em> are responsible for constructing
<em>protocol instances</em> whenever connections are established.
They may be required to create just one instance, or many instances if
many different connections are established, or they may never be
required to create one at all, if no connection ever manages to be
established.</p>
<p>Now that we have a client factory, we'll need to hook it up to the
network somehow. The next line of <code>smtpclient-2.tac</code> does
just that:</p>
<blockquote><code>
smtpClientService = internet.TCPClient(None, None, smtpClientFactory)
</code></blockquote>
<p>We'll ignore the first two arguments to
<code>internet.TCPClient</code> for the moment and instead focus on
the third. <code>TCPClient</code> is one of those <em>application
service</em> classes. It creates TCP connections to a specified
address and then uses its third argument, a <em>client factory</em>,
to get a <em>protocol instance</em>. It then associates the TCP
connection with the protocol instance and gets out of the way.</p>
<p>We can try to run <code>smtpclient-2.tac</code> the same way we ran
<code>smtpclient-1.tac</code>, but the results might be a little
disappointing:</p>
<blockquote><code><pre class="shell">
exarkun@boson:~/mail/tutorial/smtpclient$ twistd -ny smtpclient-2.tac
18:55 EST [-] Log opened.
18:55 EST [-] twistd SVN-Trunk (/usr/bin/python2.4 2.4.1) starting up
18:55 EST [-] reactor class: twisted.internet.selectreactor.SelectReactor
18:55 EST [-] Loading smtpclient-2.tac...
18:55 EST [-] Loaded.
18:55 EST [-] Starting factory <twisted.internet.protocol.ClientFactory
instance at 0xb791e46c>
18:55 EST [-] Traceback (most recent call last):
File "twisted/scripts/twistd.py", line 187, in runApp
app.runReactorWithLogging(config, oldstdout, oldstderr)
File "twisted/application/app.py", line 128, in runReactorWithLogging
reactor.run()
File "twisted/internet/posixbase.py", line 200, in run
self.mainLoop()
File "twisted/internet/posixbase.py", line 208, in mainLoop
self.runUntilCurrent()
--- <exception caught here> ---
File "twisted/internet/base.py", line 533, in runUntilCurrent
call.func(*call.args, **call.kw)
File "twisted/internet/tcp.py", line 489, in resolveAddress
if abstract.isIPAddress(self.addr[0]):
File "twisted/internet/abstract.py", line 315, in isIPAddress
parts = string.split(addr, '.')
File "/usr/lib/python2.4/string.py", line 292, in split
return s.split(sep, maxsplit)
exceptions.AttributeError: 'NoneType' object has no attribute 'split'
18:55 EST [-] Received SIGINT, shutting down.
18:55 EST [-] Main loop terminated.
18:55 EST [-] Server Shut Down.
exarkun@boson:~/mail/tutorial/smtpclient$
</pre></code></blockquote>
<p>What happened? Those first two arguments to <code>TCPClient</code>
turned out to be important after all. We'll get to them in the next
example.</p>
<h3>SMTP Client 3</h3>
<p>Version three of our SMTP client only changes one thing. The line
from version two:</p>
<blockquote><code>
smtpClientService = internet.TCPClient(None, None, smtpClientFactory)
</code></blockquote>
<p>has its first two arguments changed from <code>None</code> to
something with a bit more meaning:</p>
<blockquote><code>
smtpClientService = internet.TCPClient('localhost', 25, smtpClientFactory)
</code></blockquote>
<p>This directs the client to connect to <em>localhost</em> on port
<em>25</em>. This isn't the address we want ultimately, but it's a
good place-holder for the time being. We can run <a
href="smtpclient-3.tac">smtpclient-3.tac</a> and see what this change
gets us:</p>
<blockquote><code><pre class="shell">
exarkun@boson:~/mail/tutorial/smtpclient$ twistd -ny smtpclient-3.tac
19:10 EST [-] Log opened.
19:10 EST [-] twistd SVN-Trunk (/usr/bin/python2.4 2.4.1) starting up
19:10 EST [-] reactor class: twisted.internet.selectreactor.SelectReactor
19:10 EST [-] Loading smtpclient-3.tac...
19:10 EST [-] Loaded.
19:10 EST [-] Starting factory <twisted.internet.protocol.ClientFactory
instance at 0xb791e48c>
19:10 EST [-] Enabling Multithreading.
19:10 EST [Uninitialized] Traceback (most recent call last):
File "twisted/python/log.py", line 56, in callWithLogger
return callWithContext({"system": lp}, func, *args, **kw)
File "twisted/python/log.py", line 41, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "twisted/python/context.py", line 52, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "twisted/python/context.py", line 31, in callWithContext
return func(*args,**kw)
--- <exception caught here> ---
File "twisted/internet/selectreactor.py", line 139, in _doReadOrWrite
why = getattr(selectable, method)()
File "twisted/internet/tcp.py", line 543, in doConnect
self._connectDone()
File "twisted/internet/tcp.py", line 546, in _connectDone
self.protocol = self.connector.buildProtocol(self.getPeer())
File "twisted/internet/base.py", line 641, in buildProtocol
return self.factory.buildProtocol(addr)
File "twisted/internet/protocol.py", line 99, in buildProtocol
p = self.protocol()
exceptions.TypeError: 'NoneType' object is not callable
19:10 EST [Uninitialized] Stopping factory
<twisted.internet.protocol.ClientFactory instance at
0xb791e48c>
19:10 EST [-] Received SIGINT, shutting down.
19:10 EST [-] Main loop terminated.
19:10 EST [-] Server Shut Down.
exarkun@boson:~/mail/tutorial/smtpclient$
</pre></code></blockquote>
<p>A meagre amount of progress, but the service still raises an
exception. This time, it's because we haven't specified a
<em>protocol class</em> for the factory to use. We'll do that in the
next example.</p>
<h3>SMTP Client 4</h3>
<p>In the previous example, we ran into a problem because we hadn't
set up our <em>client factory's</em> <em>protocol</em> attribute
correctly (or at all). <code>ClientFactory.buildProtocol</code> is
the method responsible for creating a <em>protocol instance</em>. The
default implementation calls the factory's <code>protocol</code> attribute,
adds itself as an attribute named <code>factory</code> to the
resulting instance, and returns it. In <a
href="smtpclient-4.tac">smtpclient-4.tac</a>, we'll correct the
oversight that caused the traceback in smtpclient-3.tac:</p>
<blockquote><code>
smtpClientFactory.protocol = protocol.Protocol
</code></blockquote>
<p>Running this version of the client, we can see the output is once
again traceback free:</p>
<blockquote><code><pre class="shell">
exarkun@boson:~/doc/mail/tutorial/smtpclient$ twistd -ny smtpclient-4.tac
19:29 EST [-] Log opened.
19:29 EST [-] twistd SVN-Trunk (/usr/bin/python2.4 2.4.1) starting up
19:29 EST [-] reactor class: twisted.internet.selectreactor.SelectReactor
19:29 EST [-] Loading smtpclient-4.tac...
19:29 EST [-] Loaded.
19:29 EST [-] Starting factory <twisted.internet.protocol.ClientFactory
instance at 0xb791e4ac>
19:29 EST [-] Enabling Multithreading.
19:29 EST [-] Received SIGINT, shutting down.
19:29 EST [Protocol,client] Stopping factory
<twisted.internet.protocol.ClientFactory instance at
0xb791e4ac>
19:29 EST [-] Main loop terminated.
19:29 EST [-] Server Shut Down.
exarkun@boson:~/doc/mail/tutorial/smtpclient$
</pre></code></blockquote>
<p>But what does this mean?
<code>twisted.internet.protocol.Protocol</code> is the base
<em>protocol</em> implementation. For those familiar with the classic
UNIX network services, it is equivalent to the <em>discard</em>
service. It never produces any output and it discards all its input.
Not terribly useful, and certainly nothing like an SMTP client. Let's
see how we can improve this in the next example.</p>
<h3>SMTP Client 5</h3>
<p>In <a href="smtpclient-5.tac">smtpclient-5.tac</a>, we will begin
to use Twisted's SMTP protocol implementation for the first time.
We'll make the obvious change, simply swapping out
<code>twisted.internet.protocol.Protocol</code> in favor of
<code>twisted.mail.smtp.ESMTPClient</code>. Don't worry about the
<em>E</em> in <em>ESMTP</em>. It indicates we're actually using a
newer version of the SMTP protocol. There is an
<code>SMTPClient</code> in Twisted, but there's essentially no reason
to ever use it.</p>
<p>smtpclient-5.tac adds a new import:</p>
<blockquote><code>
from twisted.mail import smtp
</code></blockquote>
<p>All of the mail related code in Twisted exists beneath the
<code>twisted.mail</code> package. More specifically, everything
having to do with the SMTP protocol implementation is defined in the
<code>twisted.mail.smtp</code> module.</p>
<p>Next we remove a line we added in smtpclient-4.tac:</p>
<blockquote><code>
smtpClientFactory.protocol = protocol.Protocol
</code></blockquote>
<p>And add a similar one in its place:</p>
<blockquote><code>
smtpClientFactory.protocol = smtp.ESMTPClient
</code></blockquote>
<p>Our client factory is now using a protocol implementation which
behaves as an SMTP client. What happens when we try to run this
version?</p>
<blockquote><code><pre class="shell">
exarkun@boson:~/doc/mail/tutorial/smtpclient$ twistd -ny smtpclient-5.tac
19:42 EST [-] Log opened.
19:42 EST [-] twistd SVN-Trunk (/usr/bin/python2.4 2.4.1) starting up
19:42 EST [-] reactor class: twisted.internet.selectreactor.SelectReactor
19:42 EST [-] Loading smtpclient-5.tac...
19:42 EST [-] Loaded.
19:42 EST [-] Starting factory <twisted.internet.protocol.ClientFactory
instance at 0xb791e54c>
19:42 EST [-] Enabling Multithreading.
19:42 EST [Uninitialized] Traceback (most recent call last):
File "twisted/python/log.py", line 56, in callWithLogger
return callWithContext({"system": lp}, func, *args, **kw)
File "twisted/python/log.py", line 41, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "twisted/python/context.py", line 52, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "twisted/python/context.py", line 31, in callWithContext
return func(*args,**kw)
--- <exception caught here> ---
File "twisted/internet/selectreactor.py", line 139, in _doReadOrWrite
why = getattr(selectable, method)()
File "twisted/internet/tcp.py", line 543, in doConnect
self._connectDone()
File "twisted/internet/tcp.py", line 546, in _connectDone
self.protocol = self.connector.buildProtocol(self.getPeer())
File "twisted/internet/base.py", line 641, in buildProtocol
return self.factory.buildProtocol(addr)
File "twisted/internet/protocol.py", line 99, in buildProtocol
p = self.protocol()
exceptions.TypeError: __init__() takes at least 2 arguments (1 given)
19:42 EST [Uninitialized] Stopping factory
<twisted.internet.protocol.ClientFactory instance at
0xb791e54c>
19:43 EST [-] Received SIGINT, shutting down.
19:43 EST [-] Main loop terminated.
19:43 EST [-] Server Shut Down.
exarkun@boson:~/doc/mail/tutorial/smtpclient$
</pre></code></blockquote>
<p>Oops, back to getting a traceback. This time, the default
implementation of <code>buildProtocl</code> seems no longer to be
sufficient. It instantiates the protocol with no arguments, but
<code>ESMTPClient</code> wants at least one argument. In the next
version of the client, we'll override <code>buildProtocol</code> to
fix this problem.</p>
<h3>SMTP Client 6</h3>
<p><a href="smtpclient-6.tac">smtpclient-6.tac</a> introduces a
<code>twisted.internet.protocol.ClientFactory</code> subclass with an
overridden <code>buildProtocol</code> method to overcome the problem
encountered in the previous example.</p>
<blockquote><code><pre class="python">
class SMTPClientFactory(protocol.ClientFactory):
protocol = smtp.ESMTPClient
def buildProtocol(self, addr):
return self.protocol(secret=None, identity='example.com')
</pre></code></blockquote>
<p>The overridden method does almost the same thing as the base
implementation: the only change is that it passes values for two
arguments to <code>twisted.mail.smtp.ESMTPClient</code>'s initializer. The <code>secret</code> argument is used for SMTP authentication (which we will not attempt yet). The <code>identity</code> argument is used as a to identify ourselves
Another minor change to note is that the <code>protocol</code>
attribute is now defined in the class definition, rather than tacked
onto an instance after one is created. This means it is a class
attribute, rather than an instance attribute, now, which makes no
difference as far as this example is concerned. There are
circumstances in which the difference is important: be sure you
understand the implications of each approach when creating your own
factories.</p>
<p>One other change is required: instead of instantiating <code>twisted.internet.protocol.ClientFactory</code>, we will now instantiate <code>SMTPClientFactory</code>:</p>
<blockquote><code>
smtpClientFactory = SMTPClientFactory()
</code></blockquote>
<p>Running this version of the code, we observe that the code
<strong>still</strong> isn't quite traceback-free.</p>
<blockquote><code><pre class="shell">
exarkun@boson:~/doc/mail/tutorial/smtpclient$ twistd -ny smtpclient-6.tac
21:17 EST [-] Log opened.
21:17 EST [-] twistd SVN-Trunk (/usr/bin/python2.4 2.4.1) starting up
21:17 EST [-] reactor class: twisted.internet.selectreactor.SelectReactor
21:17 EST [-] Loading smtpclient-6.tac...
21:17 EST [-] Loaded.
21:17 EST [-] Starting factory <__builtin__.SMTPClientFactory instance
at 0xb77fd68c>
21:17 EST [-] Enabling Multithreading.
21:17 EST [ESMTPClient,client] Traceback (most recent call last):
File "twisted/python/log.py", line 56, in callWithLogger
return callWithContext({"system": lp}, func, *args, **kw)
File "twisted/python/log.py", line 41, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "twisted/python/context.py", line 52, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "twisted/python/context.py", line 31, in callWithContext
return func(*args,**kw)
--- <exception caught here> ---
File "twisted/internet/selectreactor.py", line 139, in _doReadOrWrite
why = getattr(selectable, method)()
File "twisted/internet/tcp.py", line 351, in doRead
return self.protocol.dataReceived(data)
File "twisted/protocols/basic.py", line 221, in dataReceived
why = self.lineReceived(line)
File "twisted/mail/smtp.py", line 1039, in lineReceived
why = self._okresponse(self.code,'\n'.join(self.resp))
File "twisted/mail/smtp.py", line 1281, in esmtpState_serverConfig
self.tryTLS(code, resp, items)
File "twisted/mail/smtp.py", line 1294, in tryTLS
self.authenticate(code, resp, items)
File "twisted/mail/smtp.py", line 1343, in authenticate
self.smtpState_from(code, resp)
File "twisted/mail/smtp.py", line 1062, in smtpState_from
self._from = self.getMailFrom()
File "twisted/mail/smtp.py", line 1137, in getMailFrom
raise NotImplementedError
exceptions.NotImplementedError:
21:17 EST [ESMTPClient,client] Stopping factory
<__builtin__.SMTPClientFactory instance at 0xb77fd68c>
21:17 EST [-] Received SIGINT, shutting down.
21:17 EST [-] Main loop terminated.
21:17 EST [-] Server Shut Down.
exarkun@boson:~/doc/mail/tutorial/smtpclient$
</pre></code></blockquote>
<p>What we have accomplished with this iteration of the example is to
navigate far enough into an SMTP transaction that Twisted is now
interested in calling back to application-level code to determine what
its next step should be. In the next example, we'll see how to
provide that information to it.</p>
<h3>SMTP Client 7</h3>
<p>SMTP Client 7 is the first version of our SMTP client which
actually includes message data to transmit. For simplicity's sake,
the message is defined as part of a new class. In a useful program
which sent email, message data might be pulled in from the filesystem,
a database, or be generated based on user-input. <a
href="smtpclient-7.tac">smtpclient-7.tac</a>, however, defines a new
class, <code>SMTPTutorialClient</code>, with three class attributes
(<code>mailFrom</code>, <code>mailTo</code>, and
<code>mailData</code>):</p>
<blockquote><code><pre class="python">
class SMTPTutorialClient(smtp.ESMTPClient):
mailFrom = "tutorial_sender@example.com"
mailTo = "tutorial_recipient@example.net"
mailData = '''\
Date: Fri, 6 Feb 2004 10:14:39 -0800
From: Tutorial Guy <tutorial_sender@example.com>
To: Tutorial Gal <tutorial_recipient@example.net>
Subject: Tutorate!
Hello, how are you, goodbye.
'''
</pre></code></blockquote>
<p>This statically defined data is accessed later in the class
definition by three of the methods which are part of the
<em>SMTPClient callback API</em>. Twisted expects each of the three
methods below to be defined and to return an object with a particular
meaning. First, <code>getMailFrom</code>:</p>
<blockquote><code><pre class="python">
def getMailFrom(self):
result = self.mailFrom
self.mailFrom = None
return result
</pre></code></blockquote>
<p>This method is called to determine the <em>reverse-path</em>,
otherwise known as the <em>envelope from</em>, of the message. This
value will be used when sending the <code>MAIL FROM</code> SMTP
command. The method must return a string which conforms to the <a
href="http://www.faqs.org/rfcs/rfc2821.html">RFC 2821</a> definition
of a <em>reverse-path</em>. In simpler terms, it should be a string
like <code>"alice@example.com"</code>. Only one <em>envelope
from</em> is allowed by the SMTP protocol, so it cannot be a list of
strings or a comma separated list of addresses. Our implementation
of <code>getMailFrom</code> does a little bit more than just return a
string; we'll get back to this in a little bit.</p>
<p>The next method is <code>getMailTo</code>:</p>
<blockquote><code><pre class="python">
def getMailTo(self):
return [self.mailTo]
</pre></code></blockquote>
<p><code>getMailTo</code> is similar to <code>getMailFrom</code>. It
returns one or more RFC 2821 addresses (this time a
<em>forward-path</em>, or <em>envelope to</em>). Since SMTP allows
multiple recipients, <code>getMailTo</code> returns a list of these
addresses. The list must contain at least one address, and even if
there is exactly one recipient, it must still be in a list.</p>
<p>The final callback we will define to provide information to
Twisted is <code>getMailData</code>:</p>
<blockquote><code><pre class="python">
def getMailData(self):
return StringIO.StringIO(self.mailData)
</pre></code></blockquote>
<p>This one is quite simple as well: it returns a file or a file-like
object which contains the message contents. In our case, we return a
<code>StringIO</code> since we already have a string containing our
message. If the contents of the file returned by
<code>getMailData</code> span multiple lines (as email messages often
do), the lines should be <code>\n</code> delimited (as they would be
when opening a text file in the <code>"rt"</code> mode): necessary
newline translation will be performed by <code>SMTPClient</code>
automatically.</p>
<p>There is one more new callback method defined in smtpclient-7.tac.
This one isn't for providing information about the messages to
Twisted, but for Twisted to provide information about the success or
failure of the message transmission to the application:</p>
<blockquote><code><pre class="python">
def sentMail(self, code, resp, numOk, addresses, log):
print 'Sent', numOk, 'messages'
</pre></code></blockquote>
<p>Each of the arguments to <code>sentMail</code> provides some
information about the success or failure of the message transmission
transaction. <code>code</code> is the response code from the ultimate
command. For successful transactions, it will be 250. For transient
failures (those which should be retried), it will be between 400 and
499, inclusive. For permanent failures (this which will never work,
no matter how many times you retry them), it will be between 500 and
599.</p>
<h3>SMTP Client 8</h3>
<p>Thus far we have succeeded in creating a Twisted client application
which starts up, connects to a (possibly) remote host, transmits some
data, and disconnects. Notably missing, however, is application
shutdown. Hitting ^C is fine during development, but it's not exactly
a long-term solution. Fortunately, programmatic shutdown is extremely
simple. <a href="smtpclient-8.tac">smtpclient-8.tac</a> extends
<code>sentMail</code> with these two lines:</p>
<blockquote><code><pre class="python">
from twisted.internet import reactor
reactor.stop()
</pre></code></blockquote>
<p>The <code>stop</code> method of the reactor causes the main event
loop to exit, allowing a Twisted server to shut down. With this
version of the example, we see that the program actually terminates
after sending the message, without user-intervention:</p>
<blockquote><code><pre class="shell">
exarkun@boson:~/doc/mail/tutorial/smtpclient$ twistd -ny smtpclient-8.tac
19:52 EST [-] Log opened.
19:52 EST [-] twistd SVN-Trunk (/usr/bin/python2.4 2.4.1) starting up
19:52 EST [-] reactor class: twisted.internet.selectreactor.SelectReactor
19:52 EST [-] Loading smtpclient-8.tac...
19:52 EST [-] Loaded.
19:52 EST [-] Starting factory <__builtin__.SMTPClientFactory instance
at 0xb791beec>
19:52 EST [-] Enabling Multithreading.
19:52 EST [SMTPTutorialClient,client] Sent 1 messages
19:52 EST [SMTPTutorialClient,client] Stopping factory
<__builtin__.SMTPClientFactory instance at 0xb791beec>
19:52 EST [-] Main loop terminated.
19:52 EST [-] Server Shut Down.
exarkun@boson:~/doc/mail/tutorial/smtpclient$
</pre></code></blockquote>
<h3>SMTP Client 9</h3>
<p>One task remains to be completed in this tutorial SMTP client:
instead of always sending mail through a well-known host, we will look
up the mail exchange server for the recipient address and try to
deliver the message to that host.</p>
<p>In <a href="smtpclient-9.tac">smtpclient-9.tac</a>, we'll take the
first step towards this feature by defining a function which returns
the mail exchange host for a particular domain:</p>
<blockquote><code><pre class="python">
def getMailExchange(host):
return 'localhost'
</pre></code></blockquote>
<p>Obviously this doesn't return the correct mail exchange host yet
(in fact, it returns the exact same host we have been using all
along), but pulling out the logic for determining which host to
connect to into a function like this is the first step towards our
ultimate goal. Now that we have <code>getMailExchange</code>, we'll
call it when constructing our <code>TCPClient</code> service:</p>
<blockquote><code><pre class="python">
smtpClientService = internet.TCPClient(
getMailExchange('example.net'), 25, smtpClientFactory)
</pre></code></blockquote>
<p>We'll expand on the definition of <code>getMailExchange</code> in
the next example.</p>
<h3>SMTP Client 10</h3>
<p>In the previous example we defined <code>getMailExchange</code> to
return a string representing the mail exchange host for a particular
domain. While this was a step in the right direction, it turns out
not to be a very big one. Determining the mail exchange host for a
particular domain is going to involve network traffic (specifically,
some DNS requests). These might take an arbitrarily large amount of
time, so we need to introduce a <code>Deferred</code> to represent the
result of <code>getMailExchange</code>. <a
href="smtpclient-10.tac">smtpclient-10.tac</a> redefines it
thusly:</p>
<blockquote><code><pre class="python">
def getMailExchange(host):
return defer.succeed('localhost')
</pre></code></blockquote>
<p><code>defer.succeed</code> is a function which creates a new
<code>Deferred</code> which already has a result, in this case
<code>'localhost'</code>. Now we need to adjust our
<code>TCPClient</code>-constructing code to expect and properly handle
this <code>Deferred</code>:</p>
<blockquote><code><pre class="python">
def cbMailExchange(exchange):
smtpClientFactory = SMTPClientFactory()
smtpClientService = internet.TCPClient(exchange, 25, smtpClientFactory)
smtpClientService.setServiceParent(application)
getMailExchange('example.net').addCallback(cbMailExchange)
</pre></code></blockquote>
<p>An in-depth exploration of <code>Deferred</code>s is beyond the
scope of this document. For such a look, see the <a href="">Deferred
Execution Howto</a>. However, in brief, what this version of the code
does is to delay the creation of the <code>TCPClient</code> until the
<code>Deferred</code> returned by <code>getMailExchange</code> fires.
Once it does, we proceed normally through the creation of our
<code>SMTPClientFactory</code> and <code>TCPClient</code>, as well as
set the <code>TCPClient</code>'s service parent, just as we did in the
previous examples.</p>
<h3>SMTP Client 11</h3>
<p>At last we're ready to perform the mail exchange lookup. We do
this by calling on an object provided specifically for this task,
<code>twisted.mail.relaymanager.MXCalculator</code>:</p>
<blockquote><code><pre class="python">
def getMailExchange(host):
def cbMX(mxRecord):
return str(mxRecord.exchange)
return relaymanager.MXCalculator().getMX(host).addCallback(cbMX)
</pre></code></blockquote>
<p>Because <code>getMX</code> returns a <code>Record_MX</code> object
rather than a string, we do a little bit of post-processing to get the
results we want. We have already converted the rest of the tutorial
application to expect a <code>Deferred</code> from
<code>getMailExchange</code>, so no further changes are required. <a
href="smtpclient-11.tac">smtpclient-11.tac</a> completes this tutorial
by being able to both look up the mail exchange host for the recipient
domain, connect to it, complete an SMTP transaction, report its
results, and finally shut down the reactor.</p>
<h3>Conclusion</h3>
<p>XXX wrap it up</p>
</body>
</html>
|