There are several ways to create an Excel attachment for an email using Python:
import pandas as pd
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# Create DataFrame
data = {'Name': ['John', 'Jane', 'Alice', 'Bob'], 'Age': [25, 30, 35, 40]}
df = pd.DataFrame(data)
# Create Excel file
writer = pd.ExcelWriter('data.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
writer.save()
# Create email message
msg = MIMEMultipart()
msg['Subject'] = 'Excel Attachment'
msg['From'] = 'sender@email.com'
msg['To'] = 'recipient@email.com'
# Attach Excel file
with open('data.xlsx', 'rb') as f:
attach = MIMEApplication(f.read(), _subtype='xlsx')
attach.add_header('Content-Disposition', 'attachment', filename='data.xlsx')
msg.attach(attach)
# Send email
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('sender@email.com', 'password')
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
import openpyxl
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# Create Excel file
wb = openpyxl.Workbook()
ws = wb.active
ws.title = 'Sheet1'
ws.cell(row=1, column=1, value='Name')
ws.cell(row=1, column=2, value='Age')
ws.append(['John', 25])
ws.append(['Jane', 30])
ws.append(['Alice', 35])
ws.append(['Bob', 40])
wb.save('data.xlsx')
# Create email message
msg = MIMEMultipart()
msg['Subject'] = 'Excel Attachment'
msg['From'] = 'sender@email.com'
msg['To'] = 'recipient@email.com'
# Attach Excel file
with open('data.xlsx', 'rb') as f:
attach = MIMEApplication(f.read(), _subtype='xlsx')
attach.add_header('Content-Disposition', 'attachment', filename='data.xlsx')
msg.attach(attach)
# Send email
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('sender@email.com', 'password')
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
Note: In both examples, you will need to replace the email addresses and password with your own credentials. Also, make sure to have the necessary libraries installed before running the code.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-06-24 11:00:00 +0000
Seen: 10 times
Last updated: May 01 '21
How can popen() be used to direct streaming data to TAR?
In Python, can a string be utilized to retrieve a dataframe that has the same name as the string?
What is the method for merging field value and text into a singular line for display?
What is the method for programmatic access to a time series?