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")
Related
While sending meeting invite using "icalendar" library I am facing issue with time zone difference in Gmail and outlook mails. When I am sending meeting invitation to outlook it automatically changing time zone IST to GMT. Please help me out to solve this issue.
The below code I used for sending meeting invitation using "icalendar" but it is not working for outlook mail. It is sending meeting invitation for outlook mails but timezone is differing. Please any one help me to achieve it.
Thank you
from email import encoders
import smtplib
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import datetime as dt
import datetime
from email.mime.multipart import MIMEMultipart
import icalendar
import pytz
login = "salimabegum534#gmail.com"
password = "********"
organiser_email = "example#gmail.com"
atendee_email = "example2#gmail.com"
subj = "Test mail invitation"
description = "Test mail invitation description"
start_hour = 1
start_minute = 0
# location =
date_time = datetime.datetime.now()
tz = pytz.timezone("Asia/kolkata")
start = tz.localize(dt.datetime.combine(date_time, dt.time(start_hour, start_minute, 0)))
# Imagine this function is part of a class which provides the necessary config data
# Timezone to use for our dates - change as needed
# start = tz.localize(date_time)
# Build the event itself
cal = icalendar.Calendar()
cal.add('prodid', '-//My calendar application//example.com//')
cal.add('version', '2.0')
cal.add('method', "REQUEST")
event = icalendar.Event()
event.add('attendee', atendee_email)
event.add('organizer', organiser_email)
event.add('status', "confirmed")
event.add('category', "Event")
event.add('summary', subj)
event.add('description', description)
# event.add('location', location)
event.add('dtstart', start)
event.add('dtend', tz.localize(dt.datetime.combine(date_time, dt.time(start_hour + 1, start_minute, 0))))
event.add('dtstamp', tz.localize(dt.datetime.combine(date_time, dt.time(6, 0, 0))))
event.add('dtstart', start)
# event.add('dtend', tz.localize(date_time))
event.add('dtstamp', tz.localize(date_time))
# event['uid'] = self.get_unique_id() # Generate some unique ID
event.add('priority', 5)
event.add('sequence', 1)
event.add('created', tz.localize(date_time))
# Add a reminder
alarm = icalendar.Alarm()
alarm.add("action", "DISPLAY")
alarm.add('description', "Reminder")
# The only way to convince Outlook to do it correctly
# alarm.add("TRIGGER;RELATED=START", "-PT{0}H".format(reminder_hours))
event.add_component(alarm)
cal.add_component(event)
# Build the email message and attach the event to it
msg = MIMEMultipart("alternative")
msg["Subject"] = subj
msg["From"] = organiser_email
msg["To"] = atendee_email
msg["Content-class"] = "urn:content-classes:calendarmessage"
msg.attach(MIMEText(description))
filename = "invite.ics"
part = MIMEBase('text', "calendar", method="REQUEST", name=filename)
part.set_payload(cal.to_ical() )
encoders.encode_base64(part)
part.add_header('Content-Description', filename)
part.add_header("Content-class", "urn:content-classes:calendarmessage")
part.add_header("Filename", filename)
part.add_header("Path", filename)
msg.attach(part)
# Send the email out
# s = smtplib.SMTP('localhost')
# s.sendmail(msg["From"], [msg["To"]], msg.as_string())
# s.quit()
mailServer = smtplib.SMTP('smtp.gmail.com', 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(login, password)
mailServer.sendmail(msg["From"], [msg["To"]], msg.as_string())
mailServer.close()
I would like to send two file attachments by email but I do not know how to do, any help?
def sendmail():
sender_email = "sender#gmail.com"
receiver_email = "receiver#gmail.com"
message = MIMEMultipart()
message["From"] = sender_email
message['To'] = receiver_email
message['Subject'] = "Deine Monatseinteilung"
file = (f'{myPath}/File-2-2022.ics')
attachment = open(file,'rb')
obj = MIMEBase('application','octet-stream')
obj.set_payload((attachment).read())
encoders.encode_base64(obj)
obj.add_header('Content-Disposition',"attachment; filename= "+file)
message.attach(obj)
my_message = message.as_string()
email_session = smtplib.SMTP('smtp.gmail.com',587)
email_session.starttls()
email_session.login(sender_email,'xxxxxx')
email_session.sendmail(sender_email,receiver_email,my_message)
email_session.quit()
print(f"Deine monatseinteilung wurde an deine E-Mail-Adresse gesendet ({receiver_email})")
sendmail()
Try using this code snippet below:
import smtplib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
def _send_email(send_from, send_to, subject, text, files=None):
assert isinstance(send_to, list)
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(text))
for f in files or []:
with open(f, "rb") as fil:
part = MIMEApplication(
fil.read(),
Name=basename(f)
)
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
msg.attach(part)
smtp = smtplib.SMTP(SERVER, PORT)
smtp.login(USER, PASS)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
Then you can call the function like so:
send_from = "fakeemail3#domain.com"
send_to = ['fakeemail1#domain.com', 'fakeemail2#domain.com']
subject = "My Subject"
text = "This is a email."
files = ["pathtofile1", "pathtofile2"]
_send_email(send_from, send_to, subject, text, files)
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
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
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()