The Accidental Rubyist

invalid byte sequence in UTF-8

Archive for July 2008

sending smtp mails from command line (python)

leave a comment »

First of all, ruby 1.8.x does not have SSL working in SMTP, so forget connecting to Python and perl have it working beautifully. Here’s a quick example, modified slightly from what I found on the net.

#!/usr/bin/env python
# 2008-07-07 17:33
# use this to send a simple mail from your gmail account
import smtplib
import getpass

def prompt(prompt):
    return raw_input(prompt).strip()

fromaddr = prompt("Login Email Id: ")
name = prompt("My Display Name: ")
subject = prompt("Subject: ")
toaddrs  = prompt("To: ").split()
password = getpass.getpass("password: ")
print "Enter message, end with ^D (Unix) or ^Z (Windows):"

# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n"
       % (name + "", ", ".join(toaddrs), subject))
while 1:
        line = raw_input()
    except EOFError:
#    if not line:
#        break
    msg = msg + line + "\n"

print "Message length is " + repr(len(msg))

#server = smtplib.SMTP('', 587)
server = smtplib.SMTP('')
server.login(fromaddr, password)
server.sendmail(fromaddr, toaddrs, msg)

If you have only one gmail account, you can hardcode it here. I use this to send an email using an account I use (occasionally) for some fora, this avoids logging in and out of gmail on Firefox. It’s a basic version, no attachments etc.

[Edited in Vim using HTML.vim]

Beauty is truth, truth beauty, that is all
Ye know on earth, and all ye need to know.
— John Keats


Written by totalrecall

July 10, 2008 at 4:41 pm

Posted in python

Tagged with ,