Had some requirement to send mails in my project, so we were digging into the smtplib module. Thought of trying out a small script which will send mails. The example code was fine, but modified the functions and added “Subject: ” header to it. Tested it and voila it sent mails 😛 A rather trivial piece of code, but posting it to save it somewhere in my web space 😉
#!/usr/bin/env python """Command-line SMTP Mail Sender This script can send mails provided you have an account with an SMTP server. The inputs have to be given at the command line. The recepients address can be a space separated list of emails. The subject can be multiple lines, seperated by empty lines. When done, end the subject with Ctrl+D to send the mail. """ import smtplib # function to fetch the input from command line def prompt(prompt): return raw_input(prompt).strip() fromaddr = prompt("From: ") toaddrs = prompt("To: ").split() subject = prompt("Subject: ") print "Enter message, end with ^D (Unix):" # Add the From: and To: headers at the start msg = ("From: %snTo: %snSubject: %snn" %(fromaddr, ", ".join(toaddrs), subject)) while 1: try: line = raw_input() except EOFError: break if not line: break msg = msg + line print "Message length is " +repr(len(msg)) # connect and send the mail server = smtplib.SMTP() # connects to default port, if not specify it as additional argument server.connect('mail.myhost.com') # specify username and password server.login('me.myhost.com','me1234me') server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, msg) server.quit() # done!