Send the Email
Now that your email message is ready (with headers, body, and any attachments), the final step is to connect to your email server and send it.
Step-by-Step Code Example
import smtplib
import ssl
# Create a secure SSL context
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(sender, password)
server.send_message(msg)
print("Email sent successfully")
Explanation of Key Elements
-
smtplib.SMTP_SSL()
Connects to the SMTP server using SSL encryption for secure communication. -
"smtp.gmail.com"and port465
These are Gmail’s SMTP server settings.
Replace them with your provider’s info if using Outlook, Yahoo, etc. -
server.login(sender, password)
Logs in using the credentials you loaded earlier withos.environ.get(). -
server.send_message(msg)
Sends the completeEmailMessageobject. -
withblock
Automatically handles connection closing after the email is sent.
Other SMTP Servers (Examples):
| Provider | SMTP Address | Port |
|---|---|---|
| Gmail | smtp.gmail.com | 465 |
| Outlook | smtp.office365.com | 587 |
| Yahoo Mail | smtp.mail.yahoo.com | 465 |
Yahoo has disabled and is not usable, just for information
🔐 Make sure your email account allows third-party SMTP access or app passwords.
