5th February, 2014

Send an email with a Python CGI

Make sure your web server can execute Python as CGI

<Directory "/var/www/cgi">
    Options +ExecCGI
    AddHandler cgi-script .cgi .py
    Order allow,deny
    Allow from all
</Directory>

Then save this file somewhere:

#!/usr/bin/env python
import cgi,cgitb
from email.MIMEText import MIMEText
import smtplib,sys


SMTP_LOGIN = 'yourname@gmail.com'
SMTP_PASSWORD = 'YOUR PASSWORD'
SUCCESS_FILENAME = ''

def output_success(success_filename):
    cgitb.enable()

    with open(success_filename, 'rt') as read_handle:
        text_buffer = read_handle.read()

    print('Content-Type: text/html\n\n')
    print(text_buffer)


def send_email(smtp_login, smtp_password, email_from, email_to, message):
    server = smtplib.SMTP("smtp.gmail.com",587)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(SMTP_LOGIN, SMTP_PASSWORD)
    server.sendmail(email_from, email_to, message)
    server.quit


def parse_form(smtp_login, smtp_password, success_filename):
    form_collection = cgi.FieldStorage()

    body = form_collection['message'].value
    msg = MIMEText(body)
    mfrom = "email@example.com"
    to = form_collection['to'].value

    msg['From'] = mfrom
    msg['To'] = to
    msg['Subject'] = form_collection['subject'].value

    send_email(smtp_login, smtp_password, mfrom, [to], msg.as_string())

    output_success(success_filename)

if __name__ == '__main__':
    parse_form(SMTP_LOGIN, SMTP_PASSWORD, SUCCESS_FILENAME)

Now post to it using

<form action="/path_to_your_script.py" method="post">

    <input type="text" name="to" />
    <input type="text" name="subject" />
    <input type="text" name="message" />

</form>

 

The opinions expressed here are my own and not those of my employer.