Is there a way to send email with a dataframe attachment? - python

I currently have a script that manipulates a .csv file using pandas. I'm trying to send a MIMEMultipart email with the latest .csv version of the file that has been amended but for some reason, the email recipients keep receiving an older unaltered version of the .csv that I trying to send. I'm trying to make sense of it in my head because the old version of the .csv file is written over before it is sent but the original version of the .csv is sent to the recipients.
Maybe I need to specify a path for smtplib to get the file as opposed to just giving the name of the file. Is there a way to do that or is there another way around my problem? I've already tried to change the name to something else in order for smtplib to be able to differentiate between the old .csv and the new one.
This doesn't work though as the file is placed in the directory but my script says that the new file doesn't exist
This is my current code:
email_user = 'Bot#gmail.com'
email_password = 'Business101'
email_send = ('myemail#gmail.com', 'myfriendsemail#gmail.com')
subject = 'TOP 5 CONTRACTS'
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = ",".join(email_send)
msg['Subject'] = subject
body = 'These are the latest contracts for this week!'
msg.attach(MIMEText(body,'plain'))
filename='CC.csv'
attachment =open(filename,'rb')
part = MIMEBase('application','octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment; filename= "+filename)
msg.attach(part)
text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(email_user,email_password)
server.sendmail(email_user,email_send,text)
server.quit()
print("Emailed Recipients")
Might be worth mentioning that this process is an automated one so the script is being run from a Unix Executable file on my mac.
If you can assist, I'd really appreciate it!

This has been the best way to do it, thanks
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from smtplib import SMTP
import smtplib
import sys
import pandas as pd
df_test = pd.read_csv('/Users/emmanuelafoke/Documents/Selenium/CC.csv')
email_user = 'myemailaddress#gmail.com'
email_password = 'mypassword'
recipients = ['theiremailaddress#gmail.com']
emaillist = [elem.strip().split(',') for elem in recipients]
msg = MIMEMultipart()
msg['Subject'] = 'SUBJECT'
msg['From'] = 'myemailaddress#gmail.com'
html = """\
<html>
<head></head>
<body>
{0}
</body>
</html>
""".format(df_test.to_html())
part1 = MIMEText(html, 'html')
msg.attach(part1)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email_user,email_password)
server.sendmail(msg['From'], emaillist , msg.as_string())
Thanks for all of your help!

You could actually do this by using the following libraries: email.mime.application, MIMEApplication, email.mime.multipart and email.mime.text. Now, I don't know which client you are using and you might have to do some adjustments to this.
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
SEND_FROM = 'myaddress#client.com' ## Your email address
TOSEND = {'dataframe.csv': export_csv, 'dataframe.xlsx': export_my_excel}
def send_dataframe(send_to, subject, body, df):
multipart = MIMEMultipart()
multipart['From'] = SEND_FROM
multipart['To'] = send_to
multipart['Subject'] = subject
for filename in EXPORTERS:
attachment = MIMEApplication(TOSEND[filename](df)) ### Here is where the df is attached
attachment['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
multipart.attach(attachment)
multipart.attach(MIMEText(body, 'html'))
s = smtplib.SMTP('localhost')
s.sendmail(SEND_FROM, send_to, multipart.as_string())
s.quit()
In send_dataframe() you'll have to put the df you want to attach. This is where TOSEND come in. As you see, there is a function called export_my_excel. You can create it as
import io
import pandas as pd
def export_my_excel(df):
with io.BytesIO() as buffer:
writer = pd.ExcelWriter(buffer)
df.to_excel(writer)
writer.save()
return buffer.getvalue()

Related

send excel attachment through outlook using python

Below is the code i'm using to send excel as a attachment to outlook email using python 2.7 version. If i command the attachment lines in the code, i could send the text email but not the attached email.Also i'm not receiving any error. Can somebody please help me identify the issue in the code.
import psycopg2
import pandas as pd
import numpy as np
import xlsxwriter
from datetime import date
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import smtplib
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
server = smtplib.SMTP(host='xxxxx.net', port=25)
fromaddr = "aaaaaaaaabb#outlook.com"
RECIPIENTS = "aaaaaaaaabb#outlook.com"
msg = MIMEMultipart()
body = """
Hi Team, <br>
<br>
Please find the attached data sync validation betweeen Reltio and BDS .<br>
<br>
Please reach out to Team for any questions.<br>
<br>
Regards,<br>
xxxx <br>
Support Team<br>"""
subject = 'Reltio and BDS Data Sync for EU Org'
msg = MIMEMultipart("alternative", None, [MIMEText(body, 'html','utf-8')])
msg['To'] = RECIPIENTS
msg['From'] = "axxxxxyyy#.net"
msg['Subject'] = subject
stg = MIMEBase('application', 'vnd.ms-excel')
stg.set_payload(open("EU_Consent.xlsx", "rb").read())
encoders.encode_base64(stg)
stg.add_header('Content-Disposition', 'attachment', filename="EU_Consent.xlsx")
msg.attach(stg)
server.ehlo()
server.starttls()
server.ehlo()
text = msg.as_string()
server.sendmail(fromaddr, RECIPIENTS, text)
server.quit()
path='/xxx/yyyy/zzz/file.xlsx'
fp=open(path, 'rb')
stg = MIMEBase('application','vnd.openxmlformatsofficedocument.spreadsheetml.sheet')
stg.set_payload(fp.read())
fp.close()

Trying to create an email script, yet not all recipients receive the email

The email sends and shows that it sends to both listed recipients, but only the first listed one actually receives the message. Strange since I don't notice anything particularly wrong with how I entered the addresses in (based on other examples I came across), so I'm looking for another perspective on the issue.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
email_user = 'myemail#gmail.com'
email_send = 'otheremail1#gmail.com, otheremail2#gmail.com'
subject = 'Test'
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject
body = """Hello,
This is a test.
Thanks!"""
msg.attach(MIMEText(body,'plain'))
filename='dataset.csv'
attachment =open(filename,'rb')
part = MIMEBase('application','octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment; filename= "+filename)
msg.attach(part)
text = msg.as_string()
server = smtplib.SMTP('smtp.office365.com',587)
server.starttls()
server.login(email_user,'password')
server.sendmail(email_user,email_send,text)
server.quit()
server.sendmail(email_user,email_send.split(','),text) and remove the space
Basically you only sent the first one and need to pass the other one.

How attach pandas dataframe as excel in email triggered from python

I have a pandas dataframe which I want attach as xls in an automated email triggered from python. How can this be done
I am able to send the email without attachment successfully but not with the attachment.
My code
import os
import pandas as pd
#read and prepare dataframe
data= pd.read_csv("C:/Users/Bike.csv")
data['Error'] = data['Act'] - data['Pred']
df = data.to_excel("Outpout.xls")
# import necessary packages
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
# create message object instance
msg = MIMEMultipart()
password = "password"
msg['From'] = "xyz#gmail.com"
msg['To'] = "abc#gmail.com"
msg['Subject'] = "Messgae"
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
# Login Credentials for sending the mail
server.login(msg['From'], password)
server.sendmail(msg['From'], msg['To'], msg.as_string())
As pointed out in comment you are not attaching the file, so it would not be sent.
msg.attach(MIMEText(body, 'plain'))
filename = "Your file name.xlsx"
attachment = open("/path/to/file/Your file name.xlsx","rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment; filename=%s" % filename)
msg.attach(part)
text = msg.as_string()
smtp0bj.sendmail(msg['From'], msg['To'], text)
Hope it helps

Python email PDF: Some PDFs Getting Corrupted

I am trying to attach a PDF file to an e-mail message.
For one PDF (a Word document printed to PDF), it works (the recipient opens it in Outlook with no problem).
Yet for other PDFs (which seem the same except for being a few KBs larger), they get corrupted.
Here is a sample to use which fails (becomes corrupted).
import smtplib, os
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.utils import formatdate
from email import encoders
attachment_path=r'C:\Directory'+'\\'
login='login'
password='password'
part=MIMEBase('application',"octet-stream")
def message(attachment): #attachment is just the PDF file name
fromaddr = "example#example.com"
cc=fromaddr
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = "example#example.com"
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = "Subject"
body='''
<!DOCTYPE html>
<html>
<body>
<p><font face="Tahoma" size=2> I hope everything is going well.</p></font>
</body>
</html>
'''
msg.attach(MIMEText(body, 'html'))
part.set_payload(open(attachment_path+attachment,'rb').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(attachment_path+attachment)))
msg.attach(part)
mail=smtplib.SMTP('Server',587)
mail.ehlo()
mail.starttls()
mail.login(login,password)
mail.sendmail(fromaddr,[toaddr,cc],msg.as_string())
I have tried using the following instead of base 64 encoding, but to no avail:
encoders.encode_noop(part)
encoders.encode_7or8bit(part)
encoders.encode_quopri(part)
Thanks in advance!
All I had to do was move this:
part=MIMEBase('application',"octet-stream")
to just above:
part.set_payload(open(attachment_path+attachment,'rb').read())
I have used below line of code and it is working fine for me.
part=MIMEBase('application/pdf',"octet-stream")

Sending attachment in HTML email with Python

I saw there are a few somewhat similar questions on stack overflow already, but I couldn't find a solution to my specific problem in them.
I am trying to use Python to send an HTML email with a .pdf attachment. It seems to work fine when I check my email on gmail.com, but when I check the message through apple's Mail program, I do not see the attachment. Any idea what is causing this?
My code is below. A lot of it is copied from various places on stack overflow, so I do not completely understand what each part is doing, but it seems to (mostly) work:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from os.path import basename
import email
import email.mime.application
#plain text version
text = "This is the plain text version."
#html body
html = """<html><p>This is some HTML</p></html>"""
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Deliverability Report"
msg['From'] = "me#gmail.com"
msg['To'] = "you#gmail.com"
# Record the MIME types of both parts - text/plain and text/html
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# create PDF attachment
filename='graph.pdf'
fp=open(filename,'rb')
att = email.mime.application.MIMEApplication(fp.read(),_subtype="pdf")
fp.close()
att.add_header('Content-Disposition','attachment',filename=filename)
# Attach parts into message container.
msg.attach(att)
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
s = smtplib.SMTP()
s.connect('smtp.webfaction.com')
s.login('NAME','PASSWORD')
s.sendmail(msg['From'], msg['To'], msg.as_string())
s.quit()
I'm not sure if it is relevant, but I am running this code on a WebFaction server.
Thanks for the help!
To have text, html and attachments at the same time it is necessary to use both mixed and alternative parts.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
text = "This is the plain text version."
html = "<html><p>This is some HTML</p></html>"
text_part = MIMEText(text, 'plain')
html_part = MIMEText(html, 'html')
msg_alternative = MIMEMultipart('alternative')
msg_alternative.attach(text_part)
msg_alternative.attach(html_part)
filename='graph.pdf'
fp=open(filename,'rb')
attachment = email.mime.application.MIMEApplication(fp.read(),_subtype="pdf")
fp.close()
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
msg_mixed = MIMEMultipart('mixed')
msg_mixed.attach(msg_alternative)
msg_mixed.attach(attachment)
msg_mixed['From'] = 'me#gmail.com'
msg_mixed['To'] = 'you#gmail.com'
msg_mixed['Subject'] = 'Deliverability Report'
smtp_obj = smtplib.SMTP('SERVER', port=25)
smtp_obj.ehlo()
smtp_obj.login('NAME', 'PASSWORD')
smtp_obj.sendmail(msg_mixed['From'], msg_mixed['To'], msg_mixed.as_string())
smtp_obj.quit()
Message structure should be like this:
Mixed:
Alternative:
Text
HTML
Attachment
Use
msg = MIMEMultipart('mixed')
instead of 'alternative'

Categories