Envoyer un mail avec piece jointe.

From Tuxunix
Jump to: navigation, search

Exemple


$ ./sendMail.py

Code


   1.#! /usr/bin/python
   2.       
   3.#
   4.#@Name sendMail.py
   5.#@Note Envoie un mail avec piece jointe
   6.#@Author Tuxedo
   7.#@Date 03/10/2008
   8.#@Brief
   9.#@Note
  10.#
  11.       
  12.import smtplib, os
  13.from email.MIMEMultipart import MIMEMultipart
  14.from email.MIMEBase import MIMEBase
  15.from email.MIMEText import MIMEText
  16.from email import Encoders
  17.       
  18.user = "pierrot@toto.com"
  19.      
  20.def mail(to, subject, text, attach):
  21.      
  22.    msg = MIMEMultipart()
  23.    msg['From'] = user
  24.    msg['To'] = to
  25.    msg['Subject'] = subject
  26.    msg.attach(MIMEText(text))
  27.       
  28.    part = MIMEBase('application', 'octet-stream')
  29.    part.set_payload(open(attach, 'rb').read())
  30.    Encoders.encode_base64(part)
  31.    part.add_header('Content-Disposition',
  32.      'attachment; filename="%s"' % os.path.basename(attach))
  33.      msg.attach(part)
  34.       
  35.    mailServer = smtplib.SMTP("smtp.free.fr", 25)
  36.    mailServer.ehlo()
  37.    mailServer.sendmail(user, to, msg.as_string())
  38.    mailServer.close()
  39.       
  40.fic='/Users/tuxedo/Documents/PYTHON/testArg.py'
  41.if os.path.isfile(fic):
  42.    f=open(fic)
  43.    data=f.read()
  44.    f.close()
  45.else:
  46.    print "File doesn't exist : %s" %fic
  47.    sys.exit(1)
  48.    mess = "Resultat : \n" + data
  49.
  50.    mail("pierre@tuxedo.fr","[Titre]",mess,fic)