Program 10
Write a python program to sending email using SMTPlib.
Aim
To write a python to sending email using SMTPlib.
Algorithm
Step1: Start the process.
Step2: Open PyCharm Community Edition 2021.3.2.
Step3: Import necessary modules:
i) SMTP lib for handling SMPT communication
ii) MIME Multipart and MIME text from email mime multipart for creating email content
Step4: Set up email parameters:
Login in G-mail ->manage account->security->switch on two-step verification->enter the
app name->password will be generated automatically to work with the G-mails SMTP server.
Step5: Set SMTP server and port.
Step6: Try to send the mail by establishing connection to the SMTP server.
Step7: Print an error message if any exception occur during the sending process.
Step8: Close the SMTP connection to ensure proper cleanup.
Step9: Print success message if the mail send successfully.
Step10: Stop the process.
Write a python program to sending email using SMTPLib.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
sender_email = "
[email protected]"
sender_password = "kkyi ybmq pynw ryve"
recipient_email = "[email protected]"
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = recipient_email
message["Subject"] = "Test Email from Python"
body = "This is a test email sent from Python."
message.attach(MIMEText(body, "plain"))
smtp_server = "smtp.gmail.com"
smtp_port = 587
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(sender_email, sender_password)
text = message.as_string()
server.sendmail(sender_email, recipient_email, text)
print("Email sent successfully!")
except Exception as e:
print("Error:", e)
finally:
server.quit()
output :
C:\Users\TEMP.CTIT.119\PycharmProjects\pythonProject\venv\bin\python.exe
C:/Users/TEMP.CTIT.119/PycharmProjects/pythonProject/smt.py
Email sent successfully!
Process finished with exit code 0
Result
Thus the program for sending mail using SMTP has been executed and verified successfully.