PyProgram #5 – SMTP Mail Sender

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!
Advertisements

6 thoughts on “PyProgram #5 – SMTP Mail Sender

  1. err.. I see it as viola and not voila, but indeed I had first typed it as voila then edited it in a few seconds. Wonder how you got to see the erroneous one.

    And, also have a look at smtppush. 🙂

  2. OMG, It was first voila (which I naturally wrote) and this was showing a spello. So, I right clicked and suggested word was viola. I thought my vocabs were bad and changed it. Thanks for clarifying it, think voila is not present in the dictionary (aspell?) and hence it marks it as a spello.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s