How to Send Emails with Python’s smtplib

SMTP  

Simple Mail Transfer Protocol

 

Credentials

Any email provider will work, but for this tutorial I’ll show how to get your credentials using Gmail 

  1. Go to your Google Account: https://myaccount.google.com/

  2. In the search bar, type “App passwords” and open that page.

  3. Choose a name for your app and click Create.

  4. Copy the generated password and keep it somewhere secure.



              
  logo.png             sample.pdf
 

import smtplib
from email.message import EmailMessage
from pathlib import Path

smtp_server = "smtp.gmail.com"
smtp_port = 587
username = "jcaetano1930@gmail.com"
password = "***"

msg = EmailMessage()
msg["From"] = username
msg["To"] = "jaimedcsilva@hotmail.com"
msg["Subject"] = "Example of an email with some content!"

#Plain Text
msg.set_content("Your email client does not support HTML.")

#Html
html = """
<html>
  <body>
    <img src="cid:logo">
    <p>Ever make mistakes in life? Let's make them birds.</p>
  </body>
</html>
"""

msg.add_alternative(html, subtype="html")

#Attachment
file_path = "sample.pdf"
file_data = Path(file_path).read_bytes()

msg.add_attachment(file_data, maintype="application", subtype="pdf", filename=file_path)

#Embedded Image
img_data = Path("logo.png").read_bytes()

html_part = msg.get_payload()[1]
html_part.add_related(img_data, maintype="image", subtype="png", cid="logo")


try:
    with smtplib.SMTP(smtp_server, smtp_port) as server:
        server.starttls()
        server.login(username, password)
        server.send_message(msg)

    print("E-mail sent!")

except Exception as e:
    print("Error:", e)

 





18 Nov. 2025 | Last Updated: 02 Dec. 2025 | jaimedcsilva

Related
  • Printing CMD with colors
  • Calculating & Displaying crypto currency with CoinGecko
  • Creatin an .exe file to run a Python script
  • Getting certificate chains from websites
  • Getting the complete trustchain of a website
  • Installing pip in embedded Python - Full Guide
  • Cython - Hiding Python Code
  • How to Send Emails with Python’s smtplib
  • Generating QR Codes with Python

  • Buy Me a Coffee