Différences
Ci-dessous, les différences entre deux révisions de la page.
Les deux révisions précédentes Révision précédente Prochaine révision | Révision précédente | ||
technique:python:mail_python [2020/04/06 12:39] – francoisa | technique:python:mail_python [2024/04/02 15:08] (Version actuelle) – modification externe 127.0.0.1 | ||
---|---|---|---|
Ligne 1: | Ligne 1: | ||
- | ====== Envoi de mail avec Python ====== | + | **Cette page est obsolète. Veuillez accéder au contenu |
- | + | ||
- | Pour envoyer des mails avec Python | + | |
- | + | ||
- | https:// | + | |
- | + | ||
- | < | + | |
- | 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' | + | |
- | + | ||
- | On définir les variables de connexion : | + | |
- | + | ||
- | < | + | |
- | smtp_server = " | + | |
- | smtp_port = 465 # For SSL | + | |
- | smtp_email = " | + | |
- | smtp_password = " | + | |
- | + | ||
- | </ | + | |
- | + | ||
- | Attention | + | |
- | + | ||
- | Les templates jinga intègres des filters pour le faire : '' | + | |
- | + | ||
- | <code python> | + | |
- | email = MIMEMultipart(' | + | |
- | email[' | + | |
- | email[' | + | |
- | email[' | + | |
- | txtmessage = render_template(' | + | |
- | htmlmessage = render_template(' | + | |
- | + | ||
- | email.attach(MIMEText(txtmessage, | + | |
- | email.attach(MIMEText(htmlmessage, | + | |
- | + | ||
- | server = smtplib.SMTP_SSL(host=smtp_server, | + | |
- | server.login(smtp_email, | + | |
- | server.sendmail(" | + | |
- | server.quit() | + | |
- | + | ||
- | + | ||
- | </ | + | |
- | + | ||
- | Et c'est tout. | + | |
- | + | ||
- | ====== Insertion de pièces jointes ====== | + | |
- | + | ||
- | Je coplie/ | + | |
- | + | ||
- | 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' | + | |
- | + | ||
- | <code python> | + | |
- | def send_mail(send_from, | + | |
- | assert isinstance(send_to, | + | |
- | + | ||
- | msg = MIMEMultipart() | + | |
- | msg[' | + | |
- | msg[' | + | |
- | msg[' | + | |
- | msg[' | + | |
- | + | ||
- | msg.attach(MIMEText(text)) | + | |
- | + | ||
- | for f in files or []: | + | |
- | with open(f, " | + | |
- | part = MIMEApplication( | + | |
- | fil.read(), | + | |
- | Name=basename(f) | + | |
- | ) | + | |
- | # After the file is closed | + | |
- | part[' | + | |
- | msg.attach(part) | + | |
- | + | ||
- | smtp = smtplib.SMTP(server) | + | |
- | smtp.sendmail(send_from, | + | |
- | smtp.close() | + | |
- | + | ||
- | + | ||
- | </ | + |