コード例 #1
0
    def __init__(self, **kwargs):
        super(Gmail_checker, self).__init__(**kwargs)

        self.client_secret_file = kwargs.get('client_secret_file', None)

        # check if parameters have been provided
        if self._is_parameters_ok():
            # prepare a returned dict
            returned_dict = dict()

            gmail = Gmail(client_secret_file=self.client_secret_file)

            # Unread messages in your inbox
            unread = gmail.get_unread_inbox()

            returned_dict["unread"] = len(unread)

            if len(unread) > 0:
                # add a list of subject
                subject_list = list()
                for email in unread:
                    subject = email.subject
                    subject_list.append(subject)

                returned_dict["subjects"] = subject_list

            logger.debug("gmail neuron returned dict: %s" % str(returned_dict))

            self.say(returned_dict)
コード例 #2
0
 def __init__(self,
              after_date_and_time,
              before_date_and_time,
              save_dir="output"):
     self.gmail = Gmail()
     self.save_dir = save_dir
     self.messages = self.gmail.get_messages(
         query=f'after:{_get_timestamp(after_date_and_time)} '
         f'before:{_get_timestamp(before_date_and_time)} '
         f'has:attachment')
     os.makedirs(save_dir, exist_ok=True)
     i = 0
     for message in self.messages:
         i += 1
         print(f"{i}/{len(self.messages)} From: " + message.sender)
         if message.attachments:
             for attm in message.attachments:
                 if attm.filename.find(".pdf") != -1 or attm.filename.find(
                         ".PDF") != -1:
                     file_path = os.path.join(save_dir, attm.filename)
                     if os.path.exists(file_path):
                         attm.filename = f'{attm.filename.replace(".pdf", "").replace(".PDF", "")}'
                         attm.filename = f'{attm.filename}_{int(time.time())}.pdf'
                     else:
                         attm.filename = f'{attm.filename.replace(".pdf", "").replace(".PDF", "")}'
                         attm.filename = f'{attm.filename}.pdf'
                 file_path = os.path.join(save_dir, attm.filename)
                 attm.save(file_path)
                 print(f"   Downloaded: {file_path}")
コード例 #3
0
    def downloadMail(self):
        gmail = Gmail()
        try:
            messages = gmail.get_unread_inbox()
            if len(messages) > 0:
                print(f"{len(messages)} new message")
                msg = messages[0]
                link = extractLink(msg.plain)
                print(f"Question link: {link}")
                self.log.info(f"INIT-3:DOWNLOAD_MAIL:{link}")
                qId = findQuestionId(link)
                print(qId)
                createFolder(
                    r"C:\Users\woosal\Desktop\Chegg BOT X\Downloads\{0}".
                    format(qId))
                fullPath = path.abspath(
                    r"C:\Users\woosal\Desktop\Chegg BOT X\Downloads\{0}".
                    format(qId))
                soup = BeautifulSoup(msg.html, 'html.parser')
                imgs = soup.find_all('img')
                urls = [img['src'] for img in imgs]
                for i in range(1, len(urls) - 1):
                    url = urls[i]
                    name = f"{fullPath}\image{i}.png"
                    try:
                        res = get(url)
                        file = open(name, "wb")
                        file.write(res.content)
                    except Exception as e:
                        self.log.alert(f"DOWNLOAD_MAIL:Exception:{e}")
                        pass

                try:
                    f = open(r"{0}\aplain.txt".format(fullPath),
                             "a",
                             encoding="utf-8")
                    f.write("".join(msg.plain.split("\n")[1:-13]))
                    f.close()
                except Exception as e:
                    self.log.alert(f"INIT-3:DOWNLOAD_MAIL:Exception:{e}")
                    pass
                downloadTime = dt.now() - self.start
                self.log.info(f"INIT-3:DOWNLOAD_MAIL:Mail_Downloaded:{qId}")
                print(dt.now())
                print(f"It took {downloadTime} seconds")
                msg.mark_as_read()
                self.log.info(f"INIT-3:DOWNLOAD_MAIL:Mail_Marked:{link}")
            else:
                pass
        except Exception as e:
            self.log.alert(f"INIT-3:DOWNLOAD_MAIL:Exception:{e}")
            pass
コード例 #4
0
 def send_notification(self, notification, auctions):
     link_prefix = self.__config.get('komornik.pl', 'link_prefix')
     env = Environment(loader=PackageLoader('app', 'templates'),
                       autoescape=select_autoescape(['html', 'xml']))
     template = env.get_template('notification_mail.html')
     msg_html = template.render(notification=notification,
                                auctions=auctions,
                                auction_headers=self.__auction_headers,
                                link_prefix=link_prefix)
     gmail = Gmail()
     params = {
         "to": notification['email'],
         "sender": self.__config.get('gmail', 'sender'),
         "subject": self.__config.get('gmail', 'subject'),
         "msg_html": msg_html,
         "msg_plain": "Hi\nThis is a plain text email.",
         "signature": True  # use my account signature
     }
     # print(msg_html)
     message = gmail.send_message(**params)
     pass
コード例 #5
0
ファイル: gmail-api.py プロジェクト: borrachinhams/send-gmail
import configparser
import codecs
import os

from simplegmail import Gmail

gmail = Gmail()

caminho = os.path.abspath(os.getcwd())
caminho_conf = '{}\\conf.ini'.format(caminho)
caminho_emails = '{}\\emails.txt'.format(caminho)
caminho_corpo_email = '{}\\corpo_email.html'.format(caminho)

config = configparser.ConfigParser()
config.read(caminho_conf)

emails = codecs.open(caminho_emails, 'r')
emails = emails.read().split()

corpo_email = codecs.open(caminho_corpo_email, 'r')
corpo_email = corpo_email.read()


def envia_email(email):
    params = {
        "to": email,
        "sender": config.get('email', 'de'),
        "subject": config.get('email', 'assunto'),
        "msg_html": corpo_email,
        "signature": True  # use my account signature
    }
コード例 #6
0
ファイル: gmail.py プロジェクト: rain-21/python-class
import socks
import socket
from simplegmail import Gmail
import re

# 科学上网,你也需要科学使用代理,不然科学不了外网,也许你不会需要。
headers = {
    'User-Agent':
    'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',
    'Connection': 'close'
}
socks.set_default_proxy(socks.SOCKS5, "127.0.0.1")
socket.socket = socks.socksocket

gmail = Gmail()

# Unread messages in your inbox
messages = gmail.get_unread_messages(include_spam_trash=True)

# messages = gmail.get_spam_messages()

# ...and many more easy to use functions can be found in gmail.py!

# Print them out!
for message in messages:
    if message.attachments:
        for attm in message.attachments:
            print('File: ' + attm.filename)
            matches = re.match(r'^(\d{2})[_-](\d+)[_-](.+).ipynb$',
                               attm.filename)
            if matches:
コード例 #7
0
import sqlite3
import random
import datetime
from datetime import date
from simplegmail import Gmail

gmail = Gmail()

today = date.today()

print(today.day, today.month, today.year)

print(today)

x = input("please provide date")
y = input("please provide month")
z = input("please provide year")
xx = input("Please share what is the event")

connection = sqlite3.connect("ridhi.db")
cursor = connection.cursor()
#cursor.execute("CREATE TABLE calendra( day int , mnth int , year int, evnt text)");
#cursor.execute('INSERT INTO application20 VALUES(?,?)'(input2,bucket))
cursor.execute("INSERT INTO calendra VALUES ( ?,?,?,? )", (x, y, z, xx))
connection.commit()

datetime1 = date.strftime(today, '%m,%d,%Y')
print(datetime1)
datetime2 = date.strftime(today, '%d')
print(datetime2)
datetime3 = date.strftime(today, '%m')