How to send pandas dataframe in python mail - python

I am trying to send pandas table in python mail.i tried but can't get the result.also convert pandas dataframe to html
here is my code.
please help
code
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import pandas as pd
def sendMail(ID,NAME,MARKS):
dict = {'ID': ID, 'NAME':NAME, 'MARKS': MARKS}
da = pd.DataFrame(dict)
df=da.to_html()
try:
email = "EMAIL#gmail.COM"
password = 'PASSWORD'
send_to_email =["EMAIL#gmail.COM",]
subject = 'Critical Incident'
messageHTML = '{df}'
messagePlain = 'marks of your class'
print(messageHTML)
msg = MIMEMultipart('alternative')
msg['From'] = email
msg['To'] = ', '.join(send_to_email)
msg['Subject'] = subject
msg.attach(MIMEText(messagePlain, 'plain'))
msg.attach(MIMEText(messageHTML, 'html'))
server = smtplib.SMTP("smtp.gmail.com",587)
server.starttls()
server.login(email, password)
text = msg.as_string()
server.sendmail(email, send_to_email, text)
server.quit()

I found the answer
df=da.to_html()
ds=str(df)
messageHTML = 'marks'+ds

Related

Python Command '[ ... ]' returned non-zero exit status 1

I'm trying to get a file from BigQuery, convert it to excel format and sending it attached in an email. Here is my code:
def run(**kwargs):
from datetime import datetime
from google.cloud import bigquery
import pandas as pd
def from_bq_to_dataframe(sql_location):
client = bigquery.Client()
with open(sql_location) as file:
sql = file.read()
df = client.query(sql).to_dataframe()
return df
def filter_and_excel(df):
df = df.nlargest(1000, ['cant_form_final'])
writer = pd.ExcelWriter('Document_name' + '_' + datetime.now().strftime('%Y/%m/%d'))
df = df.to_excel(writer, 'review_document') #Sheet name
return df
def send_mail(subject, text, send_to, send_to_cc=[], file=None):
import smtplib
from email.mime.multipart import MIMEMultipart
username = "user#gmail.com"
password = "*****"
msg = MIMEMultipart()
msg['From'] = username
msg['To'] = ', '.join(send_to)
msg['Cc'] = ', '.join(send_to_cc)
msg['Subject'] = subject
msg.attach(file)
server = smtplib.SMTP(host="host_address", port=587)
server.starttls()
server.login(username, password)
server.sendmail(username, send_to, msg.as_string())
server.quit()
subject = 'review ' + datetime.now().strftime('%Y-%m-%d')
text = 'Hi,\n\n' \
'I attach the review.\n\n'
send_mail(subject=subject,
text=text,
send_to=['mail#gmail.com'],
send_to_cc=['mail1#gmail.com'],
file=[filter_and_excel(from_bq_to_dataframe(**kwargs))]
)
When I try it locally I have no problems, but when I try linking it to big query I get this error:
Exception:
Command '['/tmp/venvq6e8hcce/bin/python', '/tmp/venvq6e8hcce/script.py', '/tmp/venvq6e8hcce/script.in', '/tmp/venvq6e8hcce/script.out', '/tmp/venvq6e8hcce/string_args.txt']' returned non-zero exit status 1.
Does anyone know why is that error happening? What does it mean?
Every similar error I found comes from installing python itself or maybe pip. Maybe I have some problem with the python version? I'm using 3.8
Hope someone can help me!

Python smtplib Accept Calendar Event

When Clicking accept in the email, and viewing it in the calendar it still says "has not accepted invite". Im not quite sure why the response to accept the email is not being updated in the calendar. Please help thanks! I am using outlook as the email service. Thanks again for the help much appreciated
#imports
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
import os,datetime
COMMASPACE = ', '
CRLF = "\r\n"
#Account that creats the Meeting
login = "admin#gmail.com"
password = "Password"
attendees = ["admin#gmail.com", "user1#gmail.com", "user2#gmail.com"]
organizer = "ORGANIZER;CN=Test:mailto:admin"+CRLF+"#gmail.com"
fro = "nickname <admin#gmail.com>"
ddtstart = datetime.datetime.now()
dtoff = datetime.timedelta(days = 1)
dur = datetime.timedelta(hours = 1)
ddtstart = ddtstart +dtoff
dtend = ddtstart + dur
dtstamp = datetime.datetime.now().strftime("%Y%m%dT%H%M%SZ")
dtstart = ddtstart.strftime("%Y%m%dT%H%M%SZ")
dtend = dtend.strftime("%Y%m%dT%H%M%SZ")
description = "DESCRIPTION: test invitation from pyICSParser"+CRLF
attendee = ""
for att in attendees:
attendee += "ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ- PARTICIPANT;PARTSTAT=ACCEPTED;RSVP=TRUE"+CRLF+" ;CN="+att+";X-NUM-GUESTS=0:"+CRLF+" mailto:"+att+CRLF
ical = "BEGIN:VCALENDAR"+CRLF+"PRODID:pyICSParser"+CRLF+"VERSION:2.0"+CRLF+"CALSCALE:GREGORIAN"+CRLF
ical+="METHOD:REQUEST"+CRLF+"BEGIN:VEVENT"+CRLF+"DTSTART:"+dtstart+CRLF+"DTEND:"+dtend+CRLF+"DTSTAMP:"+dtstamp+CRLF+organizer+CRLF
ical+= "UID:FIXMEUID"+dtstamp+CRLF
ical+= attendee+"CREATED:"+dtstamp+CRLF+description+"LAST-MODIFIED:"+dtstamp+CRLF+"LOCATION:"+CRLF+"SEQUENCE:0"+CRLF+"STATUS:CONFIRMED"+CRLF
ical+= "SUMMARY:test "+ddtstart.strftime("%Y%m%d # %H:%M")+CRLF+"TRANSP:OPAQUE"+CRLF+"END:VEVENT"+CRLF+"END:VCALENDAR"+CRLF
eml_body = "Event on Calendar test"
eml_body_bin = "This is the email body in binary - two steps"
msg = MIMEMultipart('mixed')
msg['Reply-To']="admin#gmail.com"
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = "Testing Event"+dtstart
msg['From'] = fro
msg['To'] = ",".join(attendees)
part_email = MIMEText(eml_body,"html")
part_cal = MIMEText(ical,'calendar;method=REQUEST')
msgAlternative = MIMEMultipart('alternative')
msg.attach(msgAlternative)
ical_atch = MIMEBase('application/ics',' ;name="%s"'%("invite.ics"))
ical_atch.set_payload(ical)
encoders.encode_base64(ical_atch)
ical_atch.add_header('Content-Disposition', 'attachment; filename="%s"'%("invite.ics"))
eml_atch = MIMEText('', 'plain')
encoders.encode_base64(eml_atch)
eml_atch.add_header('Content-Transfer-Encoding', "")
msgAlternative.attach(part_email)
msgAlternative.attach(part_cal)
mailServer = smtplib.SMTP('smtp.outlook.com', 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(login, password)
mailServer.sendmail(fro, attendees, msg.as_string())
mailServer.close()
print("Email Sent")

Emailing with an attachment with Python

import smtplib
import mechanize
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
def sem():
if not os.path.isfile('key.txt'):
print('below details are req to send report')
gmail_user = input('enter your email=')
gmail_app_password = input('enter your email password=')
print('pls accept the login in your gmail account ')
ke = open('key.txt',mode="w+")
ke.write(gmail_user)
ke.write(':')
ke.write(gmail_app_password)
ke.close()
if not os.path.isfile('sto.txt'):
gmai = input('enter the email to send report=')
ke = open('sto.txt',mode="w+")
ke.write(gmai)
ke.close()
with open('key.txt',mode="r")as f:
ds=f.readlines()
d=''.join(ds)
r=d.split(':')
with open('sto.txt',mode="r")as f:
ds=f.readlines()
f=ds
print(f)
gmail_user = r[0]
gmail_app_password = r[1]
sent_from = gmail_user
sent_to = ds
sent_subject = "hey amo lio ,how are ?"
sent_body = ("Hey, what's up? friend!")
email_text = """\
To: %s
Subject: %s
%s
""" % (", ".join(sent_to), sent_subject, sent_body)
mail = MIMEMultipart()
mail["Subject"] = sent_subject
mail["From"] = sent_from
mail["To"] = sent_to
mail.attach[MIMEText(sent_body,'html')]
ctype, encoding = mimetypes.guess_type(_file)
maintype, subtype = ctype.split('/', 1)
fp = open("./data/mood.txt")
msg = MIMEText(fp.read(), _subtype=subtype)
fp.close()
filename = os.path.basename(_file)
msg.add_header('Content-Disposition', 'attachment', filename=filename)
mail.attach(msg)
print('done')
server.sendmail(sent_from, sent_to, mail.as_string())
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_app_password)
server.sendmail(sent_from, sent_to, email_text)
server.close()
print('Email sent!')
except Exception as exception:
print("Error: %s!\n\n" % exception)
sem()
How can I attach the helloword.txt file in this email? This code is working fine, I just want to send an attachment along with it. This code lets me me send the body without any attachment. Also, how do I encrypt the key.txt file which store email address and password, and to send email it it requires the password to be entered (diff pass)?
You need to use the 'MIMEMultipart' module to attach files.
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
mail = MIMEMultipart()
mail["Subject"] = sent_subject
mail["From"] = sent_from
mail["To"] = sent_to
mail.attach(MIMEText(sent_body,'html'))
ctype, encoding = mimetypes.guess_type(_file)
maintype, subtype = ctype.split('/', 1)
fp = open("/path/to/attachment/file.txt")
# If file mimetype is video/audio use respective email.mime module.
# Here assuming 'maintype' == 'text' we will use MIMEText
msg = MIMEText(fp.read(), _subtype=subtype)
fp.close()
filename = os.path.basename(_file)
msg.add_header('Content-Disposition', 'attachment', filename=filename)
mail.attach(msg)
server.sendmail(sent_from, sent_to, mail.as_string())
import smtplib
import mechanize
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import mimetypes
import pdb
def email:
sender_address = gmail_user
#make it input
receiver_address = gmail_user
#Setup the MIME
fromaddr = gmail_user
sendto = gmail_app_password
sender_pass = gmail_app_password = input('enter your email password')
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = sendto
msg['Subject'] = 'This is cool'
body = "this is the body of the text message"
msg.attach(MIMEText(body, 'plain'))
filename = 'mood.txt'
attachment = open('./data/mood.txt', '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)
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login(gmail_user, gmail_app_password)
text = msg.as_string()
smtpObj.sendmail(fromaddr, sendto , text)
smtpObj.quit() # attach the instance 'p' to instance 'msg'
here is perfect working code for sending email

python email sent and received with smtplib has no content

I am sending email with my raspberrypi with python.
I successfully sent and received the message, but the content is missing.
Here is my code
import smtplib
smtpUser = 'myemail#gmail.com'
smtpPass = 'mypassword'
toAdd = 'target#gmail.com'
fromAdd = smtpUser
subject = 'Python Test'
header = 'To: ' + toAdd + '\n' + 'From: ' + fromAdd + '\n' + 'Subject: ' + subject
body = 'From within a Python script'
msg = header + '\n' + body
print header + '\n' + body
s = smtplib.SMTP('smtp.gmail.com',587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(smtpUser,smtpPass)
s.sendmail(fromAdd, toAdd, msg)
s.quit()
Thank you for your attention!
I wrote a wrapper around sending emails in python; it makes sending emails super easy: https://github.com/krystofl/krystof-utils/blob/master/python/krystof_email_wrapper.py
Use it like so:
emailer = Krystof_email_wrapper()
email_body = 'Hello, <br /><br />' \
'This is the body of the email.'
emailer.create_email('sender#example.com', 'Sender Name',
['recipient#example.com'],
email_body,
'Email subject!',
attachments = ['filename.txt'])
cred = { 'email': 'sender#example.com', 'password': 'VERYSECURE' }
emailer.send_email(login_dict = cred, force_send = True)
You can also look at the source code to find how it works.
The relevant bits:
import email
import smtplib # sending of the emails
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
self.msg = MIMEMultipart()
self.msg.preamble = "This is a multi-part message in MIME format."
# set the sender
author = email.utils.formataddr((from_name, from_email))
self.msg['From'] = author
# set recipients (from list of email address strings)
self.msg['To' ] = ', '.join(to_emails)
self.msg['Cc' ] = ', '.join(cc_emails)
self.msg['Bcc'] = ', '.join(bcc_emails)
# set the subject
self.msg['Subject'] = subject
# set the body
msg_text = MIMEText(body.encode('utf-8'), 'html', _charset='utf-8')
self.msg.attach(msg_text)
# send the email
session = smtplib.SMTP('smtp.gmail.com', 587)
session.ehlo()
session.starttls()
session.login(login_dict['email'], login_dict['password'])
session.send_message(self.msg)
session.quit()

Email multiple recipients Python

I'm trying to email multiple recipients using the pyton script below. I've searched the forum for answers, but have not been able to implement any of them correctly. If anyone has a moment to review my script and spot/resolve the problem it would be greatly appreciated.
Here's my script, I gather my issue is in the 'sendmail' portion, but can't figure out how to fix it:
gmail_user = "sender#email.com"
gmail_pwd = "sender_password"
recipients = ['recipient1#email.com','recipient2#email.com']
def mail(to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = ", ".join(recipients)
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
mailServer.close()
mail("recipient1#email.com, recipient2#email.com",
"Subject",
"Message",
"attchachment")
Any insight would be greatly appreciated.
Best,
Matt
It should be more like
mail(["recipient1#email.com", "recipient2#email.com"],
"Subject",
"Message",
"attchachment")
You already have a array of recipients declared,that too globally,You can use that without passing it as an argument to mail.
I wrote this bit of code to do exactly what you want. If you find a bug let me know (I've tested it and it works):
import email as em
import smtplib as smtp
import os
ENDPOINTS = {KEY: 'value#domain.com'}
class BoxWriter(object):
def __init__(self):
pass
def dispatch(self, files, box_target, additional_targets=None, email_subject=None, body='New figures'):
"""
Send an email to multiple recipients
:param files: list of files to send--requires full path
:param box_target: Relevant entry ENDPOINTS dict
:param additional_targets: other addresses to send the same email
:param email_subject: optional title for email
"""
destination = ENDPOINTS.get(box_target, None)
if destination is None:
raise Exception('Target folder on Box does not exist')
recipients = [destination]
if additional_targets is not None:
recipients.extend(additional_targets)
subject = 'Updating files'
if email_subject is not None:
subject = email_subject
message = em.MIMEMultipart.MIMEMultipart()
message['From'] = 'user#domain.com'
message['To'] = ', '.join(recipients)
message['Date'] = em.Utils.formatdate(localtime=True)
message['Subject'] = subject
message.attach(em.MIMEText.MIMEText(body + '\n' +'Contents: \n{0}'.format('\n'.join(files))))
for f in files:
base = em.MIMEBase.MIMEBase('application', "octet-stream")
base.set_payload(open(f, 'rb').read())
em.Encoders.encode_base64(base)
base.add_header('Content-Disposition', 'attachment; filename={0}'.format(os.path.basename(f)))
message.attach(base)
conn = smtp.SMTP('smtp.gmail.com', 587)
un = 'user#gmail.com'
pw = 'test1234'
conn.starttls()
conn.login(un, pw)
conn.sendmail('user#domain.com', recipients, message.as_string())
conn.close()
I was facing the same issue, I fixed this issue now. Here is my code -
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import datetime
def sendMail():
message = MIMEMultipart()
message["To"] = "xxxxx#xxxx.com,yyyy#yyyy.com"
message["Cc"] = "zzzzzz#gmail.com,*********#gmail.com"
message["From"] = "xxxxxxxx#gmail.com"
message["Password"] = "***************"
server = 'smtp.gmail.com:587'
try:
now = datetime.datetime.now()
message['Subject'] = "cxxdRL Table status (Super Important Message) - "+str(now)
server = smtplib.SMTP(server)
server.ehlo()
server.starttls()
server.login(message["From"], message["Password"])
server.sendmail(message["From"], message["To"].split(",") + message["Cc"].split(","), message.as_string())
server.quit()
print('Mail sent')
except:
print('Something went wrong...')
sendMail()

Categories

Resources