I try to use NodeJS SimpleSMTP. Get source from GIT (NodeJS SimpleSMTP)
And try add auth into smtp. My code is:
var SMTP_PORT = 2000;
var smtp = simplesmtp.createServer({debug:true, enableAuthentication:true});
smtp.listen(SMTP_PORT, function(err) {
if (err) console.log(err);
});
smtp.on("authorizeUser", function(connection, username, password, callback){
callback(null, true );
});
smtp.on("startData", function(connection){
console.log("Message from:", connection.from);
console.log("Message to:", connection.to);
});
smtp.on("data", function(connection, chunk){
});
smtp.on("dataReady", function(connection, callback){
console.log("Incoming message saved to /tmp/message.txt");
callback(null, "ABC1"); // ABC1 is the queue id to be advertised to the client
});
And for test I write simple client on Python:
smtpObj = smtplib.SMTP('localhost',2000)
smtpObj.set_debuglevel(1)
smtpObj.login('aaa', 'bbb')
sender="sender#email.com"
toemail = "recv#email.com"
msg = MIMEMultipart('alternative')
msg['Subject'] = "my subj"
msg['From'] = sender
msg['To'] = "recv.email.com"
msg.attach(MIMEText("Hello world!",'html'))
smtpObj.sendmail(sender, [toemail], msg.as_string())
If I comment smtpObj.login('aaa', 'bbb') everything is OK, but I need auth user before send email. For auth in Simple SMTP I should use event authorizeUser and option enableAuthentication:true.
What I do wrong? Why server is not make authentification.
My logs:
Python with show debug info:
send: 'ehlo [127.0.1.1]\r\n'
reply: '250-mypc at your service, [127.0.0.1]\r\n'
reply: '250-8BITMIME\r\n'
reply: '250-ENHANCEDSTATUSCODES\r\n'
reply: '250 STARTTLS\r\n'
reply: retcode (250); Msg: mypc at your service, [127.0.0.1]
8BITMIME
ENHANCEDSTATUSCODES
STARTTLS
Traceback (most recent call last):
File "/home/atlete/work/python/smtptest/src/test.py", line 6, in <module>
server.login("aaa", "bbb")
File "/usr/lib/python2.7/smtplib.py", line 576, in login
raise SMTPException("SMTP AUTH extension not supported by server.")
smtplib.SMTPException: SMTP AUTH extension not supported by server.
NodeJS debug info:
CONNECTION FROM 127.0.0.1
Connection from 127.0.0.1
OUT: "220 mypc ESMTP node.js simplesmtp"
COMMAND: ehlo [127.0.1.1]
OUT: "250-mypc at your service, [127.0.0.1]
250-8BITMIME
250-ENHANCEDSTATUSCODES
250 STARTTLS"
Connection closed to 127.0.0.1
Tough to say without seeing the SMTP logs (set simplesmtp debug:true), but you might check that the python auth method, i.e. LOGIN, matches what you set in the simplesmtp options.
Related
so I'm using websockets api python to connect to a server, here is my main logic, to connect to the server and send a heartbeat message to complete the initial handshake, but the server rejects the connection even before I send the heartbeat. The url format mentioned by the website is as follows:
"'wss://<<host_name>>/app/socket?auth=' + authToken "
authToken: String A base64 encoded string of CLIENT_ID
async def listen(self, client_id):
client_id_bytes = client_id.encode('ascii')
url = f"{socket_url}/app/socket?auth={base64.b64encode(client_id_bytes)}"
print(url)
async with websockets.connect(url) as ws:
await self.heart_beat(ws)
while True:
msg = await ws.recv()
print(msg)
my url on printing: wss://<<host_name>>/app/socket?auth=b'<<auth_token>>
error : websockets.exceptions.InvalidStatusCode: server rejected WebSocket connection: HTTP 401
can someone help me understand what may be missing here, thanks in advance
I'm trying to send an email to my webmail(yahoo) using python3 but I have some problems with the object. I've tried with different ports(465/587) without any success:
import smtplib
pass='letmein'
sender = 'manolo#yahoo.es'
receivers = ['raul#yahoo.es']
message = """From: From Person <from#fromdomain.com>
To: To Person <to#todomain.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP_SSL('smtp.mail.yahoo.com', 465) ### 587)
smtpObj.set_debuglevel(1)
smtpObj.login(sender, pass)
smtpObj.sendmail(sender, receivers, message)
print("Successfully sent email")
except SMTPException:
print("Error: unable to send email")
And this is the error I get:
send: 'ehlo [192.168.0.15]\r\n'
reply: b'250-kubenode501.mail-prod1.omega.ir2.yahoo.com Hello [192.168.0.15] [81.61.24.111])\r\n'
reply: b'250-PIPELINING\r\n'
reply: b'250-ENHANCEDSTATUSCODES\r\n'
reply: b'250-8BITMIME\r\n'
reply: b'250-SIZE 41697280\r\n'
reply: b'250 AUTH PLAIN LOGIN XOAUTH2 OAUTHBEARER\r\n'
reply: retcode (250); Msg: b'kubenode501.mail-prod1.omega.ir2.yahoo.com Hello [192.168.0.15] [81.61.24.111])\nPIPELINING\nENHANCEDSTATUSCODES\n8BITMIME\nSIZE 41697280\nAUTH PLAIN LOGIN XOAUTH2 OAUTHBEARER'
send: 'AUTH PLAIN AGF1c3RyYWxiaXRAeWFob28uZXMAQWFsaWNpYTAy\r\n'
reply: b'535 5.7.0 (#AUTH005) Too many bad auth attempts.\r\n'
reply: retcode (535); Msg: b'5.7.0 (#AUTH005) Too many bad auth attempts.'
send: 'AUTH LOGIN YXVzdHJhbGJpdEB5YWhvby5lcw==\r\n'
Error: unable to send email
Any idea about how to fix this error?
There are a few things to fix:
Use smtplib.SMTP_SSL('smtp.mail.yahoo.com', 465) because port 465 expects connection using SSL.
Add smtpObj.set_debuglevel(1) to have better help with debugging - this will tell you that you need to login first.
Use smtpObj.login("login", "password") before trying to send an email.
The From email should be the same as the login.
I am trying to get the Socket.IO work with my Django server. Here is my setup:
Frontend js:
const socket = io.connect('127.0.0.1:8001');
socket.on('connect', () => {
console.log('socket id: %s\n', socket.id);
});
Django server:
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
sio = socketio.Server(async_mode='eventlet', cors_allowed_origins='*', logger=True, engineio_logger=True)
#sio.event
def connect(sid, environ, auth):
print('connect ', sid, auth)
static_files = {
'/public': './static',
}
application = socketio.WSGIApp(sio, application, static_files=static_files)
eventlet.wsgi.server(eventlet.listen(('', 8001)), application)
Dependencies
Django==2.2.11
django-cors-headers==3.0.0
eventlet==0.30.0
gunicorn==19.7.1
python-socketio==4.6.1
...
When I run the js, the server will return 401 unauthorized error before reaching the connect function.
Frontend:
GET http://127.0.0.1:8001/socket.io/?EIO=3&transport=polling&t=NYKlRjO 401 (UNAUTHORIZED)
Django server log:
(11053) accepted ('127.0.0.1', 34906)
127.0.0.1 - - [02/Apr/2021 15:39:31] "GET /socket.io/?EIO=3&transport=polling&t=NYKlTB8 HTTP/1.1" 401 253 0.002482
But the weird thing is if I commented out the connect event, everything like other events work just fine:
# #sio.event
# def connect(sid, environ, auth):
# print('connect ', sid, auth)
The Django server is running on the same port 8001. I don't think there is any authentication check on the connect event or on the socket. Anyone knows why if I setup the connect event and the socket suddenly stop working?
It took me hours to figure this out because of the server response code is irrelevant to the issue here.
The problem is, for my case, when the js trying to connect to the socket server, there is no auth argument so the connect function will raise an exception cases the connection to fail, while all exceptions raise from the conncet function will result in 401 unauthorized although it may not be the authorization issue.
The fix is simple, change the connect definition to:
#sio.event
def connect(sid, environ, auth=''):
print('connect ', sid, auth)
will address the issue. Always assing auth token from the frontend js is a good idea as well.
So I'm trying to send an email to my self using SMTP and AWS. The email I'm using on my configuration is verified since I'm still using sandbox mode in SES. While running the script I keep getting the error Connection unexpectedly closed even dough I tried to connect with OpenSSL and it connected but it showed a Didn't find STARTTLS in server response, trying anyway... error after connecting.
Here is my code:
MAIL = {}
MAIL['USERNAME'] = 'AKIAXARHTFGFKCDAO7PD'
MAIL['PASSWORD'] = 'BE0tXPq8wteiKZYtgD2TgtfFTGhgFGOhUp3F0lG0uqn'
MAIL['HOST'] = 'email-smtp.eu-central-1.amazonaws.com'
MAIL['PORT'] = 465
# Set user code
code = random.randrange(000000, 999999)
# Send email to user
print(code)
print(current_user.email)
msg = MIMEMultipart('alternative')
msg['Subject'] = 'Ruby - Verification code'
msg['From'] = 'amng835#gmail.com'
msg['To'] = current_user.email
msg.attach(MIMEText(f'Your verification code is: {code}', 'plain'))
try:
server = smtplib.SMTP(MAIL['HOST'], MAIL['PORT'])
server.ehlo()
server.starttls()
server.ehlo()
server.login(MAIL('MAIL_USERNAME'), MAIL('MAIL_PASSWORD'))
server.sendmail('amng835#gmail.com', current_user.email, msg.as_string())
server.close()
except Exception as error:
print('Failed to send message to user')
print(error)
OpenSSL output:
The command:
openssl s_client -connect email-smtp.eu-central-1.amazonaws.com:465 -starttls smtp
The output:
CONNECTED(00000005)
Didn't find STARTTLS in server response, trying anyway...
write:errno=0
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 372 bytes
Verification: OK
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
Early data was not sent
Verify return code: 0 (ok)
---
My documentation source:
https://docs.aws.amazon.com/ses/latest/DeveloperGuide/examples-send-using-smtp.html
There seems to have some issue with port 465.Change the code to below and it will work fine.
MAIL['PORT'] = 587
I am able to send emails fine from a script using smtplib, but when I try to run it from a batch file or from task scheduler everything works except the email doesn't send at the end. I get a "No SSL" error.
I'm running this from a conda environment, but I've double checked that I calling python from within that environment and not base.
python version 3.7.3.
I call this function from another script and pass the email subject and message to the function.
def send_log_email(subject, message):
smtp_server = 'smtp.office365.com'
smpt_port = 25
sender = '[emailed address]'
pw = '[password]'
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = sender
msg['Subject'] = subject
msg.attach(MIMEText(message))
conn = SMTP(smtp_server,smtp_port)
conn.set_debuglevel(1)
conn.starttls()
conn.login(sender, pw)
conn.sendmail(sender, sender, msg.as_string())
Here's the error I get when I run it from a batch file.
send: 'ehlo []\r\n'
reply: b'250-Outlook Hello [IP]\r\n'
reply: b'250-SIZE 157286400\r\n'
reply: b'250-PIPELINING\r\n'
reply: b'250-DSN\r\n'
reply: b'250-ENHANCEDSTATUSCODES\r\n'
reply: b'250-STARTTLS\r\n'
reply: b'250-8BITMIME\r\n'
reply: b'250-BINARYMIME\r\n'
reply: b'250-CHUNKING\r\n'
reply: b'250 SMTPUTF8\r\n'
reply: retcode (250); Msg: b'outlook' Hello [IP]\nSIZE 157286400\nPIPELINING\nDSN\nENHANCEDSTATUSCODES\nSTARTTLS\n8BITMIME\nBINARYMIME\nCHUNKING\nSMTPUTF8'
send: 'STARTTLS\r\n'
reply: b'220 2.0.0 SMTP server ready\r\n'
reply: retcode (220); Msg: b'2.0.0 SMTP server ready'
Traceback (most recent call last):
File "path\my_script.py", line 136, in <module>
send_log_email(result, message)
File "path\my_email_script.py", line 31, in send_log_email
conn.starttls()
File "python_path\custom_environment\lib\smtplib.py", line 756, in starttls
raise RuntimeError("No SSL support included in this Python")
RuntimeError: No SSL support included in this Python
Contrary to most of what I found online, I needed to activate the environment in the batch file to get the script to run properly from task scheduler.
call C:\ProgramData\Anaconda3\Scripts\activate.bat
"C:\my_env_path\python.exe" "C:\my_script_path\my_script.py"
call C:\ProgramData\Anaconda3\Scripts\deactivate.bat
Not sure if I actually need to deactivate the environment or not, but there it is.