Skip to content

Instantly share code, notes, and snippets.

@m-r-r
Last active December 20, 2015 01:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save m-r-r/c5ee33978ec0f9c7ecc8 to your computer and use it in GitHub Desktop.
Save m-r-r/c5ee33978ec0f9c7ecc8 to your computer and use it in GitHub Desktop.
A dirty script that emails me the comments posted on my weblog. This is a mirror, the script can display its source code by itself.
#!/usr/pkg/bin/python3.3
# -*- coding: utf-8 -*- #
SMTP_SERVER = *Your smtp server here*
WEBLOG_NAME = *Your weblog name here*
EMAIL = *Your email here*
# Begin code:
import os
import cgi, cgitb; cgitb.enable()
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from time import asctime, gmtime, strftime
from hashlib import md5
headers_sent = False
has_errors = False
TEMPLATE = """Content-Type: text/html
Status: %(status)s
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>%(title)s</title>
<meta name="robots" content="noindex, nofollow" />
<!-- headers here -->
</head>
<body>
<h1>%(title)s</h1>
%(msg)s
</body>
</html>
"""
def error(msg):
print(TEMPLATE % {'status': '404 Not Found', 'title': 'Error', 'msg': msg})
exit(0)
if os.getenv('QUERY_STRING') == 'source':
source = open(__file__, 'rt').read()
import re
for setting in ('EMAIL', 'WEBLOG_NAME', 'SMTP_SERVER'):
placeholder = setting.lower().replace('_', ' ')
source = re.sub('^%s\s*=\s*.*$' % setting, '%s = *Your %s here*' \
% (setting, placeholder), source, flags=re.M)
source = source.replace('&', '&amp;')
source = source.replace('<', '&lt;')
source = source.replace('>', '&gt;')
print(TEMPLATE % {
'status': '200 OK',
'title': 'Here is the code',
'msg': '<p>This code is in the public domain.</p><pre>' + source + '</pre>'
})
exit(0)
form = cgi.FieldStorage()
if "redirect_to" not in form or "post_id" not in form:
error("Invalid data received")
elif "name" not in form:
error("Please fill the <q>Name</q> field")
elif "email" not in form:
error("Please fill the <q>E-Mail</q> field")
elif "message" not in form \
or len(form.getvalue("message","").strip()) == 0:
error("Please enter a message")
now = gmtime()
msg = MIMEMultipart()
msg['Subject'] = '[%s] New comment' % WEBLOG_NAME
msg['Sender'] = 'noreply@%s' % SMTP_SERVER
msg['From'] = '%s <%s>' % (form['name'].value, form['email'].value)
msg['To'] = EMAIL
msg['Date'] = '%s GMT' % asctime(now)
msg['X-Weblog'] = WEBLOG_NAME
msg['X-Post-Id'] = form['post_id'].value
msg['X-Remote-Address'] = os.getenv('REMOTE_ADDR', 'unknown')
msg['X-User-Agent'] = os.getenv('HTTP_USER_AGENT', 'unknown')
msg_text = MIMEText(form['message'].value, 'plain', 'utf-8')
msg_text['Content-Disposition'] = 'inline'
msg.attach(msg_text)
yaml_file = '%s_%s.yml' % (strftime('%Y%m%d%H%M%S', now), form['email'].value)
yaml = "date: %s\n" % strftime("%Y-%m-%d %H:%M:%S %z", now)
yaml += "picture: http://www.gravatar.com/avatar/%s?d=identicon&s=50&r=g\n" % md5(form['email'].value.encode('utf-8')).hexdigest()
for key in form.keys():
yaml += "%s: %s\n" % (key.lower(), form[key].value.replace("\n", "\n "))
msg_yaml = MIMEApplication(yaml.encode('utf-8'), 'x-yaml')
msg_yaml['Content-Disposition'] = 'attachement; filename="%s"' % yaml_file
msg.attach(msg_yaml)
try:
smtp = smtplib.SMTP(SMTP_SERVER)
smtp.send_message(msg)
smtp.close()
except Exception as e:
error("Cannot send the comment:<br /><pre>%s</pre>" % e)
msg = """Yout comment has been sent.<br />
<a href="%s">Go back.</a>""" % form["redirect_to"].value
TEMPLATE = TEMPLATE.replace(
"<!-- headers here -->",
'<meta http-equiv="refresh" content="2;%s" />' % form['redirect_to'].value
)
print(TEMPLATE % {'status': '404 Not Found', 'title': 'Sending comment ...', 'msg': msg})
@mdosch
Copy link

mdosch commented Jan 29, 2014

I can run cgi scripts on my webspace to. But I don't know how this works. Can you tell me how this script is used?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment