associação pythonbrasil[11] django zope/plone planet Início Logado como (Entrar)

Diferenças para "EnviarEmail"

Diferenças entre as versões de 1 e 5 (4 versões de distância)
Revisão 1e 2005-06-22 17:38:53
Tamanho: 4536
Editor: RodrigoSenra
Comentário:
Revisão 5e 2008-09-26 14:07:53
Tamanho: 4751
Editor: localhost
Comentário: converted to 1.6 markup
Deleções são marcadas assim. Adições são marcadas assim.
Linha 10: Linha 10:
#!python
Linha 11: Linha 12:
Linha 13: Linha 13:
Linha 15: Linha 14:
Linha 17: Linha 15:
Linha 19: Linha 16:
Linha 21: Linha 17:
Linha 23: Linha 18:

# Interpretador: Python 2.3.2
ou superior
# Interpretador: Python 2.3.2  ou superior
Linha 28: Linha 21:
Linha 30: Linha 22:
Linha 32: Linha 23:
Linha 34: Linha 24:
Linha 36: Linha 25:
Linha 38: Linha 26:
Linha 40: Linha 27:
Linha 42: Linha 28:
Linha 44: Linha 29:
Linha 46: Linha 30:
Linha 48: Linha 31:

from Crypto.Cipher import DES
from Crypto.Cipher import DES   # Opcional
Linha 52: Linha 33:
Linha 54: Linha 34:
Linha 60: Linha 39:
Linha 63: Linha 41:
__server = '127.0.0.1'
 
# alterar aqui comnome ou endereço servidor smtp
# alterar aqui com nome ou endereço servidor smtp
__server = '127.0.0.1'
Linha 66: Linha 44:

# Atualmente nao esta havendo autenticacao

#__login = ""

#
__passwd = ""
# Atualmente nao esta havendo autenticacao, preencha
# se necessario
__login = ""
__passwd = ""
Linha 76: Linha 51:
Linha 78: Linha 52:
Linha 80: Linha 53:
Linha 85: Linha 57:
def attachPlainFile(_writer, _file, _mimeType=None, _name="unknown"):
def attachPlainFile(_writer, _file, _mimeType=None,
                   
_name="unknown"):
Linha 88: Linha 60:
Linha 90: Linha 61:
Linha 92: Linha 62:
Linha 97: Linha 66:
def attachCryptFile(_writer, _file,_mimeType=None,_name="unknown"):
def attachCryptFile(_writer, _file,_mimeType=None,
                    
_name="unknown"):
Linha 100: Linha 69:
Linha 102: Linha 70:
Linha 104: Linha 71:
Linha 106: Linha 72:
Linha 108: Linha 73:
Linha 110: Linha 74:
Linha 112: Linha 75:
Linha 120: Linha 82:
Linha 122: Linha 83:
Linha 124: Linha 84:
Linha 126: Linha 85:
Linha 128: Linha 86:
Linha 130: Linha 87:
Linha 134: Linha 90:
Linha 142: Linha 97:
Linha 144: Linha 98:
Linha 146: Linha 99:
Linha 148: Linha 100:
Linha 150: Linha 101:
Linha 152: Linha 102:

attachPlainFile(writer,_file.read(),_mime,_name)
                    attachPlainFile(writer,_file.read(),
                                    
_mime,_name)
Linha 156: Linha 105:

attachCryptFile(writer,_file.read(),_mime,_name)
      attachCryptFile(writer,_file.read(),
                                    
_mime,_name)
Linha 160: Linha 108:
Linha 163: Linha 110:
                        
Linha 169: Linha 111:
Linha 172: Linha 113:

Linha 175: Linha 114:
Linha 177: Linha 115:

 
Linha 185: Linha 121:
 
Linha 188: Linha 123:
Linha 192: Linha 126:
Linha 196: Linha 129:

syslog(LOG_INFO,str(format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2])))

         
        syslog(LOG_INFO,
               
str(format_exception(sys.exc_info()[0],
                                    
sys.exc_info()[1],
                                    
sys.exc_info()[2])))
Linha 208: Linha 140:
#!python
Linha 219: Linha 152:
    aplicativo de visualização distribuído pela GPr Sistemas) e
    dispare pedidos.py para visualizar seu conteúdo.
    aplicativo de visualização distribuído pela GPr Sistemas)
    e dispare pedidos.py para visualizar seu conteúdo.
Linha 240: Linha 173:
                     _attachments = (('text',data1,'text/plain',None),
                                     ('attach',data2,'EncryptedContent.ENCRYPTED',filename)))
                     _attachments = (('text', data1,
                                      
'text/plain', None),
                                     ('attach',data2,
                                      
'EncryptedContent.\
ENCRYPTED',
                                      
filename)))

Receita: EnviarEmail

Esta receita ilustra como utilizar a biblioteca smtplib (padrão em distribuição Python) para enviar e-mails, com anexos opcionais.

Código

   1 #  ___ GPr Sistemas ____________________________________
   2 #
   3 #  Modulo: gpmail.py
   4 #  Data de Criação:     2003-02-26
   5 #  Data de Atualização: 2003-12-05
   6 #
   7 #  Desenvolvedores: João Chaves/Rod Senra
   8 #  Interpretador:   Python 2.3.2  ou superior
   9 
  10 import sys
  11 import smtplib
  12 import MimeWriter
  13 import mimetypes
  14 import base64
  15 import StringIO
  16 import getopt
  17 import os.path
  18 import sys
  19 import urllib2
  20 from StringIO import StringIO
  21 from Crypto.Cipher import DES   # Opcional
  22 from syslog import *
  23 from traceback import format_exception
  24 
  25 
  26 __version__ = '0.4'
  27 
  28 
  29 # Configurações
  30 
  31 # alterar aqui com nome ou endereço servidor smtp
  32 __server = '127.0.0.1'  
  33 
  34 # Atualmente  nao esta havendo autenticacao, preencha 
  35 # se necessario
  36 __login = ""
  37 __passwd = ""
  38 
  39 
  40 def attachText(_writer, _text,_mime):
  41     part = _writer.nextpart()
  42     body = part.startbody(_mime)
  43     body.write(_text)
  44 
  45 
  46 
  47 def attachPlainFile(_writer, _file, _mimeType=None,
  48                     _name="unknown"):
  49     part = _writer.nextpart()
  50     part.addheader('Content-Transfer-Encoding','base64')
  51     body = part.startbody("%s; name=%s"%(_mimeType,_name))
  52     base64.encode(StringIO(_file),body)
  53 
  54     
  55 
  56 def attachCryptFile(_writer, _file,_mimeType=None,
  57                     _name="unknown"):
  58     part = _writer.nextpart()
  59     part.addheader('Content-Transfer-Encoding', 'base64')
  60     body = part.startbody('%s; name=%s'%(_mimeType,_name))
  61     obj = DES.new(" secret ",DES.MODE_ECB)
  62     pad = 8-(len(_file)%8)
  63     _file = _file+pad*" "
  64     crypt = obj.encrypt(_file)
  65     base64.encode(StringIO(crypt),body)
  66 
  67     
  68 
  69 
  70 
  71 def sendmail(_subject,_from,_to,_cc=None,_attachments=None):
  72     try:
  73         message = StringIO()
  74         writer = MimeWriter.MimeWriter(message)
  75         writer.addheader('MIME-Version', '1.0')
  76         writer.addheader('Subject', _subject)
  77         writer.addheader('To',_to)
  78 
  79         if _cc:
  80             writer.addheader('Cc',_cc)
  81 
  82         writer.startmultipartbody('mixed')
  83 
  84         
  85 
  86         # process attachments
  87         if _attachments:
  88             for _mode,_file,_mime,_name in _attachments:
  89                 if _mode=="text":
  90                     attachText(writer,_file.read(),_mime)
  91                 elif _mode=="attach":
  92                     attachPlainFile(writer,_file.read(),
  93                                     _mime,_name)
  94                 elif _mode=="crypt":
  95                     attachCryptFile(writer,_file.read(),
  96                                     _mime,_name)        
  97                 else:
  98                     raise Exception("Invalid Mode specified")
  99 
 100         # finish off
 101         writer.lastpart()
 102 
 103         # send the mail
 104         smtp = smtplib.SMTP(__server)
 105 
 106         # Uncomment the line below if you need authentication
 107 
 108         if __login:
 109             smtp.login(__login,__passwd)
 110 
 111 
 112         smtp.sendmail(_from,_to, message.getvalue())
 113         #print message.read()
 114 
 115         smtp.quit()
 116         syslog(LOG_INFO,"Email Ok")
 117 
 118     except:
 119         syslog(LOG_INFO,
 120                str(format_exception(sys.exc_info()[0],
 121                                     sys.exc_info()[1],
 122                                     sys.exc_info()[2])))

Exemplo de uso

   1 def main():
   2     # Alterar estes valores antes de instalar na Wagonlit!!!
   3     to = "deFulano@dominio.com.br"
   4     orig = "paraBeltrano@outroDominio.com.br"
   5     subject = "Teste de e-mail"
   6     filename = "f0001.ped"
   7 
   8     body = """
   9     Segue em anexo o arquivo %s com um pedido 
  10     criptografado. Por obséquio, salve o arquivo no diretório
  11     c:\gpr\pedidos (ou no diretório onde foi instalado o
  12     aplicativo de visualização distribuído pela GPr Sistemas)
  13     e dispare pedidos.py para visualizar seu conteúdo.
  14 
  15     Atenciosamente,
  16     GPr Sistemas Ltda
  17     """%(filename)
  18 
  19     attach = """
  20     Name:               Fulano de tal
  21     Endereço:           Rua da Amargura 1313
  22     Cartão de Crédito:  1243543412356
  23 
  24     etc etc etc
  25     """
  26 
  27     data1 = StringIO(body)
  28     data2 = StringIO(attach)
  29 
  30     sendmail(_subject = subject,
  31                      _from = orig,
  32                      _to = to,
  33                      _attachments = (('text', data1,
  34                                       'text/plain', None),
  35                                      ('attach',data2,
  36                                       'EncryptedContent.\
  37 ENCRYPTED',
  38                                       filename)))
  39        
  40 if __name__=="__main__":
  41     main()

Volta para CookBook.


RodrigoSenra