Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

import ssl import socket import base64 class SMTP: """ Implements a basic smtp exchange the class

is initialized with the smtp server and port number used in the exchange. Capabilites: Sending a message from a sender to a recipient instance.send_mail(sender,recipient,msg) Interface: send_mail(sender, recipient, message) message must be a: string recipient must be of the form: user_name@domain sender must of of the form : user_name@domain """ def __init__(self, smtp_server,port=25): self.server = smtp_server self.port = port def get(self,socket,confirmation,error_code): buff = socket.recv(10000) if(int(buff[:3])!=confirmation): print buff return error_code return 0 def send_mail(self,sender,recipient,msg="This program rocks!"): """Sends a message from sender to recipient via the smtp protocal using the server:port defined in the initialization of the instance """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((self.server,self.port)) except e: print e return -1 s.sendall("HELO "+sender.split('@')[1]) res = self.get(s,220,-1) if res!=0: return res s.sendall("STARTTLS") secure_s = ssl.wrap_socket(s,ssl_version=ssl.PROTOCOL_SSLv23) res = self.get(secure_s,220,-1) if res!=0: return res secure_s.sendall("MAIL FROM:<"+sender+">") res = self.get(secure_s,250,-1) if res!=0: return res secure_s.sendall("RCPT TO:<"+recipient+">") res = self.get(secure_s,250,-1) if res!=0: return res secure_s.sendall("FROM: "+sender+"\nTo: "+recipient+"\n"+msg+"\n.") res = self.get(secure_s,250,-1) if res!=0: return res

secure_s.sendall("QUIT") res = self.get(secure_s,250,-1) if res!=0: return res s.close() return 0 def main(): smtp = SMTP("smtp.googlemail.com",25) print smtp.send_mail("moshe@greenraanana.com","mgmoshes@gmail.com") if __name__=="__main__": main()

You might also like