Friends,
The data extraction part is working and the emailing is also partly done.
I would like the same information I print on the screen and with the same formatting (jumping line etc) to be sent as part of the email message. I would like to save the same one that was printed on the above screen and then send it by email as the message body of the email and not the attachment.
The idea would be to throw the information in the file list.txt and then copy it to the body of the email. The part of getting the same thing that was printed on the screen and playing as message body of email is what does not work. Could you help?
Another question: how to modularize the program below into 2 files, for example? One with the part of extracting information from the site and the other with the sending of email?
import os
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
###########################################################
import requests, time
from bs4 import BeautifulSoup as bs
from datetime import datetime
url = "http://www.purebhakti.com/resources/vaisnava-calendar-mainmenu-71.html"
url_post = 'http://www.purebhakti.com/component/panjika'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
payload = {'action': 2, 'timezone': 23, 'location': 'Rio de Janeiro, Brazil 043W15 22S54 -3.00'}
req = requests.post(url_post, headers=headers, data=payload)
soup = bs(req.text, 'html.parser')
eles = soup.select('tr td')
dates = (' '.join(d.select('b')[0].text.strip().split()) for d in eles if d.has_attr('class'))
#events = (' '.join(d.text.split()) for d in eles if not d.has_attr('class'))
events = ((d.text) for d in eles if not d.has_attr('class'))
calendar = dict(zip(dates, events))
#data_hoje = time.strftime("%d %b %Y", time.gmtime() ) #data de hoje
data_desejada=time.strftime("%d %b %Y", time.gmtime(time.time() + (3600 * 24 * 2))) # daqui a 2 dias
print ("Prezados devotos, ")
print()
print("No dia %s, teremos o(s) seguinte(s) evento(s) no Calendario Vaisnava: " %(data_desejada))
print()
if(data_desejada in calendar):
print(calendar[data_desejada],end = "" )
else:
print('nenhum evento para hoje')
print()
print("Para mais detalhes acessem: %s " %(url))
print()
print("Jay Radhe!")
# esta parte nao funciona
#Gostaria de gravar o mesmo que foi impresso em tela acima e depois enviar #por email como mensagem e não anexo
##arq = open('/home/gopala/Desktop/lista.txt', 'w')
##texto = """
##Prezados devotos,
##
##No dia %s, teremos o(s) seguinte(s) evento(s) no Calendario Vaisnava: %(data_desejada))
##
##"""
##arq.write(texto)
##
##arq.close()
##
####parte envio email
COMMASPACE = ', '
def main():
sender = '[email protected]'
gmail_password = 'senhalegal'
recipients = ['[email protected]']
# Create the enclosing (outer) message
outer = MIMEMultipart()
outer['Subject'] = 'data no calendario Vaisnava'
outer['To'] = COMMASPACE.join(recipients)
outer['From'] = sender
outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'
# List of attachments
attachments = ['/home/gopala/Desktop/16839680_10212563027937627_634163502_n.jpg','/home/gopala/Desktop/lista.txt']
# Add the attachments to the message
for file in attachments:
try:
with open(file, 'rb') as fp:
msg = MIMEBase('application', "octet-stream")
msg.set_payload(fp.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))
outer.attach(msg)
except:
print("Unable to open one of the attachments. Error: ", sys.exc_info()[0])
raise
composed = outer.as_string()
# Send the email
try:
with smtplib.SMTP('smtp.gmail.com', 587) as s:
s.ehlo()
s.starttls()
s.ehlo()
s.login(sender, gmail_password)
s.sendmail(sender, recipients, composed)
s.close()
print("Email sent!")
except:
print("Unable to send the email. Error: ", sys.exc_info()[0])
raise
if __name__ == '__main__':
main()