top of page
Send Email Basic

import smtplib

# Email configuration
sender_email = "scotthead57@gmail.com"
receiver_email = "scott@scriptsbyscott.com"
password = "xxxxxxx"  # Use app passwords if 2FA is enabled

subject = "Test Email"
body = "This is a simple test email sent from Python."

# Combine subject and body
message = f"Subject: {subject}\n\n{body}"

# Sending email
try:
    # Connect to the Gmail SMTP server
    with smtplib.SMTP("smtp.gmail.com", 587) as server:
        server.starttls()  # Upgrade the connection to secure
        server.login(sender_email, password)  # Log in to your email account
        server.sendmail(sender_email, receiver_email, message)  # Send the email
        print("Email sent successfully!")
except Exception as e:
    print("Error:", e)
 

Send Email with Attachment

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

# Email configuration
sender_email = "scotthead57@gmail.com"
receiver_email = "scott@scriptsbyscott.com"
password = "xxxxxxx"  # Use an app password if 2FA is enabled

# Email subject and body
subject = "Test Email with Attachment"
body = "This email contains an attachment sent from Python."

# Create the email message
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject

# Attach the email body
message.attach(MIMEText(body, "plain"))

# File to attach
filename = "services_info.csv"  # Replace with your file's name
filepath = "c:/PYTHON/Scripts/services_info.csv"  # Replace with the full file path

try:
    # Open the file in binary mode and attach it
    with open(filepath, "rb") as attachment:
        part = MIMEBase("application", "octet-stream")
        part.set_payload(attachment.read())

    # Encode the file for safe transport
    encoders.encode_base64(part)

    # Add headers to the attachment
    part.add_header(
        "Content-Disposition",
        f"attachment; filename={filename}",  # File name as it will appear in the email
    )

    # Attach the file to the email
    message.attach(part)

    # Send the email
    with smtplib.SMTP("smtp.gmail.com", 587) as server:
        server.starttls()  # Upgrade the connection to secure
        server.login(sender_email, password)  # Log in to your email account
        server.sendmail(sender_email, receiver_email, message.as_string())  # Send the email
        print("Email with attachment sent successfully!")
except Exception as e:
    print("Error:", e)
 

bottom of page