Hello I would like to send a mail from gmail with a EC2 server,
here is my python script :
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import smtplib
gmail_user = 'libra.corp.services#gmail.com'
gmail_password = 'pwd'
sent_from = gmail_user
to = ['aao2010#hotmail.fr']
subject = 'Value bet'
body = 'Hey, what'
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(sent_from, to, email_text)
server.close()
print('Email sent')
except:
print('Something went wrong...')
I indicate my outbound rules on EC2 server :
SMTPS TCP 465 0.0.0.0/0 -
SMTPS TCP 465 ::/0 -
TCP personnalisé TCP 587 0.0.0.0/0 -
TCP personnalisé TCP 587 ::/0 -
Plus my gmail account is setting on "Access for less secure apps to On"
Here is the output :
Something went wrong...
in my own Python app I use the port 587 with TLS, also with smtplib. That is my only difference with your setup. Did you also try that? The e-mail sending code would boil down to this:
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_password)
server.sendmail(sent_from, to, email_text)
server.close()
Related
port = 465 # For SSL
smtp_server = "smtp.mail.yahoo.com"
sender_email = "c.junction#yahoo.com" # Enter your address
password = input("Type your password and press enter:")
receiver_email = "jawoneb660#jobsfeel.com" # Enter receiver address
Subject = "Hi there"
message = """Hello World!!!
This message is sent from Python."""
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as smtp:
smtp.login(sender_email, password)
smtp.sendmail(sender_email, receiver_email, Subject, message)
I tried checking if there is any auth failure.Email could not be sent. I got following error msg.
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly
closed`
import smtplib ##Import needed modules
import ssl
port = 465 # For SSL
smtp_server = "smtp.mail.yahoo.com"
sender_email = "c.junction#yahoo.com" # Enter your address
password = input("Type your password and press enter:")
receiver_email = "jawoneb660#jobsfeel.com" # Receiver address
Subject = "Hi there"
message = """Hello World!!!
This message is sent from Python."""
context = ssl.create_default_context()
try:
print("Connecting to server...")
yahoo_server = smtplib.SMTP(smtp_server, port)
yahoo_server.starttls(context=context)
yahoo_server.login(sender_email, password)
print("Connected to server!")
print(f"Sending email to - {receiver_email}")
yahoo_server.sendmail(sender_email, receiver_email, Subject, message)
print("Email successfully sent to - {receiver_email}")
except Exception as e:
print(e)
finally:
yahoo_server.quit
I added a couple of modules that I didn't see. But you need those in order to use the ssl methods as well as the smtplib.
I also added a couple of print statements to help with seeing where in the process this might be getting hung up. You also want to close the connection as best practice.
lastly I added a variable to use with the steps of logging into the smtp server. I did this for Gmail recently so I don't know if this will work offhand, but at the very least the print statements and additional variables should hopefully help with that as well.
I have a very basic server written in Python as follows:
import socket
from time import sleep
import requests
c = None #Client socket1
addr = None #Client address1
server_socket1 = socket.socket() #by default it is SOCK_STREAM (TCP) and has porotocal AF_INET (IPv4)
server_socket1.bind(('127.0.0.1',9999)) #server machine's ip and port on which it will send and recieve connections from
server_socket1.listen(2) #We will only accept two connections as of now , one for each client
print("Server started successfully!!!")
print("Waiting for connections...\n\n")
while (((c is None)and(addr is None))):
if((c is None) and (addr is None)):
c,addr = server_socket1.accept()
print("Intrusion detected at address 127.0.0.1:9999 ")
print("Client connected with ip address "+str(addr))
client_ip=str(addr)
while True:
msg = c.recv(4096)
if(msg!=None):
#print(msg)
headers, sep, body = msg.partition(b'\r\n\r\n')
headers = headers.decode('utf-8')
print(headers)
html_body = "<html><body><h1>You are not authorized to acces this Page!</p><br><p>3 more attemps and your ip will be jailed!</p></body></html>"
response_headers = {
'Content-Type': 'text/html; encoding=utf8',
'Content-Length': len(html_body),
'Connection': 'close',
}
response_headers_raw = ''.join('%s: %s\r\n' % (k, v) for k, v in response_headers.items())
response_proto = 'HTTP/1.1'
response_status = '200'
response_status_text = 'OK' # this can be random
# sending all this stuff
r = '%s %s %s\r\n' % (response_proto, response_status, response_status_text)
c.sendall(r.encode())
c.sendall(response_headers_raw.encode())
c.sendall(b'\r\n') # to separate headers from body
c.send(html_body.encode(encoding="utf-8"))
I have then used ngrok to forward my port 9999 on the web. Then I execute the server.
Now, when I connect to the ngrok's provided link via my mobile phone, I get the response from my server, that is a single lined HTML content, as seen in the code itself.
But, the c,addr = socket.accept() should return the IP of the connected client. In my case, I have used my phone to connect to ngrok, which should use my phone's public IP to connect to it, still on my server side, it shows something like this:
Can someone please tell me what am I doing wrong here?
What you are seeing makes perfect sense, as the phone is not directly connected to your server (it can't be, since your server is listening on 127.0.0.1 aka localhost, so it can only accept connections that originate from the same machine).
The phone is connected to ngrok, and then ngrok is connected to your server. So you are seeing the IP that ngrok is connecting to your server from. There is simply no way for your server to get the IP of the phone, unless ngrok includes the phone's IP in the HTTP request it sends to your server, such as in an X-Forwarded-For, X-Original-Forwarded-For, X-Real-IP, etc kind of request header, which are common for proxies to send (but which I don't see in your screenshot, but it is incomplete).
--------- --------- ----------
| phone | <-> | ngrok | <-> | server |
--------- --------- ----------
^ ^
| |
desired IP is here but you are getting IP from here
I'm trying to develop an app to send a json string from one computer on the wireless network to another (or a phone). The problem is it has to work without knowing the IP address of the recieving computer.
The below code works if i know the IP address to send to
# UDP Server
import socket
IP = "123.123.123.123" # Not actual IP address
PORT = 66666
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((IP,PORT))
while True:
data, addr = sock.recvfrom(1024)
print(f"recieved message: {data} from: {addr}")
# UDP Client
import socket
IP = "123.123.123.123" # Not actual IP address
PORT = 66666
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
MSG = b"Hello there"
sock.sendto(MSG, (IP, PORT))
I can also use sock.getsockname()[0] to get the current IP address and listen to it, but what about sending?
I've read a few tutorials and some say to use 0.0.0.0 to send or listen to all addresses however nothing is recieved with this. The other idea was to use 192.0.0.1 on both ends to listen and send to the router but then I get 'OSError: [WinError 10049] The requested address is not valid in its context'
I thought about using broadcast but have read that this is very bad practice to the point where it was used from ipv6.
I read a suggestion to use multicasting but is there a way to get all IP addresses of computers on the local network in order to use this?
Any assistance would be hugely appreciated!
Thanks to help from rdas referring me to https://gist.github.com/ninedraft/7c47282f8b53ac015c1e326fffb664b5 i've managed to solve the issue with the below;
# UDP Server
import socket
PORT = 66666
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROT_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.bind(("",PORT))
while True:
data, addr = sock.recvfrom(1024)
print(f"recieved message: {data} from: {addr}")
# UDP Client
import socket
PORT = 66666
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROT_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
MSG = b"Hello there"
sock.sendto(MSG, ('<broadcast>', PORT))
How can I create a TCP server in python3 which will return all the files in the current directory?
You can use the socketserver library, this will serve the current working directory.
Here is the Server code
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
"""
The request handler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
# here you can do self.request.sendall(use the os library and display the ls command)
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
And here is the client side
import socket
import sys
HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])
# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
# Connect to server and send data
sock.connect((HOST, PORT))
sock.sendall(bytes(data + "\n", "utf-8"))
# Receive data from the server and shut down
received = str(sock.recv(1024), "utf-8")
print("Sent: {}".format(data))
print("Received: {}".format(received))
You should then get an output like
Server:
127.0.0.1 wrote:
b'hello world with TCP'
127.0.0.1 wrote:
b'python is nice'
Client:
$ python TCPClient.py hello world with TCP
Sent: hello world with TCP
Received: HELLO WORLD WITH TCP
$ python TCPClient.py python is nice
Sent: python is nice
Received: PYTHON IS NICE
You can then just use this code to send the current directory list
You can use socketserver which will serve the current working directory.
import socketserver # import socketserver preinstalled module
import http.server
httpd = socketserver.TCPServer(("127.0.0.1", 9000), http.server.SimpleHTTPRequestHandler)
httpd.serve_forever()
I wrote a basic server-client scripts using sockets, and everything works fine on my LAN, but it doesnt work when im trying to connect to the client thats not in my LAN. I also port forwarded these ports
this is server
###SERVER####
def ChatConnection():
print('Waiting for a connection...\n')
SOCKET = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
SOCKET.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
HOST = ''
PORT = 8989
SOCKET.bind((HOST, PORT))
SOCKET.listen(1)
CONN, ADDR = SOCKET.accept()
print('You can now chat')
while True:
MSG = str(input('\n[YOU]> '))
while not MSG: MSG = str(input('\n[YOU]> '))
CONN.send(MSG.encode())
print('\nAwaiting reply...')
REPLY = CONN.recv(4096).decode()
CONN.close()
this is client
###CLIENT###
def ChatConnection():
print('Waiting for a connection...\n')
while True:
try:
HOST = SERVER EXTERNAL IP
PORT = 8989
SOCKET = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
SOCKET.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
SOCKET.connect((HOST, PORT))
print('You can now chat with server')
print('\nWaiting for server...')
while True:
REPLY = SOCKET.recv(4096)
print('\n[USER]> %s'%REPLY.decode())
MSG = str(input('\n[YOU]> '))
while not MSG: MSG = str(input('\n[YOU]> '))
SOCKET.send(MSG.encode())
print('\nAwaiting reply...')
SOCKET.close()
except Exception: pass
what i need to do so this will work on the WAN?
Make sure that port forward WORKS, to check this run your program and try running a port scan on your public IP.Port scanning tool
Try to change the HOST to 0.0.0.0.
If that didn't work go to CMD and write netstat -a while your script is running.
Search for the port you are listening on and make sure the IP is 0.0.0.0.
If the IP is 0.0.0.0 then try to turn off your Firewall.