How to send a file to mail using python
There are several ways to send a file via email using Python. Here are a few options:
Option 1: Using the smtplib
library
You can use the smtplib
library to send an email with an attachment. Here's an example:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders
# Set up the email server
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('[email protected]', 'your_password')
# Create the email message
msg = MIMEMultipart()
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
msg['Subject'] = 'File attachment'
msg['Date'] = formatdate(localtime=True)
# Add the file attachment
attachment = open('path/to/your/file.txt', 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="file.txt"')
msg.attach(part)
# Send the email
server.sendmail('[email protected]', '[email protected]', msg.as_string())
server.quit()
Option 2: Using the yagmail
library
yagmail
is a Python library that makes it easy to send emails with attachments. Here's an example:
import yagmail
# Set up the email server
yag = yagmail.SMTP('[email protected]', 'your_password')
# Send the email with attachment
yag.send('[email protected]', 'File attachment', 'path/to/your/file.txt')
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:
import email
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
# Create the email message
msg = MIMEMultipart()
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
msg['Subject'] = 'File attachment'
msg['Date'] = email.utils.formatdate(localtime=True)
# Add the file attachment
attachment = open('path/to/your/file.txt', 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="file.txt"')
msg.attach(part)
# Send the email
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('[email protected]', 'your_password')
server.sendmail('[email protected]', '[email protected]', msg.as_string())
server.quit()
Make sure to replace the placeholders ([email protected]
, your_password
, [email protected]
, and path/to/your/file.txt
) with your actual email credentials and file path.
Also, note that you may need to enable "Less secure app access" in your Google account settings if you're using Gmail.