Skip to content

Instantly share code, notes, and snippets.

@markjenkins
Last active Oct 6, 2020
Embed
What would you like to do?
<p>
<a href="https://markjenkins.ca">Return to markjenkins.ca</a>
</p>
<p>
This contact form submits to my
<a href="mailto:mark@markjenkins.ca">mark@markjenkins.ca</a> email address.
</p>
<p>
I don't check it frequently.
</p>
<p>Please only use to submit text, unicode supported.
</p>
<p>
Include information on how to reach you if you need a reply.
</p>
<form action="/contactpost" method="POST" accept-charset="UTF-8">
<textarea name="msg" cols="80" rows="25"></textarea>
<div>
<input type="submit" />
</div>
</form>
#!/usr/bin/env python3
# use only when developing
#import cgitb
#cgitb.enable()
import cgi
import html
from smtplib import (
SMTP,
SMTPRecipientsRefused,
SMTPHeloError,
SMTPSenderRefused,
SMTPDataError,
)
from email.message import Message
from email.utils import make_msgid
from hashlib import sha256
from email.utils import formatdate as RFC2822_currentdate
CONTACT_FORM_EMAIL = "contact@markjenkins.ca"
CONTACT_FORM_DEST_EMAIL = "mark@markjenkins.ca"
CONTACT_FORM_SUBJECT = "markjenkins.ca contact form"
CONTACT_FORM_DEST_SERVER = 'mail.skull.space'
CONTACT_DOMAIN_MID = 'markjenkins.ca'
def email_fail():
print("Email delivery failed")
def custom_msg_gid(msg):
return make_msgid(
idstring=sha256(msg.encode('UTF-8')).hexdigest()[0:16],
domain=CONTACT_DOMAIN_MID)
def main():
print("Content-type: text/html")
print()
fs = cgi.FieldStorage()
msg = fs.getfirst("msg")
if msg == None:
print("<h1>no msg recieved</h1>")
print()
return
email_msg = Message()
email_msg.set_unixfrom(CONTACT_FORM_EMAIL)
email_msg.add_header("From", CONTACT_FORM_EMAIL)
email_msg.add_header("To", CONTACT_FORM_DEST_EMAIL)
email_msg.add_header("Subject", CONTACT_FORM_SUBJECT)
email_msg.add_header(
"Message-ID", custom_msg_gid(msg) )
email_msg.add_header("Date", RFC2822_currentdate() )
try:
msg.encode('ascii')
except UnicodeEncodeError:
email_msg.set_payload(msg, charset="UTF-8")
else:
email_msg.set_payload(msg, charset='ascii')
with SMTP(CONTACT_FORM_DEST_SERVER) as s:
s.ehlo("markjenkins.ca") # FIXME, should be in a variable at the top
try:
s_result = s.send_message(
email_msg,
from_addr=CONTACT_FORM_EMAIL,
to_addrs=[CONTACT_FORM_DEST_EMAIL])
except (SMTPRecipientsRefused,
SMTPHeloError,
SMTPSenderRefused,
SMTPDataError):
email_fail()
else:
if len(s_result) == 0:
print("<h1>Email sent</h1>")
# FIXME, should be in a variable at the top for customization
print('<a href="https://markjenkins.ca/">markjenkins.ca</a>')
else:
email_fail()
print()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment