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)
-
Facing issues? Have Questions? Post them here! I am happy to answer!
More Posts related to Python,
- Python: Convert Date to DateTime
- How to sort a List using Lambda in Python
- Python matplotlib segmentation fault: 11 macOS Big Sur
- What is Terminal Velocity and its Formula? How to calculate it programmatically?
- How to install Python 3.11 on Mac
- How to flatten a nested list in Python
- Python: Pandas Merge DataFrames on Index Example
- How to Run all Cells at Once Jupyter Notebook
- Python - Convert float to String
- How to add borders to tkinter label text
- How to Exit a Loop in Python Code
- [Python] Fix: ValueError: All arrays must be of the same length
- Sorting an array using Bubble Sort in Python Programming
- How to Unzip a file using Python
- Python: Merge DataFrames Pandas Outer Join Example
- Change label (text) color in tkinter
- Convert Float to String in Python
- Fix: fatal error: No such file or directory compilation terminated
- Python: Access index/counter of a for loop iteration
- Import Other Python Files Examples
- How to install Anaconda on Mac (M1/M2 Mac)
- Python Regular Expression to Find All Matches in List
- How to Read a binary File with Python
- How to disable warnings while Python file execution
- Know current Python Version
More Posts:
- apt-get list --installed packages in Ubuntu Linux - Ubuntu
- How to get unique values from a list in Python - Python
- SQL: Check if table exists - HowTos
- What is $$ in Bash Shell Script- Special Variable - Bash
- Open New tab using keyboard shortcut in Mac Terminal - Mac-OS-X
- W3 HTML validator warning Unable to Determine Parse Mode - Html
- Show Hidden Files in Mac Terminal - MacOS
- Disable Fading Edges Scroll Effect Android Views - Android