So i'm having issues getting my python 3.5 script to run as an exe. Here is the code I am using:
import base64
import imaplib
import json
import smtplib
import urllib.parse
import urllib.request
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import lxml.html
GOOGLE_ACCOUNTS_BASE_URL = 'https://accounts.google.com'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
GOOGLE_CLIENT_ID = '<FILL ME IN>'
GOOGLE_CLIENT_SECRET = '<FILL ME IN>'
GOOGLE_REFRESH_TOKEN = None
def command_to_url(command):
return '%s/%s' % (GOOGLE_ACCOUNTS_BASE_URL, command)
def url_escape(text):
return urllib.parse.quote(text, safe='~-._')
def url_unescape(text):
return urllib.parse.unquote(text)
def url_format_params(params):
param_fragments = []
for param in sorted(params.items(), key=lambda x: x[0]):
param_fragments.append('%s=%s' % (param[0], url_escape(param[1])))
return '&'.join(param_fragments)
def generate_permission_url(client_id, scope='https://mail.google.com/'):
params = {}
params['client_id'] = client_id
params['redirect_uri'] = REDIRECT_URI
params['scope'] = scope
params['response_type'] = 'code'
return '%s?%s' % (command_to_url('o/oauth2/auth'), url_format_params(params))
def call_authorize_tokens(client_id, client_secret, authorization_code):
params = {}
params['client_id'] = client_id
params['client_secret'] = client_secret
params['code'] = authorization_code
params['redirect_uri'] = REDIRECT_URI
params['grant_type'] = 'authorization_code'
request_url = command_to_url('o/oauth2/token')
response = urllib.request.urlopen(request_url, urllib.parse.urlencode(params).encode('UTF-8')).read().decode('UTF-8')
return json.loads(response)
def call_refresh_token(client_id, client_secret, refresh_token):
params = {}
params['client_id'] = client_id
params['client_secret'] = client_secret
params['refresh_token'] = refresh_token
params['grant_type'] = 'refresh_token'
request_url = command_to_url('o/oauth2/token')
response = urllib.request.urlopen(request_url, urllib.parse.urlencode(params).encode('UTF-8')).read().decode('UTF-8')
return json.loads(response)
def generate_oauth2_string(username, access_token, as_base64=False):
auth_string = 'user=%s\1auth=Bearer %s\1\1' % (username, access_token)
if as_base64:
auth_string = base64.b64encode(auth_string.encode('ascii')).decode('ascii')
return auth_string
def test_imap(user, auth_string):
imap_conn = imaplib.IMAP4_SSL('imap.gmail.com')
imap_conn.debug = 4
imap_conn.authenticate('XOAUTH2', lambda x: auth_string)
imap_conn.select('INBOX')
def test_smpt(user, base64_auth_string):
smtp_conn = smtplib.SMTP('smtp.gmail.com', 587)
smtp_conn.set_debuglevel(True)
smtp_conn.ehlo('test')
smtp_conn.starttls()
smtp_conn.docmd('AUTH', 'XOAUTH2 ' + base64_auth_string)
def get_authorization(google_client_id, google_client_secret):
scope = "https://mail.google.com/"
print('Navigate to the following URL to auth:', generate_permission_url(google_client_id, scope))
authorization_code = input('Enter verification code: ')
response = call_authorize_tokens(google_client_id, google_client_secret, authorization_code)
return response['refresh_token'], response['access_token'], response['expires_in']
def refresh_authorization(google_client_id, google_client_secret, refresh_token):
response = call_refresh_token(google_client_id, google_client_secret, refresh_token)
return response['access_token'], response['expires_in']
def send_mail(fromaddr, toaddr, subject, message):
access_token, expires_in = refresh_authorization(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REFRESH_TOKEN)
auth_string = generate_oauth2_string(fromaddr, access_token, as_base64=True)
msg = MIMEMultipart('related')
msg['Subject'] = subject
msg['From'] = fromaddr
msg['To'] = toaddr
msg.preamble = 'This is a multi-part message in MIME format.'
msg_alternative = MIMEMultipart('alternative')
msg.attach(msg_alternative)
part_text = MIMEText(lxml.html.fromstring(message).text_content().encode('utf-8'), 'plain', _charset='utf-8')
part_html = MIMEText(message.encode('utf-8'), 'html', _charset='utf-8')
msg_alternative.attach(part_text)
msg_alternative.attach(part_html)
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo(GOOGLE_CLIENT_ID)
server.starttls()
server.docmd('AUTH', 'XOAUTH2 ' + auth_string)
server.sendmail(fromaddr, toaddr, msg.as_string())
server.quit()
def main():
if GOOGLE_REFRESH_TOKEN is None:
print('No refresh token found, obtaining one')
refresh_token, access_token, expires_in = get_authorization(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET)
print('Set the following as your GOOGLE_REFRESH_TOKEN:', refresh_token)
exit()
send_mail('--------#gmail.com', '--------#gmail.com',
'A mail from you from Python',
'<b>A mail from you from Python</b><br><br>' +
'So happy to hear from you!')
input("Success!")
print(__name__)
input("Wait!!")
if __name__ == '__main__':
main()
When i run the code in pyCharm is works great, when i use pyinstaller it creates the exe. When i run the EXE it will open a new cmd prmpt with no text in it, then it closes. Any ideas why it doesn't print the name or "Wait!!" on the screen?
I named the file main and it works great in PyCharm.
I'm not familiar with troubleshooting code that works in an IDE and does nothing as an exe. Is there a basic troubleshooting guide for that?
Most of the problems are errors caused by imported modules.
Here are two ways I think of
Use exception handling and use traceback.format_exc() to display the contents when an error occurs.
Errors are usually associated with the sys.stderr, so you can redirect stderr output a specified format to a specified file or the like.
Example:
import sys
from pathlib import Path
from os import startfile
import traceback
DEBUG = True
class CaptureStderr:
__slots__ = ('debug_flag',
'original',
'log',)
def __init__(self, debug_flag=False, log=None):
self.debug_flag = debug_flag
self.original = sys.stderr # Keep track of original
self.log = log
def new_log_file(self, log_path: Path = Path('temp.log').resolve()):
self.log = open(str(log_path), 'w')
return self.log
def start(self):
""" Start filtering and redirecting stderr """
sys.stderr = self
def stop(self):
""" Stop filtering and redirecting stderr """
sys.stderr = self.original
def write(self, message: str):
""" When sys.stderr.write is called, it will re directed here"""
if not self.debug_flag:
self.original.write(message)
self.original.flush()
return
if self.log:
self.log.write(message)
def main():
...
if __name__ == '__main__':
try: # method 1
from .notexistmodule import notexistclass
# Put modules that you are not sure whether it is 100% import successful on here.
main()
except:
print(traceback.format_exc())
# method 2: redirect sys.stderr
cs = CaptureStderr(DEBUG)
cs.new_log_file(Path('error.log'))
cs.start()
from .notexistmodule2 import notexistclass2
main()
cs.stop()
startfile(cs.log.name)
You probably have an error in the exe, most likely an import error.
Run your exe like this to see the error:
Create a .bat file to run the exe with the following commands
start C:\Path\To\.exe
pause
This will stop the command prompt from exiting until you press a key on the keyboard, letting you read the output.
Related
As the question, I now creating a simple http.server with Python and I have to send information about request like Client IP, login time of client, method GET/POST, HTTP header, HTTP body to Client and display it on Frontend. But I don't know how to send and how to get that information to send ? Please help me, thanks
This is my server code:
from http.server import BaseHTTPRequestHandler, HTTPServer
import os
import cgi
from supervisor.medusa.auth_handler import get_header
from database.db import create_table, signup, check_login
from random import randint
from datetime import datetime
import logging
islogin = False
def read_html_template(path):
try:
with open(path) as f:
file = f.read()
except Exception as e:
file = e
return file
class handler(BaseHTTPRequestHandler):
def gen_token(self):
return "".join(str(randint(1, 9)) for _ in range(25))
def get_Ip_addr(self):
return self.client_address[0]
def get_header(self):
return logging.error(self.headers)
def get_time(self):
now = datetime.now()
return now.strftime("%d/%m/%Y %H:%M:%S")
def data_to_send(self):
login_time = self.get_time()
header_data = self.get_header()
ip_client = self.get_Ip_addr()
data = ('{"IP_Client": '+ str(ip_client) + ', "HTTP_Header": ' + str(header_data) + ', "Login_Time": '+ str(login_time) + '}')
return data
def do_GET(self):
if self.path == '/':
self.path = './src/html/index.html'
elif self.path == '/login':
self.path = './src/html/Login.html'
elif self.path == '/signup':
self.path = './src/html/Signup.html'
elif self.path == '/forgotpwd':
self.path = './src/html/ForgotPwd.html'
elif self.path == '/home' and islogin == True:
self.path = './src/html/singnedIn.html'
try:
split_path = os.path.splitext(self.path)
request_extension = split_path[1]
if request_extension != ".py":
f = read_html_template(self.path)
self.send_response(200)
self.end_headers()
self.wfile.write(bytes(f, 'utf-8'))
else:
f = "File not found"
self.send_error(404,f)
except:
f = "File not found"
self.send_error(404,f)
with HTTPServer(('', 8000), handler) as server:
server.serve_forever()
My idea is write data to a json file and send it to client but 2 things I don't know is
How to send json file ? and
How to get data and write it to json file ?
This is the code. (cred.py is a file containing my password and username)
import os
from os.path import dirname,realpath
from imbox import Imbox
import imaplib
import traceback
import datetime
from cred import * # contains username and password
def main():
p = dirname(realpath(__file__))
host = "imap.gmail.com"
download_folder = p+"\\"+username+"\\"+str(datetime.datetime.now())[:10]
if not os.path.isdir(download_folder):
os.makedirs(download_folder, exist_ok=True)
mail = Imbox(host, username=username, password=password, ssl=True, ssl_context=None, starttls=False)
messages = mail.messages(unread=True) # defaults to inbox
for (uid, message) in messages:
mail.mark_seen(uid) # optional, mark message as read
for idx, attachment in enumerate(message.attachments):
try:
att_fn = attachment.get('filename')
download_path = f"{download_folder}\\{att_fn}"
print(download_path)
with open(download_path, "wb") as fp:
fp.write(attachment.get('content').read())
except:
print(traceback.print_exc())
mail.logout()
if input('Enter "test" to run now, else to run at 00:00 ') == 'test':
main()
while True:
if str(datetime.datetime.now())[11:-7] == "00:00:00":
print('running')
main()
For some reason some messages raise a ValueError and it looks like a bug in module. What do I do?
Hello I need help with my code. It keeps giving me authentication-errors.
Can you check it out for me?
All I needed was the code to authenticate successfully and save the working login in a txt-file and the bad login (wrong password) in another txt-file. It works with smtp but keeps giving me an error on imap.
See the code below.
Thanks
The logins in accounts.txt are in the following format email:password
...
import imaplib
import ssl
import socket
import getpass
import re
import socks
import codecs
import unicodedata
import random
from multiprocessing.pool import ThreadPool
# PROXY_TYPE_HTTP
# PROXY_TYPE_SOCKS5
proxy_type = socks.PROXY_TYPE_HTTP
use_proxies = False
thead_count = 1
use_encrpytion = False
accounts = []
accounts_checked = 0
accounts_valid = []
accounts_invalid = []
proxies = []
def check_account(email, password):
try:
if (use_proxies):
proxy = random.choice(proxies)
proxy_host = proxy.split(':')[0]
proxy_port = int(proxy.split(':')[1])
socks.setdefaultproxy(proxy_type, proxy_host, proxy_port)
socks.wrapmodule(imaplib)
mailserver = imaplib.IMAP4_SSL(('mail.' + re.search('#((\w|\w[\w\-]*?\w)\.\w+)', email).group(1)), 993)
mailserver.login(str(email), str(password))
mailserver.close()
return True
except imaplib.IMAP4.error:
print ("Log in failed.")
return False
def get_status(account):
global accounts_checked, accounts
if (':' not in account):
return False
email = account.split(':')[0]
password = account.split(':')[1]
valid = check_account(email, password)
if (valid):
print("Valid: ", account)
f1 = open("connect.txt", "a+")
f1.write(account)
f1.close()
accounts_valid.append(account)
else:
f2 = open("not_connect.txt", "a+")
f2.write(account)
f2.close()
accounts_invalid.append(account)
accounts_checked += 1
print("(" + str(accounts_checked) + "/" + str(len(accounts)) + ")")
return valid
if __name__ == "__main__":
if (use_proxies):
print("Reading \"proxies.txt\"...")
with open("proxies.txt") as f:
for line in f:
if (':' in line):
proxies.append(line)
print("Found " + str(len(proxies)) + " proxies.")
print("Reading \"accounts.txt\"...")
with codecs.open("accounts.txt", encoding='utf-8') as f:
for line in f:
line = unicodedata.normalize('NFKD', line).encode('ascii','ignore').decode('ascii')
if (':' in line):
accounts.append(line.replace("\n", "").replace("\t", ""))
print("Found " + str(len(accounts)) + " accounts.")
print("Creating thread pool...")
pool = ThreadPool(thead_count)
results = pool.map(get_status, accounts)
pool.close()
pool.join()
print("Done checking, writing output...")
print("Completed!")
...
you should create a minimal example, in my case I cannot log in using
imaplib but I do not wrap with the socket stuff.. Why is the ssl
sockets not automatic?
def get_mail_client(email_address):
print(password)
mail = imaplib.IMAP4_SSL(SMTP_SERVER, SMTP_PORT)
mail.login(email_address, password)
return mail
def start(name):
# Use a breakpoint in the code line below to debug your script.
mailClient = get_mail_client(EMAIL)
status, messages = mailClient.select('INBOX')
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
print(messages)
print(messages[0])
How to get logged into some website using python code
i.e www.example.com/auth/gmail which is taking advantage of google+ API for user logins. Now I would like to login with my credentials (Gmail or What?) by using python code. Please help me how to approach towards this problem.
Thanks
Here you have an example by using the google-api-python-client
First of all you have to create your client secrets on the google developer console.
First time you execute the code you will have to authorize the script to use your gmail account, then you can save the credentials on a file as on the example, and use it for the future executions without requiring this authentication
from googleapiclient.discovery import build
from oauth2client import client
from googleapiclient.errors import HttpError
import base64
from email.mime.text import MIMEText
from apiclient import errors
from oauth2client import client
import httplib2
from googleapiclient.discovery import build
def getCredentials(secrets, scope,filename):
flow = client.flow_from_clientsecrets(
secrets,
scope=scope,
redirect_uri='urn:ietf:wg:oauth:2.0:oob')
auth_uri = flow.step1_get_authorize_url()
webbrowser.open(auth_uri)
auth_code = raw_input('Enter the auth code: ')
credentials = flow.step2_exchange(auth_code)
saveJson(filename,credentials.to_json())
def saveJson(filename, object):
with open(filename, 'w') as f:
json.dump(object, f)
def openJson(filename):
with open(filename, 'r') as f:
object = json.load(f)
return object
if __name__=='__main__':
client_secrets = 'client_secrets.json' #client secrets to use the API
credentials = 'auth_credentials.json'
if(firstRun) #create a file with the auth credentials
scope = 'https://www.googleapis.com/auth/gemail.send'
getCredentials(secrets,scope,credentials)
cre = client.Credentials.new_from_json(openJson(credentials))
http_auth = cre.authorize(httplib2.Http())
gmail = build('gmail', 'v1', http=http_auth)
#gmail.doSomething
this is old(sandbox) and is done really fast so, you have to refactor the code
import re
import sys
import imaplib
import getpass
import email
import datetime
import string
import get_mail_search
from sys import stdout
M = imaplib.IMAP4_SSL('imap.gmail.com')
class Get_mail(object):
"""docstring for Get_mail"""
def __init__(self, *args):
super(Get_mail, self).__init__()
c=1
self.login(c)
self.toast_msg()
raw_input()
def toast_msg(self, *args):
"""docstring for Get_mail"""
M = self.mailbox()
stdout.write("\n{}\n".format(get_mail_search.search_help_info))
serach_input = raw_input()
rv, data = M.search(None, serach_input)
if rv != 'OK':
print "No messages found!"
id_ls = data[0].split()
rev_id_ls = [i for i in reversed(id_ls)]
if rev_id_ls:
for o in rev_id_ls:
try:
msg_content = self.process_mailbox(M, o)
_date_ = msg_content[0]
_from_ = msg_content[1]
_to_ = msg_content[2]
_subject_ = msg_content[3]
_msg_ = msg_content[4]
stdout.write("$$$$$$$$$$$\nDate: {}\nFrom: {}\nTo: {}\nSubject: {}\nMSG: {}\n".format(_date_,_from_,_to_,_subject_,_msg_))
except Exception, e:
pass
else:
stdout.write("No {} Mail Found!".format(serach_input))
raw_input()
self.toast_msg()
def login(self, try_c, *args):
"""docstring for Get_mail"""
try:
stdout.write("\nMail:\n")
mail = raw_input()
if mail:
M.login(str(mail), getpass.getpass())
else:
sys.exit(1)
except imaplib.IMAP4.error:
if try_c<=3:
stdout.write("Versuch: {}/3\n".format(try_c))
stdout.write("Die eingegebene E-Mail-Adresse und das Passwort stimmen nicht uberein. Nochmal versuchen")
try_c+=1
self.login(try_c)
else:
sys.exit(1)
def mailbox(self, *args):
"""docstring for Get_mail"""
rv, mailboxes = M.list()
if rv == 'OK':
for menu in mailboxes:
print('{}'.format(menu))
rv, data = M.select("inbox")
if rv == 'OK':
return M
def eval_decode(self, header, *args):
"""docstring for Get_mail"""
return email.Header.decode_header(header)[0]
def process_mailbox(self, M, num, *args):
"""docstring for Get_mail"""
rv, header = M.fetch(num, '(RFC822)')
if rv != 'OK':
print "ERROR getting message", num
header_msg = email.message_from_string(header[0][1])
if header_msg.is_multipart():
body=[payload.get_payload(decode=True) for payload in header_msg.get_payload()]
else:
body=payload.get_payload(decode=True)
from_decode = self.eval_decode(header_msg['From'])
subject_decode = self.eval_decode(header_msg['Subject'])
date_decode = self.eval_decode(header_msg['Date'])
to_decode = self.eval_decode(header_msg['To'])
return (date_decode[0], from_decode[0], to_decode[0], subject_decode[0], str(body[0]))
def run():
try:
Get_mail()
except KeyboardInterrupt:
M.close()
M.logout()
sys.exit(1)
run()
I have a HTML code in a text file emailtext.txt # http://pastie.org/8276028 ,currently I am using the following code to send an email(via outlook) in HTML format but the formatting seems messed up sometimes... can someone provide inputs on how to send this email in a reliable way?
from email.mime.text import MIMEText
from subprocess import check_call,Popen,PIPE
def email (body,subject,to=None):
msg = MIMEText("%s" % body)
msg['Content-Type'] = "text/html; charset=UTF8"
msg["From"] = "userid#qualcomm.com"
if to!=None:
to=to.strip()
msg["To"] = to
else:
msg["To"] = "userid2#company.com"
msg["Subject"] = '%s' % subject
p = Popen(["/usr/sbin/sendmail", "-t", "-f" + msg["From"]], stdin=PIPE)
p.communicate(msg.as_string())
print "Done"
def main ():
with open('emailtext.txt', 'r') as f:
body = f.read()
Subject ="test email"
email(body, Subject, "userid3#company.com")
if __name__ == '__main__':
main()
Try using smtplib:
from smtplib import SMTP
s = SMTP('localhost',25)
s.sendmail('Me <me#example.com>', ['You <you#example.com>'],msg=msg.as_string())
If that doesn't work then your HTML is probably bad.