Advertisement
Guest User

Untitled

a guest
Mar 29th, 2018
544
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.07 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. from datetime import datetime #usado para o contador do numero de emails enviados!
  4. from datetime import date
  5.  
  6. import facebook
  7. import requests
  8. ###############################facebook
  9.  
  10.  
  11. ######add body email
  12. import os
  13. import smtplib
  14. from email import encoders
  15. from email.mime.base import MIMEBase
  16. from email.mime.multipart import MIMEMultipart
  17. from email.mime.text import MIMEText
  18.  
  19.  
  20. import requests, time
  21. from bs4 import BeautifulSoup as bs
  22. from datetime import datetime
  23.  
  24. import re
  25.  
  26. f = open('/Gopala1/scripts/ptbr/calendar.txt', 'r')
  27. content = f.read()
  28.  
  29.  
  30. data_desejada = time.strftime("%d %b %Y", time.localtime(time.time() + (3600 * 24 * 2))) # daqui a 2 dias
  31. amanha = time.strftime("%d %b %Y", time.localtime(time.time() + (3600 * 24 * 1))) #amanha
  32.  
  33. # Localizando todas as datas no arquivo:
  34. dates = re.findall(r"[0-9]{1,2}\s.+\s[0-9]{4}", content)
  35.  
  36.  
  37. # Verifica se a data existe no arquivo:
  38. if not amanha in dates:
  39.   raise Exception("Data não definida")
  40.  
  41.  
  42.  
  43. # Localiza a data desejada no arquivo:
  44. start = content.find(amanha)
  45.  
  46.  
  47. # Verifica o índice da data na lista de datas:
  48. index = dates.index(amanha)
  49.  
  50.  
  51. # Verifica se não é a última data da lista:
  52. if index < len(dates)-1:
  53.  
  54.   # Verifica qual é a data posterior à desejada:
  55.   next_date = dates[index+1]
  56.  
  57.   # Localiza a próxima data no arquivo:
  58.   end = content.find(next_date)
  59.  
  60. else:
  61.  
  62.   # É a última data da lista, então exibe até o final do arquivo:
  63.   end = len(content)
  64.  
  65. # Exibe o conteúdo:
  66. #print(content[start:end])
  67.  
  68.    
  69.  
  70.  
  71.  
  72. url = "http://www.bhaktiyogapura.com/calendario-vaisnava/"
  73.  
  74.  
  75. print ("Prezados devotos, ")
  76. print()
  77. print()
  78.  
  79. print()
  80. print("Amanhã, %s, teremos o(s) seguinte(s) evento(s) no Calendario Vaisnava: " %(amanha ))
  81. print()
  82. print(content[start:end])
  83. ##
  84. ##print()
  85.  
  86. #print("Amanhã %s, teremos o(s) seguinte(s) evento(s) no Calendario Vaisnava: " %(amanha))
  87. print()
  88.  
  89. #print(calendar[data_nova2],end ="" )
  90.  
  91. print()
  92. print("Para mais detalhes acessem: %s " %(url))
  93. print()
  94. print("Jay Radhe!")
  95.  
  96.  
  97.  
  98. arq = open('CalendarioVaisnava.txt', 'w')
  99. texto = []
  100. texto.append("Prezados devotos,")
  101.  
  102.  
  103. texto.append('\n')
  104. texto.append('\n')
  105. texto.append('\n')
  106. texto.append('\n')
  107.  
  108.  
  109. texto.append("Amanhã, %s, teremos o(s) seguinte(s) evento(s) no Calendario \
  110. Vaisnava : " %(amanha))
  111.  
  112. texto.append('\n')
  113. texto.append('\n')
  114. ##texto.append('\n')
  115. texto.append(content[start:end])
  116.  
  117. texto.append('Para mais detalhes acessem: Para mais detalhes: http://www.bhaktiyogapura.com/calendario-vaisnava/')
  118. texto.append('\n')
  119. #texto.append('José Lima\n')
  120. arq.writelines(texto)
  121. arq.close()
  122.  
  123.  
  124.  
  125. ####parte envio email
  126. COMMASPACE = ', '
  127.  
  128. def main():
  129.     sender = 'xxxxxxxxxxxxx@gmail.com'
  130.     gmail_password = 'xxxxxxxxxxxx'
  131.  
  132.    
  133.     recipients = ['xxxxxxx@gmail.com']
  134.  
  135.  
  136.     #criando um contador do numero de emails enviados desde 25fev2017
  137. ##    inicio = datetime.strptime ('2017-02-25' ,"%Y-%m-%d")
  138. ##    hoje = date.today()
  139. ##    contador = hoje.toordinal() - inicio.toordinal()
  140. ##
  141. ##    
  142.     # Create the enclosing (outer) message
  143.     outer = MIMEMultipart()
  144.    
  145.     #titulo = 'Lembrete número ' + str(contador)+  " sobre o calendario Vaisnava"
  146.     titulo = "Lembrete sobre o calendario Vaisnava"
  147.     outer['Subject'] = titulo
  148.     outer['To'] = COMMASPACE.join(recipients)
  149.     outer['From'] = sender
  150.     outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'
  151.  
  152.   ###OBS sempre colocar o caminho completo da imagem
  153.  
  154.     # List of attachments
  155.     #attachments = ['/Gopala1/scripts/p.jpg','CalendarioVaisnava.txt']
  156.     #attachments =['CalendarioVaisnava.txt']
  157.     attachments = ['/Gopala1/scripts/ptbr/p.jpg','CalendarioVaisnava.txt']
  158.  
  159.  
  160.  
  161.  
  162.     # Create the body of the message (a plain-text and an HTML version).
  163.     #text = open("CalendarioVaisnava.txt","r")
  164.     arq = open("CalendarioVaisnava.txt",'r')
  165.     text = arq.read()
  166.  
  167.                
  168.          
  169.     html ="""
  170.    <html>
  171.    
  172.      <head></head>
  173.      
  174.      <body>
  175.  
  176.     <embed src="CalendarioVaisnava.txt">
  177.  
  178.     <p><h1>Jay Radhe!</h1><br>
  179.          Anadi-Krsna Das<br><br /><br />
  180.          Para mais detalhes, acessem <a href="Para mais detalhes: http://www.bhaktiyogapura.com/calendario-vaisnava/">link</a>.
  181.        </p>
  182.  
  183.         <figure>
  184.  <img src="http://oi68.tinypic.com/2n9ajj6.jpg" alt="Jay Guru Parampara!" >
  185. </figure>
  186.      </body>
  187.    </html>
  188.    """
  189.  
  190.    
  191.     # Now add the related image to the html part.
  192.     #data_uri = open('parampara.jpg', 'rb').read().encode('base64').replace('\n', '')
  193. ##    data_uri = base64.b64encode(open('parampara.jpg', 'rb').read()).decode('utf-8').replace('\n', '')
  194. ##    img_tag = '<img src="data:image/png;base64,{0}">'.format(data_uri)
  195.  
  196.     # Record the MIME types of both parts - text/plain and text/html.
  197.     part1 = MIMEText(text, 'plain')
  198.     part2 = MIMEText(html, 'html')
  199.  
  200.  
  201.     # Attach parts into message container.
  202.     # According to RFC 2046, the last part of a multipart message, in this case
  203.     # the HTML message, is best and preferred.
  204.     outer.attach(part1)
  205.     outer.attach(part2)
  206.  
  207.  
  208.    
  209.  
  210.     # Add the attachments to the message
  211.     for file in attachments:
  212.         try:
  213.             with open(file, 'rb') as fp:
  214.                 msg = MIMEBase('application', "octet-stream")
  215.                 msg.set_payload(fp.read())
  216.             encoders.encode_base64(msg)
  217.             msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))
  218.             outer.attach(msg)
  219.         except:
  220.             print("Unable to open one of the attachments. Error: ", sys.exc_info()[0])
  221.             raise
  222.  
  223.     composed = outer.as_string()
  224.  
  225.  
  226.  
  227.     # Send the email
  228.    
  229.    
  230.     try:
  231.         with smtplib.SMTP('smtp.gmail.com', 587) as s:
  232.             s.ehlo()
  233.             s.starttls()
  234.             s.ehlo()
  235.             s.login(sender, gmail_password)
  236.             s.sendmail(sender, recipients, composed)
  237.             s.close()
  238.         print("Email sent!")
  239.     except:
  240.         print("Unable to send the email. Error: ", sys.exc_info()[0])
  241.         raise
  242.     arq.close()
  243. if __name__ == '__main__':
  244.     main()
  245.  
  246.  
  247.  
  248. ###########facebook
  249.  
  250.  
  251.  
  252. def some_action(post):
  253.     """ Here you might want to do something with each post. E.g. grab the
  254.    post's message (post['message']) or the post's picture (post['picture']).
  255.    In this implementation we just print the post's created time.
  256.    """
  257.     post['lllllllllllllllllllllllllllllll']
  258.    
  259.  
  260. #token de XXX@gmail.com
  261. access_token ='lalalalala'
  262. #This new long-lived access token will expire on June 24th, 2017:
  263.  
  264. user = '33333333' #pagina Vaishnava
  265.  
  266. graph = facebook.GraphAPI(access_token)
  267. profile = graph.get_object(user)
  268. posts = graph.get_connections(profile['id'], 'posts')
  269.  
  270.  
  271.  
  272. #graph.put_object("me", "feed", message="O salomao taaaaa durmindo")
  273. #graph.put_photo(image=open('DSC02274.JPG', 'rb'), message='Look at this cool photo!')
  274. #graph.put_photo(image=open('salompas.jpg', 'rb'), message='lindinhu')
  275. ##arq = open("CalendarioVaisnava.txt",'r')
  276. ##attachment= arq.readlines()
  277. #graph.put_photo(image=open('CalendarioVaisnava.txt', 'r'), message='Look at this cool photo!')
  278.  
  279.  
  280. f = open('CalendarioVaisnava.txt', 'r')
  281. listao=[]
  282. listao = f.readlines() # converte o arquivo em lista
  283.  
  284.  
  285. mensagem = ''.join(listao) #transforma a lista em string
  286. #print("a mensagem eh", mensagem)
  287.  
  288. ###OBS sempre colocar o caminho completo da imagem
  289. #posting on a principal page
  290.  
  291. ##nao consigo postar IMAGEM
  292. graph.put_photo(image=open('/Gopala1/scripts/ptbr/p.jpg', 'rb'), message='Jay Guru Parampara!')
  293. #graph.put_photo(image=open('p.jpg', 'rb'), message='Jay Guru Parampara!')
  294. #graph.put_photo(image='http://oi68.tinypic.com/2n9ajj6.jpg', message='Jay Guru Parampara!
  295. graph.put_object("me", "feed", message=mensagem)
  296.  
  297. #posting on a wall
  298. #graph.put_photo(image=open('parampara.jpg', 'rb'), message='Jay Guru Parampara!',album_path="232568853880500")
  299. #graph.put_object("1290498430996462", "feed", message=mensagem) #edsonbsouza@gmail.com
  300. graph.put_object("1290498430996462", "feed", message=mensagem) #emailtudaogeral@gmail.com
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement