Python code to send emails to anyone
To send emails in Python, you can use the built-in smtplib
module, which allows you to connect to an SMTP (Simple Mail Transfer Protocol) server and send email messages. Additionally, you can use the email
module to create and format email messages. Here's a step-by-step guide on how to send an email using Python:
Import necessary modules:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
Set up your email and SMTP server details:
Replace these values with your own email and SMTP server details sender_email = 'your_email@example.com' receiver_email = 'recipient_email@example.com'
smtp_server = 'smtp.example.com'
smtp_port = 587 # Use 465 for SSL/TLS connections smtp_username = 'your_email@example.com' smtp_password = 'your_email_password
Compose the email message:
subject = 'Test Email'
body = 'This is a test email sent from Python.'
# Create a MIMEText object to represent the email body
msg = MIMEText(body)
# Add the sender, recipient, and subject to the email headers
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
Connect to the SMTP server and send the email:
try:
# Connect to the SMTP server
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls() # Upgrade the connection to a secure SSL/TLS connection
# Log in to the SMTP server
server.login(smtp_username, smtp_password)
# Send the email
server.sendmail(sender_email, receiver_email, msg.as_string())
print('Email sent successfully!')
except Exception as e:
print(f'Error sending email: {e}')
finally:
# Close the connection to the SMTP
server server.quit()
Make sure to replace the placeholder values in the
sender_email
,sender_password
, andreceiver_emails
variables with appropriate email addresses and credentials. Thesend_email
function will send the email to all the recipients listed in thereceiver_emails
list.Note that in the above example, we are assuming you are using Gmail as the SMTP server. If you are using a different SMTP server, make sure to modify the
smtp_server
andsmtp_port
variables accordingly. Additionally, be aware that some email providers may require you to enable "less secure apps" or generate an "app password" for the script to work correctly. Always take appropriate security measures when handling email credentials in your code.