Learning Python Network Programming

(Sean Pound) #1
Chapter 4
msg['To'] = recipient
msg['From'] = sender
subject = input('Enter your email subject: ')
msg['Subject'] = subject
message = input('Enter your email message. Press Enter when
finished. ')
part = MIMEText('text', "plain")
part.set_payload(message)
msg.attach(part)
# create smtp session
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
#session.set_debuglevel(1)
# send mail
session.sendmail(sender, recipient, msg.as_string())
print("You email is sent to {0}.".format(recipient))
session.quit()

if __name__ == '__main__':
sender = input("Enter sender email address: ")
recipient = input("Enter recipient email address: ")
send_email(sender, recipient)

If you run this script, then you can see that the output is similar to what is mentioned
here. For the sake of anonymity, real e-mail addresses have not been shown in the
following example:


$ python3 smtp_mail_sender.py


Enter sender email address: @gmail.com


Enter recipeint email address: @gmail.com


Enter your email subject: Test mail


Enter your email message. Press Enter when finished. This message can be
ignored


You email is sent to @gmail.com.


This script will send a very simple e-mail message by using Python's standard library
module, smtplib. For composing the message, MIMEMultipart and MIMEText
classes have been imported from the email.mime submodule. This submodule
has various types of classes for composing e-mail messages with different types of
attachments, for example, MIMEApplication(), MIMEAudio(), MIMEImage(), and
so on.

Free download pdf