33: Python Program to send an email vid GMail


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


Solution:
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.starttls()
        server.login(sender_email, sender_password)
        server.send_message(email_message)

    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!"
}

send_email_via_gmail(email_details)

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