Learning Python Network Programming

(Sean Pound) #1

Engaging with E-mails


In this example, the send_mail() function has been called by two arguments: sender
and receiver. Both of these arguments are e-mail addresses. An e-mail message is
constructed by the MIMEMultipart() message class. The essential headers, such as
To, From, and Subject have been added to this class namespace. The body of the
message is composed with the instance of the MIMEText() class. This is done by the
class set_payload() method. Then, this payload is attached to the main message by
the attach() method.


In order to communicate with the SMTP server, a session with the server will be
created by instantiating the smtplib module's SMTP() class. The server name and the
port arguments will be passed to the constructor. According to the SMTP protocol,
an extended hello message through ehlo() method will be sent by the client to the
server. The message will be sent by the sendmail() method.


Notice that if the set_debuglevel() method is called on an SMTP session object,
then it will produce additional debug messages. The line is commented out in the
preceding example. Un-commenting that line will produce a debug message such as:


$ python3 smtp_mail_sender.py


Enter sender email address: @gmail.com


Enter recipeint email address: @gmail.com


Enter your email subject: Test email


Enter your email message. Press Enter when finished. This is a test email


send: 'mail FROM:[email protected] size=339\r\n'


reply: b'250 2.1.0 OK hg2si4622244wib.38 - gsmtp\r\n'


reply: retcode (250); Msg: b'2.1.0 OK hg2si4622244wib.38 - gsmtp'


send: 'rcpt TO:[email protected]\r\n'


reply: b'250 2.1.5 OK hg2si4622244wib.38 - gsmtp\r\n'


reply: retcode (250); Msg: b'2.1.5 OK hg2si4622244wib.38 - gsmtp'


send: 'data\r\n'


reply: b'354 Go ahead hg2si4622244wib.38 - gsmtp\r\n'


reply: retcode (354); Msg: b'Go ahead hg2si4622244wib.38 - gsmtp'


data: (354, b'Go ahead hg2si4622244wib.38 - gsmtp')


send: 'Content-Type: multipart/mixed;
boundary="===============1431208306=="\r\nMIME-Version: 1.0\r\nTo:
[email protected]\r\nFrom: [email protected]\r\nSubject: Test
email\r\n\r\n--===============1431208306==\r\nContent-Type:
text/plain; charset="us-ascii"\r\nMIME-Version: 1.0\r\nContent-
Transfer-Encoding: 7bit\r\n\r\nThis is a test email\r\n--
===============1431208306==--\r\n.\r\n'

Free download pdf