How to add attachments from Flask to win32com? - python

Hi I am having trouble attaching flask uploads to Outlook,
I need to attach uploads from flask to outlook.
Thanks
''' f = rq.files['filesattach']
msg.HTMLBody = str("<br> <br>Hi, the follow data are attached to this email <br>").title() + "\n \n" + "<br> Date Request Sent to Permit Coordinator: " + dateReq + "\n" + "<br>WO #: "+ wo+ " \n" + "<br>Date Needed: " + dateNeed + "\n" +"<br>SR: "+ sr + "\n" + "<br>TCF: " +tcf + "\n" + "<br>Munplicity: "+ mun + "\n" + "<br>Political Sub: " + polSub + "\n" + '<br>Address: '+ address + "\n" + '<br>Cross Street: ' + cross + "\n" + '<br>Description: '+ desc + "\n" + "<br>Permit Type: " + permitType
msg.Subject = "WO " + wo +" "+ permitType+" "+"Permit Form"
msg.Display()
shell.AppActivate("Outlook")
shell.SendKeys("%s", 0)
saved = f.save(secure_filename(f.filename))
return "Message sent"
else:
return render_template(permitForm)'''

uploaded_files = rq.files.getlist("filesattach")
for i in uploaded_files:
file = os.path.realpath(str(i.filename))
msg.attachments.Add(file)

Related

How can I stop getting 2 different print results under same condition

newbie here. I want to get only one result when condition met but couldn't figure out how to do that.
current_threshold = (max_bid_val - min_ask_val) * 100 / min_ask_val
if (current_threshold > threshold) :
alert_message = "Buy " + coin_list[i] + " on " + min_ask_place + " website for " + str(
min_ask_val) + " price and Sell on " + max_bid_place + " for " + str(max_bid_val) + " price."
alert_message_paribu = "Buy " + coin_list[i] + " on " + min_ask_place + " website for " + str((
min_ask_val * paribu_dic[symbol_usdt_tl][
'highestBid'])) + " price and Sell on " + max_bid_place + " for " + str(max_bid_val) + " price."
if 'paribu' in min_ask_place :
print(alert_message_paribu)
start_alert(alert_message_paribu)
telegram_send.send(messages=[alert_message_paribu])
time.sleep(10)
else : #if min_ask_place is not paribu I need to get results as alert_message
alert_message = "Buy " + coin_list[i] + " on " + min_ask_place + " website for " + str(
min_ask_val) + " price and Sell on " + max_bid_place + " for " + str(max_bid_val) + " price."
print(alert_message)
start_alert(alert_message)
telegram_send.send(messages=[alert_message])
time.sleep(10)
any idea or suggestions? sorry if it's too ignorant. thanks
Looks like you have two print statements where there is a condition that allows both to run. Does it print twice if 'paribu' is not in min_ask_place? maybe move the second print under the else.

I can't see what is triggering the invalid Syntax error

I am currently trying to replicate a packet sniffer in python that can parse udp, tcp, and ICPM packets.
As it is now no other compiler errors show except an invalid syntax error.
#packet sniffer for linux in python
import socket, sys
from struct import*
#A function that converts a string of 6 characters of ethernet address into dash seperated hex string
def ethernet_address (string):
new_String = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(string(0)), ord(string(1)), ord(string(2)), ord(string(3)), ord(string(4)), ord(string(5)))
return new_String
#Section that creates the socket
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.ntohs(0x0003))
except socket.error as msg:
print ("Socket could not be created, Error : ")
print (msg)
sys.exit()
#recieve a packet
while True:
packet = sock.recvfrom(60000)
#packet string from tuple
packet = packet[0]
#parse ethernet header
ether_length = 14
ether_Header = packet[:ether_length]
ether = unpack('!6s6sh', ether_Header)
ether_protocol = socket.ntohs(ether[2])
print ("Destination MAC: " + ethernet_address(packet[0:6]) + "Source MAC: " + ethernet_address(packet[6:12]) + " Protocol: " + str(ether_protocol))
#This section handles parsing IP packets
if ether_protocol == 8:
#Parse the IP header
#take the first 20 character from the header
ip_header = packet[ether_length:20 + ether_length]
#now unpack
iph = unpack('!BBHHHBBH4s4s', ip_header)
version_ihl = iph[0]
version = version_ihl >> 4
ihl = version_ihl & 0xf
iph_length = ihl * 4
ttl = iph[5]
protocol = iph[6]
source_address = socket.inet_ntoa( iph[8] )
destination_address = socket.inet_ntoa( iph[9] )
print("Version: " + str(version) + " IP header length: " + str(ihl) + " TTL: " + str(ttl) + " Protocol: " + str(protocol + " Source Address: " + str(source_address) + " Destination Address: " + str(destination_address) )
#This section handles parsing TCP packets
if protocol == 6 : #This is the line with the error******************************************
num = iph_length + ether_length
tcp_header = packet[ num:num+20]
#unpack
tcph = unpack('!HHLLBBHHH', tcp_header)
source_port = tcph[0]
destination_port = tcph[1]
sequence = tcph[2]
acknowledgment = tcph[3]
doff_reserve = tcph[4]
tcph_length = doff_reserve >> 4
print("Source Port: " + str(source_port) + " Destination Port: " + destination_port + " Sequence: " + sequence + " Acknowledgment: " + str(acknowledgment) + " TCP header length: " + str(tcph_length))
h_size = ether_length + iph_length + tcph_length * 4
data_size = len(packet) - h_size
#get data
data = packet[h_size:]
print ("Data: "+ data)
#This section Handles parsing ICMP packets
elif protocol == 1:
u = iph_length + ether_length
icmph_length = 4
icmp_header = packet[u:u+20]
#unpack
icmph = unpack('!BBH', icmp_header)
icmp_type = icmph[0]
code = icmph[1]
checksum = icmph[2]
print("Type: " + str(icmp_type) + " Code: " + str(code) + " Checksum: " + str(checksum))
h_size = ether_length + iph_length + icmph_length
data_size = len(packet) - h_size
#retrive data
data = packet[h_size]
print("Data: " + data)
#This section handles parsing UDP
elif protocol == 17:
u = iph_length +ether_length
udph_length = 8
udp_header = packet[u:u+8]
#now unpack them
udph = unpack('!HHHH', udp_header)
src_port = udph[0]
dest_port = udph[1]
length = udph[2]
checksum = udph[3]
print("Source Port: " + str(src_port) + " Destination Port: " + str(dest_port) + " Length: " + str(length) + " Checksum: " + str(checksum) )
h_size = ether_length + iph_length + udph_length
data_size = len(packet) - h_size
#get data
data = packet[h_size]
print("Data: " + data)
else:
print("Protocol is something other than UDP, ICMP, or TCP")
print
The error is caused by the line:
if protocol == 6 :
Visual Studio says that this is a syntax error, but I'm of how because it is written just like every other if statement and they don't have a syntax error warning. What is the error if there is one?
I believe you are missing a bracket. print("Version: " + str(version) + " IP header length: " + str(ihl) + " TTL: " + str(ttl) + " Protocol: " + str(protocol + " Source Address: " + str(source_address) + " Destination Address: " + str(destination_address) )) should work.
Note: I added a bracket at the end but that might not be where it should be added for your code to function as intended despite removing the error. It seems print("Version: " + str(version) + " IP header length: " + str(ihl) + " TTL: " + str(ttl) + " Protocol: " + str(protocol) + " Source Address: " + str(source_address) + " Destination Address: " + str(destination_address) ) is likely what you want.
The error is found in the line above:
print("Version: " + str(version) + " IP header length: " + str(ihl) + " TTL: " + str(ttl) + " Protocol: " + str(protocol + " Source Address: " + str(source_address) + " Destination Address: " + str(destination_address) )
Specifically, the error comes from ... str(protocol + ..., which should be ... str(protocol) + ....
You have an unmatched parenthesis on the previous line:
print("Version: " +
str(version) +
" IP header length: " +
str(ihl) +
" TTL: " +
str(ttl) +
" Protocol: " +
str(protocol +
" Source Address: " +
str(source_address) +
" Destination Address: " +
str(destination_address)
)
You probably want something like this:
print("Version: " +
str(version) +
" IP header length: " +
str(ihl) +
" TTL: " +
str(ttl) +
" Protocol: " +
str(protocol) +
" Source Address: " +
str(source_address) +
" Destination Address: " +
str(destination_address)
)
Also, consider using " ".join(iterable) to join strS with spaces. Concatenation is inefficient (not an issue here) and difficult to read (definitely an issue here).

using a variable from a json.load in another function

I am using an API for receiving TTN data from a device. i have created a function "def on_message(mqttc, obj, msg):", using a json.loads(msg.payload.decode('utf-8')) to receive mqtt data.
I want to pick the variable "node_data" and use in def devdata(). but it seems that i do not get anything but None.
import paho.mqtt.client as mqtt
import json
import pybase64
import binascii
APPEUI = "0018B24441524632"
APPID = "adeunis_fieldtester"
PSW = "ttn-account-v2.vuQczD1bmPoghhaKjlIHR-iHovHIbYMpfWSKosPAGaU"
# Call back functions
# gives connection message
def on_connect(mqttc, mosq, obj, rc):
print("Connected with result code:" + str(rc))
# subscribe for all devices of user
mqttc.subscribe('+/devices/+/up')
# gives message from device
def on_message(mqttc, obj, msg):
try:
x = json.loads(msg.payload.decode('utf-8'))
# metadata
app = x["app_id"]
device = x["dev_id"]
deveui = x["hardware_serial"]
port = x["port"]
confirmed = x["confirmed"]
counter = x["counter"]
payload_fields = x["payload_raw"]
datetime = x["metadata"]["time"]
gateways = x["metadata"]["gateways"]
frequency = x["metadata"]["frequency"]
modulation = x["metadata"]["modulation"]
data_rate = x["metadata"]["data_rate"]
air_time = x["metadata"]["airtime"]
coding_rate = x["metadata"]["coding_rate"]
for gw in gateways:
gateway_id = gw["gtw_id"]
timestamp = gw["timestamp"]
time = gw["time"]
channel = gw["channel"]
gwrssi = gw["rssi"]
gwsnr = gw["snr"]
# decoding the payload_field
payload_r = (pybase64.b64decode(payload_fields + "="))
# decoding the Payload_r to Byte-Ascii string
payload_h = binascii.hexlify(payload_r)
# Byte to tekst
node_data = (payload_h.decode("utf-8)")) #this is the variable i would like to use in devdata()
# Printing data, + str(payload_fields) + ", "
print(str(app) + ", " + str(device) + ", " + str(deveui) + ", " + str(port) + ", " + str(counter) + ", "
+ str(node_data) + ", " + str(modulation) + ", " + str(datetime) + ", " + str(frequency) + ", "
+ str(confirmed) + ", " + str(data_rate) + ", " + str(air_time) + ", " + str(coding_rate) + ", "
+ str(gateway_id) + ", " + str(timestamp) + ", " + str(time) + "," + str(channel) + ", "
+ str(gwrssi) + ", " + str(gwsnr))
return node_data #return data for use in devdata()
except Exception as e:
print(e)
pass
def devdata():
node_data = on_message() # trying to use this as the Variable
temperatur = int(node_data[2:4], 16)
print("temperatur =", temperatur)
`

why there is a "SyntaxError: invalid syntax"

Error message:
runfile('//rschfs1x/userrs/xd73_RS/Documents/Python Scripts/test_515.py', wdir='//rschfs1x/userrs/xd73_RS/Documents/Python Scripts')
File "//rschfs1x/userrs/xd73_RS/Documents/Python Scripts/test_515.py", line 120
if __name__ == "__main__":
^
SyntaxError: invalid syntax
Really not sure why thre is this problem
def sendemail(alertmessage):
msg = MIMEText(alertmessage)
msg['Subject'] = 'Patent Data Error Message'
msg['From'] = "patentcornell#gmail.com"
msg['To'] = "patentcornell#gmail.com"
# Credentials (if needed)
username = 'patentcornell#gmail.com'
password = ''
# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail("hello", "xd73#cornell.edu", alertmessage)
server.sendmail("hello", "jq58#cornell.edu", alertmessage)
#server.sendmail("hello", "sl2448#cornell.edu", alertmessage)
server.sendmail("hello", "patentcornell#gmail.com", alertmessage)
'''
Shanjun Li <sl2448#cornell.edu>,
Panle Barwick <pjb298#cornell.edu>,
Jing Qian <jq58#cornell.edu>
'''
server.quit()
def main(year = 1985, starting_page = 2, filepath = ""):
time1 = time.time()
print "start timing: " + str(time1)
driver = webdriver.Firefox()
driver.get("http://epub.sipo.gov.cn/")
elem = driver.find_element_by_id("soso_text")
f = open( filepath + "year_test_" + str(year), "wb")
flog = open(filepath + "log_" + str(year), "wb")
driver.get("http://epub.sipo.gov.cn/")
elem = driver.find_element_by_id("soso_text")
elem.send_keys(str(year))
elem.send_keys(Keys.RETURN)
content = driver.page_source.encode('utf-8')
for uchar in content:
f.write(bytearray([ord(uchar)]))
flog.write(str(year) + " " + str(1) + "\n")
case = 1
nextpage = driver.find_element_by_xpath("/html/body/div[3]/div[2]/div[4]/a[7]")
turnto = driver.find_element_by_xpath("/html/body/div[3]/div[2]/div[4]/span")
print "hello 0"
print nextpage.get_attribute("innerHTML")
totalnum = int(nextpage.get_attribute("innerHTML"))
print "totalnum: " + str(totalnum)
#try:
# from which page we start downloading, the starting page
for i in range(starting_page, totalnum + 1):
timeinterval_1 = time.time()
print str(year) + " page: " + str(i)
#turnto = driver.find_element_by_xpath("/html/body/div[3]/div[2]/div[4]/span")
turnto = driver.find_element_by_id('pn')
turnto.send_keys(str(i))
turnto.send_keys(Keys.ENTER)
#turnto.submit()
content = driver.page_source.encode('utf-8')
# test file writing speed
time_file_start = time.time()
for uchar in content:
f.write(bytearray([ord(uchar)]))
f.write("\n")
#robust Check
print "interval: " + str(timeinterval_2 - timeinterval_1)
if timeinterval_2 - timeinterval_1 > 60:
flog.write("lost: " + str(year) + " page: " + str(i) + "\n")
print "too long to load " + str(year) + " " + str(i)
continue
else:
flog.write(str(year) + " " + str(i) + "\n")
continue
#except ValueError as err:
print(err.args)
sendmail("xd73_RS: " + err.args + " " + str(time.time())
if __name__ == "__main__":
filepath = "U:/Documents/Python Scripts/test_data_515/"
#sendemail("test email function!")
main(2010, 2, filepath)
This line:
sendmail("xd73_RS: " + err.args + " " + str(time.time())
Has unmatched parentheses. Generally if the syntax error occurs on line n, its a good idea to check the syntax on line n-1.

print the result of a scapy function in tkinter

a=lb + "(IP(src='" + SrcIP + "', dst='" + DestIP + "')/TCP(sport=" + SrcPort + ", dport=" + DestPort + ",flags='"+P+""+S+""+A+""+U+""+F+""+R+"'), timeout=" + Timeout + ")"
p=eval(a)
p.show()
tkMessageBox.showinfo(title = "the configuration and results", message = "The configuration is:\nFlags:"+psh+"\n"+syn+"\n"+ack+"\n"+urg+"\n"+fin+"\n"+rst+"\nSource IP:"+SrcIP + "\nDestination IP: " + DestIP + "\nSource Port: " +SrcPort+ "\nDestination port: " + DestPort + "\nTimeout: " +Timeout+"\nSend/Received method: "+lb+"\t")
How can i put the result of p.show() in tkMessageBox.showinfo?
I don't think you can, as the .show() method only uses print statements.

Categories