send excel attachment through outlook using python - 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()

Related

Send video file via mail python

I'm trying to send example.mp4 file with mail in below codes. Mail send successfully. But when I download the video in related mail. Video is not working after download from mail. But normally video is working successfully.Where is my fault ?
import smtplib
from email import message, encoders
from email.message import EmailMessage
from email.mime.base import MIMEBase
from os.path import basename
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from_addr = 'FROM_MAIL'
to_addr = 'TO_ADDRESS'
subject = 'I just sent this email from Python!'
content = 'Test'
# Initializing video object
video_file = MIMEBase('application', "octet-stream")
# Importing video file
video_file.set_payload(open('example.mp4', "rb").read())
# Encoding video for attaching to the email
encoders.encode_base64(video_file)
# creating EmailMessage object
msg = MIMEMultipart()
# Loading message information ---------------------------------------------
msg['From'] = "person_sending#gmail.com"
msg['To'] = "person_receiving#gmail.com"
msg['Subject'] = 'text for the subject line'
msg.set_content('text that will be in the email body.')
msg.add_attachment(video_file, filename="example.mp4")
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(from_addr, 'APP_PASS')
server.send_message(msg, from_addr=from_addr, to_addrs=[to_addr])
Adding this did it for me:
video_file.add_header('Content-Disposition',
'attachment; filename={}'.format("test.mp4"))

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

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()

How do I attach separate PDF's to contact list email addresses using Python?

I have written a script that sends individual emails to all contacts in an Excel table. The table looks like this:
Names Emails PDF
Name1 Email1#email.com PDF1.pdf
Name2 Email2#email.com PDF2.pdf
The code I have so far is as follows:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from string import Template
import pandas as pd
e = pd.read_excel("Contacts.xlsx")
emails = e['Email'].values
PDF = e['PDF'].values
print(emails, PDF)
server = smtplib.SMTP(host='smtp.outlook.com', port=587)
server.starttls()
server.login('sender_email','sender_password')
msg = ("""
Hi there
Test message
Thankyou
""")
subject = "Send emails with attachment"
body = "Subject: {}\n\n{}".format(subject,msg)
for emails in emails:
server.sendmail('sender_email',emails,body)
print("Emails sent successfully")
server.quit()
Question: How can I look up the correct attachment (column 3) for each e-mail address (column 2) and attach it to the email using Python?
I made a little changes , and make you sure the pdf field has the pdf path
Edit:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from string import Template
import pandas as pd
#e = pd.read_csv("Contacts.csv")
e = pd.read_excel("Contacts.xlsx")
server = smtplib.SMTP(host='smtp.outlook.com', port=587)
server.starttls()
server.login('yourmail#mail.com','yourpass')
body = ("""
Hi there
Test message
Thankyou
""")
subject = "Send emails with attachment"
fromaddr='yourmail#mail.com'
#body = "Subject: {}\n\n{}".format(subject,msg)
#Emails,PDF
for index, row in e.iterrows():
print (row["Emails"]+row["PDF"])
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
filename = row["PDF"]
toaddr = row["Emails"]
attachment = open(row["PDF"], "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()
server.sendmail(fromaddr, toaddr, text)
#server.sendmail('sender_email',emails,body)
print("Emails sent successfully")
server.quit()

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")

Unable to send html file content as email body in python

I have a html file whose contents I want to send in the email body using python. Below is the python script:
import smtplib,email,email.encoders,email.mime.text,email.mime.base
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import codecs
msg = MIMEMultipart()
# me == my email address
# you == recipient's email address
me = "a#b.com"
you = "b#a.com"
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('mixed')
msg['Subject'] = "Automation Testing"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
f = codecs.open('/Users/test.htm')
html = f.read()
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part2)
composed = msg.as_string()
fp = open('msgtest.txt', 'w')
fp.write(composed)
# Credentials (if needed)
# The actual mail send
server = smtplib.SMTP('smtp.a.com', 25)
server.starttls()
server.sendmail(me, you, composed)
server.quit()
fp.close()
But, it is sending only an empty email with no html content in the body. Please tell me how to fix this.

Categories