Last active
December 5, 2017 05:49
-
-
Save hex128/4174a2c2351840c2197c98550f68c9a3 to your computer and use it in GitHub Desktop.
Contact Form with NGINX, Lua, Python and SMTP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ngx.req.read_body() | |
local fp = assert(io.popen('/usr/local/bin/contact.py >> /var/log/nginx/contact-form.log 2>&1', 'w')) | |
fp:write(ngx.var.remote_addr) | |
fp:write('\r\n') | |
fp:write(ngx.req.get_body_data()) | |
assert(fp:close()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import json | |
import smtplib | |
from email.mime.text import MIMEText | |
from sys import stdin, stdout | |
from urllib.parse import parse_qsl, urlencode | |
from urllib.request import Request, urlopen | |
ip, qs = stdin.read().split('\r\n', 1) | |
data = dict(parse_qsl(qs)) | |
data['ip'] = ip | |
json.dump(data, stdout) | |
stdout.write('\n') | |
assert {'name', 'company', 'email', 'phone', 'message', 'g-recaptcha-response'} <= set(data) | |
with urlopen(Request( | |
url='https://www.google.com/recaptcha/api/siteverify', | |
data=urlencode({ | |
'secret': '0123456789ABCDEFGHIJK_LMNOPQRSTUVW_XYZab', | |
'response': data.get('g-recaptcha-response') | |
}).encode('utf-8'), | |
headers={'content-type': 'application/x-www-form-urlencoded'} | |
)) as response: | |
assert json.loads(response.read().decode('utf-8')).get('success') | |
template = "Name: {name}\r\nCompany: {company}\r\nEmail: {email}\r\nPhone: {phone}\r\nIP: {ip}\r\n\r\n{message}" | |
message = MIMEText(template.format(**data).encode('utf-8'), 'plain', 'utf-8') | |
message['Subject'] = 'Example Contact Form' | |
message['From'] = 'Example Contact Form <[email protected]>' | |
message['To'] = '[email protected]' | |
with smtplib.SMTP('192.168.16.4') as smtp: | |
smtp.send_message(message) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
location = /contact { | |
default_type 'text/plain'; | |
content_by_lua_file /usr/local/bin/contact.lua; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment