INTERNET CLIENT PROGRAMMING USING PYTHON C U A U H T E M O C C A R B A J A L I T E S M C E M A P R I L 0 6 , 2 0 1 3 1
INTRODUCTION • In the previous lecture we took a look at low-level networking communication protocols using sockets. • This type of networking is at the heart of most of the client/server protocols that exist on the Internet today (FTP, NNTP, SMTP, POP3, IMAP, etc.). • These protocols work in a way much like the client/server examples of the previous lecture. • The only difference is that now we have taken lower-level protocols such as TCP/IP and created newer, more specific protocols on top of them to implement these higher-level services. 2
NETWORK CLIENT LIBRARIES • Python offers a rich variety of network client code • Email: smtplib , poplib , imaplib • rfc822 and email modules handle content • File transfer: ftplib • Web: httplib , urllib • More on these later • Network news: nntplib • Telnet: telnetlib 3
GENERAL CLIENT STRATEGY • Library usually defines an object class • Create an instance of the object to interact with the server • Call the instance's methods to request particular interactions 4
USING SMTPLIB • s = smtplib.SMTP([host[, port]]) • Create SMTP object with given connection parameters • r = s.sendmail(from, to, msg [, mopts[, ropts]]) • from : sender address • to : list of recipient addresses • msg : RFC822-formatted message (including all necessary headers) • mopts, ropts : ESMTP option lists 5
SMTP EXAMPLE import smtplib, socket frad = "sholden@holdenweb.com" toads = ["bookuser@holdenweb.com", "nosuchuser@holdenweb.com", "sholden@holdenweb.com"] msg = """To: Various recipients From: Steve Holden <sholden@holdenweb.com> Hello. This is an RFC822 mail message. """ 6
SMTP EXAMPLE (CONT) try: server = smtplib.SMTP('10.0.0.1') result = server.sendmail(frad, toads, msg) server.quit() if result: for r in result.keys(): print "Error sending to", r rt = result[r] print "Code", rt[0], ":", rt[1] else: print "Sent without errors" except smtplib.SMTPException, arg: print "Server could not send mail", arg 7
SENDING EMAILS FROM THE RASPBERRY PI • There are many cases when it can be very useful to be able to send emails from the Raspberry Pi to arbitrary recipients. • This is not the same as having a real MTA running on the Pi (like Sendmail, Postfix, Exim, QMail, etc.), which can also receive and store emails. • In the following we are only going to cover the possibility of sending emails, not receiving. • In most cases this is enough, as people tend to use GMail, Yahoo! Mail and other major email service providers and they store their emails on the servers of these providers. • Still, sending out emails from the Raspberry Pi can come in handy in many situations. 8
SENDING EMAILS FROM THE RASPBERRY PI (CONT) • You could have some sensors connected to the GPIO pins of the Pi and you could program the Pi to send you an email • when the temperature in the room rises above or drops below certain threshold values, • when a gas sensor registers unwanted gas leaks or • when the measured voltage of a monitored battery becomes too low. • You could also have your Pi send you daily or weekly emails with summarized system data. • Or maybe you could connect a webcam to the Raspberry Pi and set up some motion detection software, which would send you an email as soon as it detects motion in a given area of your house. • Maybe you are hosting a WordPress website on your Raspberry Pi and you would like to provide your readers with the possibility to subscribe to the posts. • This all means that the Pi needs to be able to send out emails. 9
PYTHON SENDING EMAIL USING SMTP • Simple Mail Transfer Protocol (SMTP) is a protocol which handles sending e-mail and routing e-mail between mail servers. • Python provides smtplib module which defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon. • For normal use, you should only require the initialization/connect, sendmail(), and quit() methods. An example is included below. 10
PYTHON SENDING EMAIL USING SMTP • Here is a simple syntax to create one SMTP object which can later be used to send an email: import smtplib smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] ) • Parameters: • host: This is the host running your SMTP server. You can specify the host’s IP address or a domain name like tutorialspoint.com. This is optional argument. • port: If you are providing host argument then you need to specify a port where SMTP server is listening. Usually this port would be 25. • local_hostname : If your SMTP server is running on your local machine then you can specify just localhost as of this option. 11
SENDMAIL SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]) • Arguments: • an RFC 822 from-address string, • a list of RFC 822 to-address strings (a bare string will be treated as a list with 1 address), • and a message string. • The caller may pass a list of ESMTP options (such as 8bitmime) to be used in MAIL FROM commands as mail_options. • ESMTP options (such as DSN commands) that should be used with all RCPT commands can be passed as rcpt_options. (If you need to use different ESMTP options to different recipients you have to use the low-level methods such as mail(), rcpt() and data() to send the message.) 12
EHLO SMTP.ehlo([hostname]) • Identify yourself to an ESMTP server using EHLO. • The hostname argument defaults to the fully qualified domain name of the local host. Examine the response for ESMTP option and store them for use by has_extn(). Also sets several informational attributes: the message returned by the server is stored as the ehlo_resp attribute, does_esmtp is set to true or false depending on whether the server supports ESMTP, and esmtp_features will be a dictionary containing the names of the SMTP service extensions this server supports, and their parameters (if any). • Unless you wish to use has_extn() before sending mail, it should not be necessary to call this method explicitly. It will be implicitly called by sendmail() when necessary. 13
STARTTLS SMTP.starttls([keyfile[, certfile]]) • Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP commands that follow will be encrypted. You should then call ehlo() again. • If keyfile and certfile are provided, these are passed to the socket module’s ssl() function. • If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. 14
STMPLIB EXAMPLE import smtplib to = 'carbajal@itesm.mx' gmail_user = 'carbajal.cuauhtemoc@gmail.com' gmail_pwd = '28/Julio/1955' smtpserver = smtplib.SMTP("smtp.gmail.com",587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo smtpserver.login(gmail_user, gmail_pwd) header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:testing \n' print header msg = header + '\n this is test msg from my RPi \n\n' smtpserver.sendmail(gmail_user, to, msg) print 'done!' smtpserver.close() 15 email-example2.py
PIR MOVEMENT DETECTOR • A PIR movement detector and an Arduino are used to have the Arduino communicate with a Python program running on a computer (or RPi) to send an email whenever movement is detected by the sensor. http://learn.adafruit.com/arduino-lesson-17-email-sending-movement-detector 16
ARDUINO SETUP 17
ARDUINO CODE int pirPin = 7; int minSecsBetweenEmails = 60; // 1 min long lastSend = -minSecsBetweenEmails * 1000l; void setup() { pinMode(pirPin, INPUT); Serial.begin(9600); } 18
ARDUINO CODE (CONT) void loop() { long now = millis(); if (digitalRead(pirPin) == HIGH) { if (now > (lastSend + minSecsBetweenEmails * 1000l)) { Serial.println("MOVEMENT"); lastSend = now; } else { Serial.println("Too soon"); } } delay(500); } 19
PYTHON CODE import time import serial import smtplib TO = 'putyour@email.here' GMAIL_USER = 'putyour@email.here' GMAIL_PASS = 'putyourpasswordhere' SUBJECT = 'Intrusion!!' TEXT = 'Your PIR sensor detected movement' ser = serial.Serial('/dev/ttyACM0', 9600) 20
PYTHON CODE (CONT) def send_email(): print("Sending Email") smtpserver = smtplib.SMTP("smtp.gmail.com",587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo smtpserver.login(GMAIL_USER, GMAIL_PASS) header = 'To:' + TO + '\n' + 'From: ' + GMAIL_USER header = header + '\n' + 'Subject:' + SUBJECT + '\n‘ print header msg = header + '\n' + TEXT + ' \n\n‘ smtpserver.sendmail(GMAIL_USER, TO, msg) smtpserver.close() 21
PYTHON CODE (CONT) while True: message = ser.readline() print(message) if message[0] == 'M' : send_email() time.sleep(0.5) 22
Recommend
More recommend