snippets / nicolask / 

All nicolask's snippets (2)

  1. Envoyer un mail html avec python

    Comment envoyer un mail au format html en python. Pratique pour de gros envois de mail.

     1 import smtplib
    2 import MimeWriter
    3 import mimetools
    4 import StringIO
    5
    6 def sendHtmlMail(to,frommail,text,html):
    7 encoding = "base64"
    8 charset = "iso-8859-15"
    9
    10 #déclaration des buffers
    11 out = StringIO.StringIO()
    12 htmlin = StringIO.StringIO(html)
    13 txtin = StringIO.StringIO(html)
    14
    15 #déclaration et initialisation du writer
    16 writer = MimeWriter.MimeWriter(out)
    17 writer.addheader("Subject", text)
    18 writer.addheader("MIME-Version", "1.0")
    19 writer.addheader("From", frommail)
    20 writer.addheader("To", to)
    21 writer.startmultipartbody("alternative")
    22 writer.flushheaders()
    23
    24 #ajout de la partie text
    25 textPart = writer.nextpart()
    26 textPart.addheader("Content-Transfer-Encoding", encoding)
    27 pout = textPart.startbody("text/plain", [("charset", charset)])
    28 mimetools.encode(txtin, pout, encoding)
    29 txtin.close()
    30
    31 #On ajoute la partie html
    32 htmlPart = writer.nextpart()
    33 htmlPart.addheader("Content-Transfer-Encoding", encoding)
    34 pout = htmlPart.startbody("text/html", [("charset", charset)])
    35 mimetools.encode(htmlin, pout, encoding)
    36 htmlin.close()
    37
    38 #on clot le mail
    39 writer.lastpart()
    40 mail = out.getvalue()
    41 out.close()
    42 smtp = smtplib.SMTP("localhost")
    43 #smtp.connect()
    44 smtp.sendmail(frommail, [to], mail)
    45 smtp.close()
    first posted by Fufu to python python mail ... saved by 7 persons ... 0 comments ... 1 year, 2 months
  2. simple xml serializer

    simple xml serializer that convert a python object in xml file.

     1 def serialize_xml(d):
    2 # simple serializer
    3 if not isinstance(d, (dict,list,tuple)):
    4 raise TypeError("Expected a dict here")
    5 yield "\r\n"
    6 if isinstance(d, dict):
    7 for k,v in d.items():
    8 if isinstance(v, (dict,list,tuple)):
    9 v = "".join(serialize_xml(v))
    10 yield "<%(key)s>%(value)s</%(key)s>\r\n" % {
    11 'key':k,
    12 'value':v
    13 }
    14 elif isinstance(d, (tuple, list)):
    15 for v in d:
    16 if isinstance(v, (dict,list,tuple)):
    17 v = serialize_xml(v)
    18 yield "<value>%s</value>\r\n" % v
    first posted by benoitc to python xml serializer ... saved by 2 persons ... 0 comments ... 7 months, 1 week
showing 10, 25, 50 items per pages

Pages : 1