technique:python:mail_python

Ceci est une ancienne révision du document !


Envoi de mail avec Python

Pour envoyer des mails avec Python

https://blog.mailtrap.io/sending-emails-in-python-tutorial-with-code-examples/

import smtplib, ssl
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

Il est possible de définir des templates jinga pour l'envoi de mail (ici avec les 2 render_template).

On définir les variables de connexion :

smtp_server = "mail.cemea.org"
smtp_port = 465  # For SSL
smtp_email = "machines@cemea.asso.fr"
smtp_password = "xxxxxx"

Attention à ne pas intégrer de caractères non HTML (codées sur 7 bits dans le corps du mail, sinon en 64 bits).

Les templates jinga intègres des filters pour le faire : |escape (comme escape ).

   email = MIMEMultipart('alternative')
    email['To'] = "toi@adresse.fr"
    email['From'] = "moi@adresse.fr"
    email['Subject'] = f"Sujet du mail"
    txtmessage = render_template('mail.txt', msg=msg)
    htmlmessage = render_template('mailhtml.txt', msg=msg)
 
    email.attach(MIMEText(txtmessage, 'plain'))
    email.attach(MIMEText(htmlmessage, 'html'))
 
    server = smtplib.SMTP_SSL(host=smtp_server,port=smtp_port)
    server.login(smtp_email, smtp_password)
    server.sendmail("From: "+email['From'], "To: "+email['To'], email.as_string())
    server.quit()

Et c'est tout.

Insertion de pièces jointes

Je coplie/colle ici : https://stackoverflow.com/questions/3362600/how-to-send-email-attachments

Pas testé, juste documenté

import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate

Et la fonction d'envoi avec lesfichiers dans “files”

def send_mail(send_from, send_to, subject, text, files=None, server="127.0.0.1"):
    assert isinstance(send_to, 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 or []:
        with open(f, "rb") as fil:
            part = MIMEApplication(
                fil.read(),
                Name=basename(f)
            )
        # After the file is closed
        part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
        msg.attach(part)
 
    smtp = smtplib.SMTP(server)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
  • technique/python/mail_python.1586169545.txt.gz
  • Dernière modification : 2020/04/11 02:26
  • (modification externe)