I have a script that sends a request mirror via email. However, it sends the attached mirror of .htm type
I would like it to be sent in pdf.
Below is the script
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import psycopg2
import psycopg2.extras
import sys
import os
import subprocess
import re
import base64
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from validate_email import validate_email
bin_path = os.path.dirname(os.path.realpath(__file__))
general_path = os.path.split(bin_path)[0]
geral_conf = general_path + "/geral.conf"
geral_conf_cmd = ". " + geral_conf
error_message = "None"
conn_pg_string = os.getenv('v_qry')
try:
conn_pg = psycopg2.connect(conn_pg_string)
print "Database connected..."
except Exception as e:
error_message = "Erro ao tentar conectar ao banco de dados: ", e
sys.exit(error_message)
cursor_pg = conn_pg.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor_pg = conn_pg.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor_pg.execute("""SELECT s_valor FROM t_parametro_cliente WHERE s_campo = 'smtp'""")
pg_result = cursor_pg.fetchone()
stamp_configs = pg_result[0].split(',')
mailserver_smtp = stamp_configs[0]
mailserver_login = stamp_configs[1]
mailserver_password = base64.b64decode(stamp_configs[2])
mailserver_ssl = stamp_configs[3]
mailserver_port = stamp_configs[4]
origem = stamp_configs[1]
if mailserver_ssl == '0':
s = smtplib.SMTP(mailserver_smtp, mailserver_port, timeout=15)
s.starttls()
s.login(mailserver_login, mailserver_password)
else:
s = smtplib.SMTP_SSL(mailserver_smtp, mailserver_port, timeout=15)
s.login(mailserver_login, mailserver_password)
cursor_pg.execute("""SELECT v3 AS s_query1 FROM t_vars WHERE grp = 'PEDI' AND id = emp2long('MAIL') AND ord = emp2long('QRY1') AND ((v1 & 1) = 1);""")
rs1 = cursor_pg.fetchone()
cursor_pg.execute("""SELECT v3 AS s_query2 FROM t_vars WHERE grp = 'PEDI' AND id = emp2long('MAIL') AND ord = emp2long('QRY2') AND ((v1 & 1) = 1);""")
rs2 = cursor_pg.fetchone()
cursor_pg.execute("""SELECT v3 AS s_query3 FROM t_vars WHERE grp = 'PEDI' AND id = emp2long('MAIL') AND ord = emp2long('QRY3') AND ((v1 & 1) = 1);""")
rs3 = cursor_pg.fetchone()
if len(rs1) < 1 or len(rs2) < 1 or len(rs3) < 1:
sys.exit(2)
query1 = rs1[0]
query2 = rs2[0]
query3 = rs3[0]
cursor_pg.execute("""SELECT unnest(string_to_array(v3, '|')) AS s_valor FROM t_vars WHERE codmaq = 0 AND grp = 'PEDI' AND id = emp2long('MAIL') AND ord = emp2long('VAR3');""")
rsvar3 = cursor_pg.fetchall()
cursor_pg.execute("""SELECT unnest(string_to_array(v3, '|')) AS s_valor FROM t_vars WHERE codmaq = 0 AND grp = 'PEDI' AND id = emp2long('MAIL') AND ord = emp2long('VAR2');""")
rsvar2 = cursor_pg.fetchall()
cursor_pg.execute("SELECT unnest(string_to_array(v3, '|')) AS s_valor FROM t_vars WHERE codmaq = 0 AND grp = 'PEDI' AND id = emp2long('MAIL') AND ord = emp2long('VAR1');")
rsvar1 = cursor_pg.fetchall()
if len(rsvar1) < 1 or len(rsvar2) < 1 or len(rsvar3) < 1:
sys.exit(4)
cursor_pg.execute("""SELECT u_numero_polibras, unnest(string_to_array(s_email, ',')) AS s_email FROM t_vendedor_email_pedido WHERE s_email ~ E'[A-Za-z0-9._-]+@[A-Za-z0-9]+.[A-Za-z]+' ORDER BY u_numero_polibras LIMIT 50""")
qryrsgeral = cursor_pg.fetchall()
for rsgeral in qryrsgeral:
destino = rsgeral["s_email"]
v_u_numero_polibras = rsgeral["u_numero_polibras"]
print "Envio de e-mail para o pedido numero: %s" % v_u_numero_polibras
query_envia_email = ("""SELECT COALESCE((SELECT (CASE WHEN s_value = 'SIM' THEN 1 ELSE 0 END)::integer FROM observacao WHERE u_id = 1346716745 AND u_srt = 1397314646 AND u_type = 1129270594 AND u_numero_polibras = $1), 0::integer) AS envia_email;""").replace("$1",str(v_u_numero_polibras))
cursor_pg.execute(query_envia_email)
rs1 = cursor_pg.fetchone()
envia_email = rs1[0]
if validate_email(destino) and envia_email:
query = ("""SELECT COALESCE(substring(s_value, E'\([^,]*\),'),'0')::numeric(18,6) AS valor_frete FROM observacao WHERE u_id = emp2long('PEDI') AND u_srt = emp2long('FRET') AND u_relkey = $1;""").replace("$1", str(v_u_numero_polibras))
cursor_pg.execute(query)
rs1 = cursor_pg.fetchall()
if len(rs1) > 0:
valor_frete = rs1[0]
else:
valor_frete = 0
str_itens = ""
str_observacao = ""
v_total = 0
v_subtotal = 0
v_qtditens = 0
cursor_pg.execute("""SELECT v3 AS v_snd1 FROM t_vars WHERE grp = 'PEDI' AND id = emp2long('MAIL') AND ord = emp2long('SND1') AND ((v1 & 1) = 1);""")
rs1 = cursor_pg.fetchone()
cursor_pg.execute("""SELECT v3 AS v_snd2 FROM t_vars WHERE grp = 'PEDI' AND id = emp2long('MAIL') AND ord = emp2long('SND2') AND ((v1 & 1) = 1);""")
rs2 = cursor_pg.fetchone()
cursor_pg.execute("""SELECT v3 AS v_snd3 FROM t_vars WHERE grp = 'PEDI' AND id = emp2long('MAIL') AND ord = emp2long('SND3') AND ((v1 & 1) = 1);""")
rs3 = cursor_pg.fetchone()
v_snd1 = rs1[0]
v_snd2 = rs2[0]
v_snd3 = rs3[0]
v_snd3_orig = v_snd3
query3_exec = query3.replace("$1",str(v_u_numero_polibras))
cursor_pg.execute(query3_exec)
result_query3 = cursor_pg.fetchall()
for rs3 in result_query3:
for row in rsvar3:
valor = row["s_valor"].split(',')
v_snd3 = re.sub(valor[0], str(rs3[valor[1]]), v_snd3)
str_observacao = str_observacao + v_snd3
v_snd3 = v_snd3_orig
v_snd2_orig = v_snd2
query2_exec = query2.replace("$1",str(v_u_numero_polibras))
cursor_pg.execute(query2_exec)
result_query2 = cursor_pg.fetchall()
for rs2 in result_query2:
for i in rsvar2:
valor = i["s_valor"].split(',')
v_snd2 = re.sub(valor[0], str(rs2[valor[1]]), v_snd2)
str_itens = str_itens + v_snd2
v_snd2 = v_snd2_orig
v_total = v_total + rs2["preco"] * rs2["quantidade"]
v_qtditens = v_qtditens + 1
query1_exec = query1.replace("$1",str(v_u_numero_polibras))
cursor_pg.execute(query1_exec)
result_query1 = cursor_pg.fetchall()
for rs1 in result_query1:
for row in rsvar1:
valor = row["s_valor"].split(',')
v_snd1 = re.sub(valor[0], str(rs1[valor[1]]), v_snd1)
v_snd1 = re.sub("__data__", str(rs1["data"]), v_snd1)
v_snd1 = re.sub("__qtdItens__", str(v_qtditens), v_snd1)
v_snd1 = re.sub("__subtotalPedido__", str(v_subtotal), v_snd1)
v_snd1 = re.sub("__totalPedido__", str(round(v_total,6)), v_snd1)
v_snd1 = re.sub("__linhasProduto__", str_itens, v_snd1)
v_snd1 = re.sub("__linhasObs__", str_observacao, v_snd1)
#v_snd1 = re.sub("__valor_frete__", str(valor_frete), v_snd1)
corpo = v_snd1
#Verifica se utiliza customizacao do campos "ASSUNTO" do e-mail
cursor_pg.execute("""SELECT COALESCE((SELECT 1::integer FROM t_vars WHERE (grp, id, ord) = ('PEDI', emp2long('MAIL'), emp2long('SBJT'))), 0::integer) AS use_custom_subject;""")
rs1 = cursor_pg.fetchone()
use_custom_subject = rs1[0]
if use_custom_subject:
cursor_pg.execute("""SELECT v3 AS custom_subject FROM t_vars WHERE (grp, id, ord) = ('PEDI', emp2long('MAIL'), emp2long('SBJT'));""")
rs1 = cursor_pg.fetchone()
query_custom_subject = rs1[0]
query_custom_subject = query_custom_subject.replace("$1",str(v_u_numero_polibras))
cursor_pg.execute(query_custom_subject)
rs1 = cursor_pg.fetchone()
assunto = rs1[0]
else:
assunto = "Confirmação de Pedido"
mensagem = MIMEMultipart("mixed", "------------060808030104070108020807")
mensagem["Subject"] = Header(assunto, "UTF-8")
mensagem["From"] = Header(origem, "UTF-8")
mensagem["To"] = Header(destino, "UTF-8")
mensagem.attach(MIMEText(corpo))
s.sendmail(origem, destino, mensagem.as_string())
print "Deletando o pedido numero: %s apos o envio via e-mail." % (v_u_numero_polibras)
query_deleta_record = """DELETE FROM t_vendedor_email_pedido WHERE u_numero_polibras = %s;""" % v_u_numero_polibras
cursor_pg.execute(query_deleta_record)
conn_pg.commit()
s.quit()