python et les mails
*******************
envoie d’un email txt
=====================
On souhaite envoyer via l’adresse **f.aoustin@kff.fr** un message vers **fraoustin@gmail.com** contenant
.. code-block:: bash
    Bonjour!
    text a envoyer
.. code-block:: python
    import smtplib
    # un message email de type text
    from email.MIMEText import MIMEText
    
    def send(mfrom,mto):
        email = MIMEText('Bonjour !\ntext a envoyer')              # objet Message contenant du text/plain
        email['From']=mfrom                        # headers du mail : from/to/subject
        email['To']=mto
        email['Subject']='Bonjour !'
        server = smtplib.SMTP('smtp.fr.oleane.com')         # objet serveur
        #server.login('user', 'password')
        server.sendmail(mfrom,                     # on lui envoi notre mail
                    mto,
                    email.as_string())
        server.quit()                              # on ferme la connection
    
    if __name__ == '__main__':
        send('f.aoustin@kff.fr','fraoustin@gmail.com')
envoie d’un email txt+html
==========================
.. code-block:: python
    #! /usr/bin/python
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    me = "f.aoustin@kff.fr"
    you = "f.aoustin@kff.fr"
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "Link"
    msg['From'] = me
    msg['To'] = you
    text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
    html = """\
    
    
    
        Hi!
        How are you?
        Here is the link you wanted.
        
    
    
    """
    part1 = MIMEText(text, 'plain')
    part2 = MIMEText(html, 'html')
    msg.attach(part1)
    msg.attach(part2)
    s = smtplib.SMTP('smtp.fr.oleane.com')
    s.sendmail(me, you, msg.as_string())
    s.close()
envoi mail par ligne de commande
================================
.. code-block:: python
    #!/usr/bin/env python
    
    import os
    import sys
    import logging
    import syslog
    import smtplib
    from email.MIMEText import MIMEText
    
    server_smtp = 'smtp.fr.oleane.com'
    sender = 'f.aoustin@kff.fr'
    
    def send(mfrom,mto, title, msg):
        email = MIMEText(msg)
        email['From']=mfrom
        email['To']=mto
        email['Subject']=title
        server = smtplib.SMTP(server_smtp)
        server.sendmail(mfrom,
                mto,
                email.as_string())
        server.quit()
    
    if __name__ == "__main__":
        import sys
        from getpass import getpass
        try:
            to = sys.argv[1]
            subject = sys.argv[2]
            msg = ''
            for i in sys.argv[3:]:
                msg = msg + i + '\n'
        except IndexError:
            syslog.syslog('[%s][ERROR]Usage: %s   ' % (sys.argv[0],sys.argv[0]))
            for i in sys.argv[:]:
                syslog.syslog('[%s][ERROR]: %s ' % (sys.argv[0],i))
            print "Usage: %s   " % sys.argv[0]
            raise SystemExit
    
        try:
            send(sender ,to, subject, msg)
        except Exception, e:
            syslog.syslog('[%s][ERROR] Login failed. (Wrong username/password?)' % sys.argv[0])
            syslog.syslog('[%s][ERROR][TO]: %s ' % (sys.argv[0],to))
            syslog.syslog('[%s][ERROR][SUBJECT]: %s ' % (sys.argv[0],subject))
            syslog.syslog('[%s][ERROR][MSG]: %s ' % (sys.argv[0],msg))
            syslog.syslog('[%s][ERROR][ERROR]: %s ' % (sys.argv[0],e))
Pour utiliser gmail il faut activier le ssl et utiliser le port 587, le server smtp.gmail.com et son compte fraoustin@gmail.com + password
.. code-block:: python
    def send_mail(txt):
        write_log(INFO, "send mail %s %s" % (CONF_MAIL, CONF_SUBJECT))
        server = smtplib.SMTP('smtp.gmail.com',587)
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(login,password)
un plus compliqué avec envoie de pièces jointes
===============================================
.. code-block:: python
    from optparse import OptionParser
    import sys
    import os, os.path
    import smtplib
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email.MIMEText import MIMEText
    from email.Utils import COMMASPACE, formatdate
    from email import Encoders
    import syslog
    
    def send_mail(send_from, send_to, subject, text, files=[], server="localhost",password=""):
        """
        Send msg and attach
        """
        assert type(send_to)==list
        assert type(files)==list
    
        msg = MIMEMultipart()
        msg['From'] = send_from
        msg['To'] = COMMASPACE.join(send_to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
    
        msg.attach( MIMEText(text) )
    
        for f in files:
            part = MIMEBase('application', "octet-stream")
            part.set_payload( open(f,"rb").read() )
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
            msg.attach(part)
    
        smtp = smtplib.SMTP(server)
        if password != "":
            smtp.login(send_from, password)
        smtp.sendmail(send_from, send_to, msg.as_string())
        smtp.close()
    
    def getPathFile(p):
        """
        Test of p is file with pwd and PYTHONPATH
        """
        if os.path.isfile(p):
            return p
        if os.path.isfile(os.path.join(os.getcwd(),p)):
            return os.path.join(os.getcwd(),p)
        for i in sys.path:
            if os.path.isfile(os.path.join(i,p)):
                return os.path.join(i,p)
        raise AttributeError, '%s is not directory' % p
    
    def getPathDir(p):
        """
        Test of p is file with pwd and PYTHONPATH
        """
        if os.path.isdir(p):
            return p
        if os.path.isdir(os.path.join(os.getcwd(),p)):
            return os.path.join(os.getcwd(),p)
        for i in sys.path:
            if os.path.isfile(os.path.join(i,p)):
                return os.path.join(i,p)
        raise AttributeError, '%s is not directory' % p
    
    if __name__ == '__main__':
        parser = OptionParser(version="%prog 0.1")
        parser.description= "send mail with or without file"
        parser.epilog = "by Frederic Aoustin"
        parser.add_option("-f", "--from",
            dest="fro",
            help ="smtp from",
            type="string")
        parser.add_option("-t", "--to",
            dest="to",
            help ="to(s) separated by ;",
            type="string")
        parser.add_option("-s", "--server",
            dest="server",
            help ="server smtp",
            type="string")
        parser.add_option("-p", "--password",
            dest="password",
            help ="password of from",
            default="",
            type="string")
        parser.add_option("-a", "--subject",
            dest="subject",
            help ="subject of mail",
            type="string")
        parser.add_option("-b", "--txt",
            dest="txt",
            help ="text of mail, line separated by ;",
            type="string")
        parser.add_option("-x", "--files",
            dest="files",
            help ="file(s) separated by ;",
            type="string")
        (options, args) = parser.parse_args()
        try:
            fro = options.fro
            to= []
            for i in options.to.split(";"):
                to.append(i)
            serv = options.server
            password = options.password
            subject = options.subject
            txt = options.txt
            txt = txt.replace(";","\n")
            fil = []
            for i in options.files.split(";"):
                fil.append(getPathFile(i))
            send_mail(fro, to, subject, txt, fil, serv,password)
        except Exception, e:
            print parser.error(e)
            syslog.syslog('[%s][ERROR] Login failed. (Wrong username/password?)' % sys.argv[0])
            syslog.syslog('[%s][ERROR][ERROR]: %s ' % (sys.argv[0],e))
Utilisation
.. code-block:: bash
    C:\Users\aoustin\Desktop>python mailer.py -f f.aoustin@kff.fr -t f.aoustin@kff.fr;fraoustin@gmail.com
        -s smtp.fr.oleane.com -p stingray -a TEST -b "coucou;deux lignes"
        -x C:\eula.1028.txt;C:\eula.1033.txt
envoi d'un email en UTF-8
=========================
.. code-block:: python
    html = template('mail',{'sensors' : SENSORS,
                                                    'local' : LOCALSYSTEM,
                                            })
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "Dashboard %s" % self.hostname
    msg['From'] = APP_MAIL_FROM
    msg['To'] = APP_MAIL_TO
    part = MIMEText(html.encode('utf-8'),_subtype='html', _charset='utf-8')
    msg.attach(part)
    server = smtplib.SMTP(APP_MAIL_SMTP)
    server.sendmail(APP_MAIL_FROM, APP_MAIL_TO, msg.as_string())
    server.close()   
envoi d'un mail contenant des images
====================================
.. code-block:: python
    # Send an HTML email with an embedded image and a plain text message for
    # email clients that don't want to display the HTML.
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEText import MIMEText
    from email.MIMEImage import MIMEImage
    # Define these once; use them twice!
    strFrom = 'f.aoustin@myprop-group.com'
    strTo = 'f.aoustin@myprop-group.com'
    # Create the root message and fill in the from, to, and subject headers
    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = 'test message'
    msgRoot['From'] = strFrom
    msgRoot['To'] = strTo
    msgRoot.preamble = 'This is a multi-part message in MIME format.'
    # Encapsulate the plain and HTML versions of the message body in an
    # 'alternative' part, so message agents can decide which they want to display.
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)
    msgText = MIMEText('This is the alternative plain text message.')
    msgAlternative.attach(msgText)
    # We reference the image in the IMG SRC attribute by the ID we give it below
    msgText = MIMEText('Some HTML text and an image.

Nifty!', 'html')
    msgAlternative.attach(msgText)
    # This example assumes the image is in the current directory
    fp = open('test.png', 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    # Define the image's ID as referenced above
    msgImage.add_header('Content-ID', '')
    msgRoot.attach(msgImage)
    # Send the email (this example assumes SMTP authentication is required)
    import smtplib
    smtp = smtplib.SMTP()
    smtp.connect('srvxxxx1')
    smtp.sendmail(strFrom, strTo, msgRoot.as_string())
    smtp.quit()