How to send mail through python

There are several ways to send mail using Python. Here are a few options:

Option 1: Using the smtplib library

The smtplib library is a built-in Python library that allows you to send emails using a Simple Mail Transfer Protocol (SMTP) server. Here's an example code snippet:

import smtplib

# Set up the SMTP server
server = smtplib.SMTP('smtp.gmail.com', 587)  # Replace with your SMTP server

# Set up the email sender and recipient
from_addr = '[email protected]'
to_addr = '[email protected]'

# Set up the email message
subject = 'Test email from Python'
body = 'This is a test email sent from Python.'

# Send the email
server.sendmail(from_addr, to_addr, f'Subject: {subject}\n\n{body}')

# Close the SMTP connection
server.quit()

Option 2: Using the yagmail library

The yagmail library is a popular Python library that provides a simple way to send emails. Here's an example code snippet:

import yagmail

# Set up the email sender and recipient
from_addr = '[email protected]'
to_addr = '[email protected]'

# Set up the email message
subject = 'Test email from Python'
body = 'This is a test email sent from Python.'

# Send the email
yag = yagmail.SMTP(from_addr)
yag.send(to_addr, subject, body)

Option 3: Using the email library

The email library is a built-in Python library that allows you to create and send emails. Here's an example code snippet:

import email
import smtplib

# Set up the email sender and recipient
from_addr = '[email protected]'
to_addr = '[email protected]'

# Set up the email message
msg = email.MIMEMultipart()
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = 'Test email from Python'
body = 'This is a test email sent from Python.'
msg.attach(email.MIMEText(body, 'plain'))

# Send the email
server = smtplib.SMTP('smtp.gmail.com', 587)  # Replace with your SMTP server
server.sendmail(from_addr, to_addr, msg.as_string())
server.quit()

Additional tips