33: Python Program to send an email vid GMail

Q 33: Write a program in Python to send an Email.

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

def send_email_via_gmail(email_details):
    sender_email = email_details.get("sender_email")
    sender_password = email_details.get("sender_password")
    receiver_email = email_details.get("receiver_email")
    email_subject = email_details.get("email_subject")
    email_body = email_details.get("email_body")

    smtp_server = "smtp.gmail.com"
    smtp_port = 587

    email_message = MIMEMultipart()
    email_message["From"] = sender_email
    email_message["To"] = receiver_email
    email_message["Subject"] = email_subject
    email_message.attach(MIMEText(email_body, "plain"))

    with smtplib.SMTP(smtp_server, smtp_port) as server:
        server.login(sender_email, sender_password)

    print("The email has been sent successfully!")

email_details = {
    "sender_email": "sender-email-id@gmail.com",
    "sender_password": "sender-password-goes-here",
    "receiver_email": "recipient-email@example.com",
    "email_subject": "This email has been sent via Python Code!",
    "email_body": "Hello! This is a test email sent via Python code!"


Please replace the sender_email, sender_password and receiver_email.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap