Pages

Monday, January 11, 2016

Скрипты для Mail Form

Это скрипты, которые требуются для того, чтоб послать емайл с домашнего веб-сайта. Инструкции по их применению тут.  

Скачать: mail.tar.gz

 

sendmail.py

 

#!/usr/bin/python
#-*-coding:utf-8-*-

#=============================================
# СМЕНИ НАСТРОЙКИ

sender= 'Мой секси сайт'  # Имя отправителя, которое появится в 
     # поле From (Oт кого)
email_to = "vasqpupkin@mail.ru"  # адрес, на который пойдет емайл

smtp_security_type='TLS'  # TLS или SSL
     # TLS для Gmail
     # SSL для Mail.ru
       
smtp_server = "smtp.gmail.com"  # название SMTP сервера
smtp_port= 587    # Порт SMTP сервера
smtp_login = "misexysite@gmail.com" # Твой логин на Mail.ru или Gmail
smtp_password="z63)1Lg1"  # Твой пароль


template='/var/www/html/mail/template.txt' # Путь к файлу templates.txt
response='/var/www/html/mail/response.html' # Путь к файлу response.html
open_url = '/mail/iframe.html'   # URL страницы с iframe.

#==============================================

import cgitb
cgitb.enable()

import cgi
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import time, re

form = cgi.FieldStorage()
Errors=[]

Name, From, Subject, Message = '','','',''
a, b, c, d = '','','',''

try:
 Name=form['name'].value.strip()
 a='Ваше имя: '+ Name
 if len(Name)==0:
  Errors.append('Ваше имя: не указано')
except:
 Errors.append('Ваше имя: не указано')
try:
 From = form['from'].value.strip()
 b='Ваш емайл: '+ From
except:
 Errors.append('Ваш емайл: не указан')
try:
 Subject=form['subject'].value.strip()
 c='Тема: '+ Subject
except:
 Errors.append('Тема: не указана')
try:
 Message = form['message'].value.strip()
 d= Message
except:
 Errors.append('Послание: отсутствует')

if len(Errors) == 0:
 EMAIL_REGEX = re.compile(r"[^@]+@[^@]+\.[^@]+")
 if not EMAIL_REGEX.match(From):
  Errors.append('Ваш емайл невалидный: '+From)

html='<h1>Спасибо за письмо</h1>'+a+'<br>'+b+'<br>'+c+'<br>'*2+d.replace('\n', '<br>')

if len(Errors) == 0:
 try:
  msg = MIMEMultipart()
  msg['From'] = sender+' <'+smtp_login+'>'
  msg['Reply-To'] = Name+' <'+From+'>'
  msg['To'] = email_to
  msg['Subject'] = Subject
  msg['Date'] = time.strftime("%c")
  msg.attach(MIMEText(Message, 'plain'))

  # Опции для SMTP сервера ---------
  
  if smtp_security_type =='TLS':
   server = smtplib.SMTP(smtp_server, smtp_port)
   server.starttls()
  
  if smtp_security_type =='SSL':
   server = smtplib.SMTP_SSL(smtp_server, smtp_port)
   
  server.ehlo()
  server.login(smtp_login, smtp_password)
  text = msg.as_string()
  server.sendmail(From, email_to, text)
  server.close()
  
  #----------------------------------
  
 except Exception as e:
  
  i=0
  for item in e:
   
   item=str(item)
   if i==0:
    item='Error: '+item
   
   item=item.replace('<', '&lt;')
   item=item.replace('>', '&gt;')
   
   Errors.append(item)
   i=1+1

if len(Errors)>0:
 html='<h1>Исправьте ошибки</h1>'
 for item in Errors:
  html=html+item+'<br>'
 html=html+'<br>Письмо не отправлено.'

f=open(template, 'r')
s=f.read()
f.close()

s=s.replace('[msg]', html)

f=open(response, 'w')
f.write(s)
f.close()

print 'Content-type: text/html\n\n'
print '<meta http-equiv="refresh" content="0;url='+open_url+'">'
print '<link rel="canonical" href="'+open_url+'"/>'


iframe.html

 

<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title>Response</title>
</head>
<body>
 
<!-- === Копируй отсюда  === -->
<iframe src="/mail/response.html" width="500" height="300" frameBorder="0"></iframe> 
<!-- === и досюда  ========= -->

</body>
</html>


response.css

 

body {
background-color: white;
color: black;
font-family: Verdana;
font-size: 14px;
}

h1 {
font-family: Tahoma;
font-size: 20px;
}


template.txt

 

<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<link rel="stylesheet" type="text/css" href="response.css">
<title>Спасибо</title>
</head>
<body>

[msg]

</body>
</html>


mailform.html

 

<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title>Mail Form</title>
</head>
<body>
 
<h1>Напиши мне</h1>

<!-- === Копируй отсюда  === -->
<form action="/cgi-bin/sendmail.py" method="get">
Ваше имя:<br>
<input name="name" size="40" type="text"><br><br>
Ваш емайл:<br>
<input name="from" size="40" type="text"><br><br>
Тема:<br>
<input name="subject" size="40" type="text"><br><br>
Послание:<br>
<textarea cols="46" name="message" rows="10"></textarea><br><br>
<input value="Submit" type="submit"></form>
<!-- === и досюда  ========= -->

</body>
</html>