Thursday, 18 April 2024

send email using using smtp python

 To send an email using SMTP in Python, you can use the smtplib library. Below is a basic example demonstrating how to send an email using Gmail's SMTP server:


import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # Email credentials sender_email = "your_email@gmail.com" sender_password = "your_password" receiver_email = "recipient_email@gmail.com" # Create a multipart message message = MIMEMultipart() message["From"] = sender_email message["To"] = receiver_email message["Subject"] = "Test Email" # Add body to email body = "This is a test email sent from Python using SMTP." message.attach(MIMEText(body, "plain")) # Connect to Gmail's SMTP server server = smtplib.SMTP("smtp.gmail.com", 587) server.starttls() # Log in to the SMTP server server.login(sender_email, sender_password) # Send email server.sendmail(sender_email, receiver_email, message.as_string()) # Close the SMTP server connection server.quit() print("Email sent successfully!")



Make sure to replace "your_email@gmail.com" and "your_password" with your Gmail email address and password, respectively. Also, replace "recipient_email@gmail.com" with the recipient's email address.

Note: If you're using two-factor authentication (2FA) with Gmail, you'll need to generate an app password for your Python script. You can do this in your Google Account settings. Also, keep in mind that Google may block sign-in attempts from unknown locations or apps, so you might need to allow less secure apps access to your Google account temporarily or use OAuth2 for authentication.

No comments:

Post a Comment

python code to Twilio SMS

Here's an example of a TwilioSMS class that you can use to send SMS messages using the Twilio Python helper library: import os from twil...