Announcement

Collapse
No announcement yet.

Send emails via your Gmail account

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Send emails via your Gmail account

    Here's an example of how to send emails from the PremierWave using your Gmail account and Gmail's SMTP server. This will parse the serial port for the details of the email you want to send. There's no checking to see if the serial port is being used for something else (like the tunnel), so use at your own risk!

    Code:
    #!/usr/bin/python
    
    import serial
    import socket
    import smtplib
    
    from time import sleep
    
    
    def SendEmail(sender,recepient,subject,passwd,msg):
    	smtpserver = 'smtp.gmail.com'
    	smtpport = 587
    	
    	s = smtplib.SMTP(smtpserver, smtpport)
    	s.ehlo()
    	s.starttls()
    	s.ehlo()
    	s.login(sender,passwd)
    	s.sendmail(sender,recepient, 'To: ' + recepient + '\n' + 'From: ' + sender + '\n' + 'Subject: ' + subject + '\n\n' + msg + '\n\n')
    	s.close()
    
    def receive_line(ser):
    	buffer = ''
    	
    	while True:
    		buffer = buffer + ser.read(ser.inWaiting())
    		sleep(0.5)
    		
    		if '\r' in buffer:
    			lines = buffer.split('\r')
    			return lines[-2]			
    
    	
    			
    def main():
    	port = '/dev/ttyS1'
    	baud = 9600
    	timeout = 30
    	
    	sleep 10
    	
    	while True:
    		try:
    			sockstat = True
    			socket.setdefaulttimeout(float(timeout))
    		except Exception:
    			sockstat = False
    		
    		if sockstat:
    			break
    			
    	ser = serial.Serial(port, baud)
    	
    	ser.write('Welcome to the serial emailer!\n\r')
    	ser.write('Please enter your Gmail email address (as sender)\n\r')
    	sender = receive_line(ser)
    	ser.write('From: ' + sender + '\n\rNow enter your Gmail password\n\r')
    	passwd = receive_line(ser)
    	ser.write('Got it, now enter the recepient of the email\n\r')
    	recepient = receive_line(ser)
    	ser.write('To: ' + recepient + '\n\rAlmost done here, enter a Subject for your email\n\r')
    	subject = receive_line(ser)
    	ser.write('Subject: ' + subject + '\n\rNow enter the body of the message. Finish with a blank line\n\r')
    	
    	msg = ''
    	
    	while True:
    		line = receive_line(ser)
    	
    		if line == '':
    			SendEmail(sender,recepient,subject,passwd,msg)
    			ser.write("Email sent, I'm done!\n\r")
    			break
    		else:
    			msg = msg + line + '\n'
    		
    			
    	ser.close()
    
    if __name__ == "__main__":
    	main()
Working...
X