Skip to content

PY Gmail integration

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# Your credentials
gmail_user = 'your_email@gmail.com'
gmail_password = 'your_password'

# Email parameters
to = 'recipient_email@example.com'
subject = 'Hello from Python'
body = 'This is a test email sent from a Python script using smtplib.'

# Setting up the MIME
message = MIMEMultipart()
message['From'] = gmail_user
message['To'] = to
message['Subject'] = subject

# Attach the body with the msg instance
message.attach(MIMEText(body, 'plain'))

# Create SMTP session for sending the mail
try:
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(gmail_user, gmail_password)
    text = message.as_string()
    server.sendmail(gmail_user, to, text)
    server.close()

    print("Email sent successfully!")
except Exception as e:
    print(f"Error: {e}")