Introduction
Envoyer des emails depuis Python peut se faire de plusieurs manières :
- En utilisant la bibliothèque intégrée
smtplib de Python
- En utilisant des bibliothèques de haut niveau comme
yagmail
- En utilisant des API (SendGrid, Mailgun) pour des envois à grande échelle ou sans email personnel
Ce tutoriel couvre toutes ces approches avec des exemples.
2. Utilisation de smtplib (bibliothèque intégrée Python)
2.1 Email texte simple
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | import smtplib
sender_email = "votre_email@example.com"
receiver_email = "destinataire@example.com"
password = "votre_mot_de_passe" # Ou mot de passe d'application si 2FA activé
subject = "Bonjour depuis Python"
body = "Ceci est un email de test envoyé depuis Python !"
message = f"Subject: {subject}\n\n{body}"
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls() # Connexion sécurisée
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
print("Email envoyé avec succès !")
|
Remarques :
- Pour Gmail : serveur SMTP =
smtp.gmail.com, port 587
- Utilisez les mots de passe d’application si la double authentification est activée
2.2 Email avec pièce jointe
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 | import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
sender_email = "votre_email@example.com"
receiver_email = "destinataire@example.com"
password = "votre_mot_de_passe"
msg = MIMEMultipart()
msg["From"] = sender_email
msg["To"] = receiver_email
msg["Subject"] = "Email avec pièce jointe"
msg.attach(MIMEText("Bonjour ! Voici votre pièce jointe.", "plain"))
filename = "exemple.pdf"
with open(filename, "rb") as f:
attach = MIMEApplication(f.read(), _subtype="pdf")
attach.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(attach)
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls()
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, msg.as_string())
print("Email avec pièce jointe envoyé !")
|
3. Utilisation de yagmail (plus simple et plus propre)
3.1 Installation
3.2 Stocker le mot de passe Gmail de manière sécurisée
| import yagmail
yagmail.register('votre_email@gmail.com', 'votre_mot_de_passe_app')
|
3.3 Envoyer un email simple
| import yagmail
sender_email = "votre_email@gmail.com"
receiver_email = "destinataire@example.com"
yag = yagmail.SMTP(sender_email)
yag.send(to=receiver_email, subject="Bonjour !", contents="Ceci est un email de test avec yagmail.")
print("Email envoyé avec succès !")
|
3.4 Email avec pièces jointes
| yag.send(to="destinataire@example.com",
subject="Rapport",
contents="Veuillez trouver le rapport en pièce jointe.",
attachments=["exemple.pdf"])
|
3.5 Envoi à plusieurs destinataires dynamiquement
| emails = [
{"to": "alice@example.com", "subject": "Bonjour Alice", "body": "Salut Alice !"},
{"to": "bob@example.com", "subject": "Bonjour Bob", "body": "Salut Bob !", "attachments": ["rapport.pdf"]}
]
yag = yagmail.SMTP("votre_email@gmail.com")
for email in emails:
yag.send(to=email["to"], subject=email["subject"], contents=email["body"], attachments=email.get("attachments"))
print(f"Email envoyé à {email['to']}")
|
3.6 Lecture des emails depuis un CSV
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | import pandas as pd
df = pd.read_csv("emails.csv")
yag = yagmail.SMTP("votre_email@gmail.com")
for _, row in df.iterrows():
to = row["to"]
subject = row["subject"]
body = row["body"]
attachments = row.get("attachments", None)
if pd.notna(attachments) and attachments.strip() != "":
attachments = [att.strip() for att in attachments.split(";")]
else:
attachments = None
yag.send(to=to, subject=subject, contents=body, attachments=attachments)
print(f"Email envoyé à {to}")
|
Exemple de format CSV :
| to,subject,body,attachments
alice@example.com,Bonjour Alice,"Salut Alice, ceci est ton message !",
bob@example.com,Bonjour Bob,"Salut Bob, voici ta mise à jour !","rapport.pdf"
|
3.7 Envoyer des emails HTML
| html_content = """
<html>
<body>
<h1 style="color:blue;">Bonjour !</h1>
<p>Ceci est un email <b>HTML</b> envoyé depuis Python.</p>
</body>
</html>
"""
yag.send(to="destinataire@example.com", subject="Email HTML", contents=html_content)
|
4. Utilisation des API Email (Optionnel, pas besoin d’email personnel)
Pour des envois automatisés ou à grande échelle sans utiliser Gmail :
- SendGrid
- Mailgun
- Amazon SES
Exemple avec SendGrid :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 | import requests
api_key = "VOTRE_API_KEY_SENDGRID"
url = "https://api.sendgrid.com/v3/mail/send"
data = {
"personalizations": [{"to": [{"email": "destinataire@example.com"}]}],
"from": {"email": "no-reply@mondomaine.com"},
"subject": "Bonjour depuis Python",
"content": [{"type": "text/plain", "value": "Ceci est un email de test."}]
}
response = requests.post(url, json=data, headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
})
print(response.status_code, response.text)
|
5. Conseils de sécurité
- Ne jamais coder en dur les mots de passe. Utilisez
yagmail.register() ou des variables d’environnement.
- Pour Gmail, utilisez toujours les mots de passe d’application si la double authentification est activée.
- Évitez d’envoyer des informations sensibles par email.
6. Résumé
smtplib : intégré, bas niveau, nécessite une configuration manuelle.
yagmail : haut niveau, simple, supporte les pièces jointes, HTML et l’automatisation via CSV.
- APIs : idéales pour les solutions à grande échelle ou sans email personnel.
Ce tutoriel fournit un outil complet pour envoyer des emails avec Python, des scénarios simples aux automatisations avancées.
Références