Django send_mail results in error 61 refused on Mac OSX - django

Running into a very stange error. I'm running Django on my Mac OSX and when I tried to send an email from my application it hangs and gives me this error: "Error 61 Connection Refused"
Any ideas? I don't have my firewall turned on. I can upload an image of the error if needed.

Have you actually configured the EMAIL_* settings in settings.py? Error 61 is the error you get if you leave it on the default values and you don't have a local SMTP server running.
Alternatively, as Peter suggests, if you have set it up then you might need to use authentication with your SMTP server.

Being totally Max OS X ignorant, my first guess would be that your SMTP server requires authentication.

Its simple, if sendmail works via command-line, copy the code from http://djangosnippets.org/snippets/1864/ into a file called sendmail.py
"""sendmail email backend class."""
import threading
from django.conf import settings
from django.core.mail.backends.base import BaseEmailBackend
from subprocess import Popen,PIPE
class EmailBackend(BaseEmailBackend):
def __init__(self, fail_silently=False, **kwargs):
super(EmailBackend, self).__init__(fail_silently=fail_silently)
self._lock = threading.RLock()
def open(self):
return True
def close(self):
pass
def send_messages(self, email_messages):
"""
Sends one or more EmailMessage objects and returns the number of email
messages sent.
"""
if not email_messages:
return
self._lock.acquire()
try:
num_sent = 0
for message in email_messages:
sent = self._send(message)
if sent:
num_sent += 1
finally:
self._lock.release()
return num_sent
def _send(self, email_message):
"""A helper method that does the actual sending."""
if not email_message.recipients():
return False
try:
ps = Popen(["sendmail"]+list(email_message.recipients()), \
stdin=PIPE)
ps.stdin.write(email_message.message().as_string())
ps.stdin.flush()
ps.stdin.close()
return not ps.wait()
except:
if not self.fail_silently:
raise
return False
return True
Inside of settings.py, set the variable:
EMAIL_BACKEND = 'path.to.sendmail.EmailBackend'

I had a similar problem and found this link: http://dashasalo.com/2011/05/29/django-send_mail-connection-refused-on-macos-x/
Basically, you need to have a mail server running in order to send mail from it. If there is no mail server running you will get a 61.

Related

Unable to send emails through Flask-mail

I have been trying to create a web app which takes email address as an input through HTML form and sends a one time pin for further access to website.
I have 2 html files in my template folder (one for taking user's email address and other for OTP entering)
i have config.json file which stores my accountid and password through which i intend to send the OTP.
.py file
from flask import Flask, render_template, request
from random import randint
import json
from flask_mail import *
with open('config.json','r') as f:
params = json.load(f)['params']
mail = Mail(app)
otp = randint(100,999) #otp production
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = params['gmail-user']
app.config['MAIL_PASSWORD'] = params['gmail-password']
#app.route('/')
def home():
return(render_template('otpgive.html'))
#app.route('/getOTP', methods = ['POST'])
def getOTP(): #OTP send and Verify here
email_id = request.form['usermail']
msg = Message('OTP for the APPLICATION', sender = 'my_email', recipients = [email_id])
#my_email is the email through which i plan to send messages.
msg.body = "Greetings! Your email has been verified successfully. Kindly note your OTP is " + str(otp)
mail.send(msg)
return render_template('otpconfirm.html')
#app.route('/validateOTP', methods = ['POST'])
def validateOTP():
userotp = request.form['otp']
if (otp == int(userotp)):
return ("Email Verified Succcessfully ")
else:
return render_template('otpgive.html',msg = 'incorrect otp')
if __name__ == '__main__':
app.run(debug = False)
#app.run(host='0.0.0.0',port=5000, debug = True)
Solutions I tried but failed:
Tried disabling the firewall.
Tried setting the port number for 0.0.0.0
Tried debug = False
I was expecting it to work. i.e send emails to the users but it shows ConnectionError or InternalServerError
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
ConnectionRefusedError:
[WinError 10061] No connection could be made because the target machine actively refused it
I finally got the solution.
Since I was using G-Mail, I had to enable 2FA (2-Factor Auth) first on my profile, and then generate a new password for my app.
The password thus obtained was pasted in the config.json file instead of my
main profile password.
Used directions from this thread Less Secure option in gmail unavailable
Now Changes I made in my code:
Reverted back to ip: host='0.0.0.0', port=5000, debug = True
I kept firewall disabled as a precaution.
I repositioned mail = Mail(app) line to after all app.configs

How to send socket messages via Django views when socket server and views.py are split into two files?

Env: Python 3.6, and Django 2.1
I have created a Django website and a socket server, and files are organized like this:
web
...
user (a Django app)
__init__.py
views.py
...
server.py
Actually I want to build a umbrella rental system by using django, and server connects to umbrella shelf via multi-thread socket (sending some messages). Like I press the borrow button, and views.py can call the server test_function and send some messages to the connected umbrella shelf.
I can import server variables or functions in views.py, but I cannot get the right answer while server.py is running. So I want to ask you if you could give me some advice. Thanks a lot!
By the way, I tried to import the global variable clients directly in views.py, but still got [].
server.py defines a multi-thread server, which is basically as below:
clients = []
class StuckThread(threading.Thread):
def __init__(self, **kwargs):
self.name = kwargs.get('name', '')
def run(self):
while True:
# do something
def func1(self):
# do something
def test_function(thread_name):
# if the function is called by `views.py`, then `clients = []` and return 'nothing', but if I call this function in `server.py`, then I can get a wanted result, which is `got the thread`
for client in clients:
if client['thread'].name == thread_name:
return 'got the thread'
return 'nothing'
if __name__ == '__main__':
ip_port = ('0.0.0.0', 65432)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ip_port)
server.listen(max_listen_num)
while True:
client, address = socket.accept()
param = {'name': 'test name'}
stuck_thread = StuckThread(**param)
clients.append({"client": client, "address": address, "thread": stuck_thread})
stuck_thread.start()
and I have a Django views.py like this
def view_function(request):
from server import clients
print(clients) # got []
form server import test_function
print(test_function('test name')) # got 'nothing'
return render(request, 'something.html')
I have solve this problem by socket communication between django views.py and server.py. I open another port to receive messages from views.py. Once the borrow button is pressed, a socket client in views.py will build up and send arguments and other messages to the server.

Connecting flask-socketio with user_loader

Warning: Apologies for the long post
We are currently running a flask server with a couchdb backend. We have a few API endpoints that provide user information. We've used flask-login for user management. THe user_loader checks the user database on each request:
#login_manager.user_loader
def load_user(id):
mapping = g.couch.get('_design/authentication')
mappingDD = ViewDefinition('_design/authentication','auth2',mapping['views']['userIDMapping']['map'])
for row in mappingDD[id]:
return userModel.User(row.value)
We also have a segment that has a websocket to enable chat between the server and the client. The code below I took after seeing the authentication section of the flask-socketio documentation:
def authenticated_only(f):
#functools.wraps(f)
def wrapped(*args, **kwargs):
if not current_user.is_authenticated:
disconnect()
else:
return f(*args, **kwargs)
return wrapped
I have the following code for my web socket:
#app.route('/sampleEndPoint/')
def chatRoom():
return render_template('randomIndex.html', async_mode=socketio.async_mode)
#socketio.on('connect', namespace='/test')
#authenticated_only
def test_connect():
app.logger.debug(session)
emit('my_response', {'data': 'Connected'})
#socketio.on('disconnect_request', namespace='/test')
#authenticated_only
def disconnect_request():
session['receive_count'] = session.get('receive_count', 0) + 1
emit('my_response',{'data': 'Disconnected!', 'count': session['receive_count']})
disconnect()
#socketio.on('disconnect', namespace='/test')
#authenticated_only
def test_disconnect():
print('Client disconnected', request.sid)
Everything works well in the other routes. However, I get the following error when I connect to the websocket:
File "/home/sunilgopikrishna/insurance_brokerage/perilback/main.py",
line 144, in load_user
mapping = g.couch.get('_design/authentication') File "/home/sunilgopikrishna/.local/lib/python3.5/site-packages/werkzeug/local.py",
line 343, in getattr
return getattr(self._get_current_object(), name) AttributeError: '_AppCtxGlobals' object has no attribute 'couch'
I read in the flask-socketio documentation that login_required does not work with socketio.
Is there a workaround for this? Any help is appreciated.
Regards,
Galeej
I read in the flask-socketio documentation that login_required does not work with socketio
Sure, but you are not using login_required in your socketio events, so that is not the problem here.
The problem is that you probably have a before_request handler that sets g.couch. The "before" and "after" handlers only run for HTTP requests, they do not run for Socket.IO, because in this protocol there is no concept of requests, there is just a single long-term connection.
So basically, you need to find another way to access your database connection in your user loader handler that does not rely on a before_request handler.

Using Telegram bot webhook by pyTelegramBotAPI and Flask on pythonanywhere.com

The question is about using webhooks in a Telegram bot using the pyTelegramBotAPI module.
I am using pythonanywhere.com to host the bot.
The following code works fine:
from flask import Flask, request
import telebot
secret = "A_SECRET_NUMBER"
bot = telebot.TeleBot ('YOUR_AUTHORIZATION_TOKEN')
bot.set_webhook("https://YOUR_PYTHONANYWHERE_USERNAME.pythonanywhere.c..
}".format(secret), max_connections=1)
app = Flask(__name__)
#app.route('/{}'.format(secret), methods=["POST"])
def telegram_webhook():
update = request.get_json()
if "message" in update:
text = update["message"]["text"]
chat_id = update["message"]["chat"]["id"]
bot.sendMessage(chat_id, "From the web: you said '{}'".format(text))
return "OK"
But when I use message handlers as shown in the example, I receive no answer from the bot:
# Process webhook calls
#app.route(WEBHOOK_URL_PATH, methods=['POST'])
def webhook():
if flask.request.headers.get('content-type') == 'application/json':
json_string = flask.request.get_data().decode('utf-8')
update = telebot.types.Update.de_json(json_string)
bot.process_new_updates([update])
return ''
else:
flask.abort(403)
# Handle '/start' and '/help'
#bot.message_handler(commands=['help', 'start'])
def send_welcome(message):
bot.reply_to(message,
("Hi there, I am EchoBot.\n"
"I am here to echo your kind words back to you."))
# Handle all other messages
#bot.message_handler(func=lambda message: True, content_types=['text'])
def echo_message(message):
bot.reply_to(message, message.text)
I have tried examples from different libraries, but still no answer.
Any ideas?
It would be great if you could share a working example of Telegram "echo-bot" on pythonanywhere.com.
Thanks.
You should disable threading in the TeleBot constructor like this:
bot = telebot.TeleBot('YOUR_AUTHORIZATION_TOKEN', threaded=False)
I had the same issue and found a solution here:
https://www.pythonanywhere.com/forums/topic/9562/#id_post_40177
Threading is unavailable for free PythonAnywhere accounts.
Error in 17th line. return "ok" not in telegram_webhook function.

Emit/Broadcast Messages on REST Call in Python With Flask and Socket.IO

Background
The purpose of this project is to create a SMS based kill switch for a program I have running locally. The plan is to create web socket connection between the local program and an app hosted on Heroku. Using Twilio, receiving and SMS will trigger a POST request to this app. If it comes from a number on my whitelist, the application should send a command to the local program to shut down.
Problem
What can I do to find a reference to the namespace so that I can broadcast a message to all connected clients from a POST request?
Right now I am simply creating a new web socket client, connecting it and sending the message, because I can't seem to figure out how to get access to the namespace object in a way that I can call an emit or broadcast.
Server Code
from gevent import monkey
from flask import Flask, Response, render_template, request
from socketio import socketio_manage
from socketio.namespace import BaseNamespace
from socketio.mixins import BroadcastMixin
from time import time
import twilio.twiml
from socketIO_client import SocketIO #only necessary because of the hack solution
import socketIO_client
monkey.patch_all()
application = Flask(__name__)
application.debug = True
application.config['PORT'] = 5000
# White list
callers = {
"+15555555555": "John Smith"
}
# Part of 'hack' solution
stop_namespace = None
socketIO = None
# Part of 'hack' solution
def on_connect(*args):
global stop_namespace
stop_namespace = socketIO.define(StopNamespace, '/chat')
# Part of 'hack' solution
class StopNamespace(socketIO_client.BaseNamespace):
def on_connect(self):
self.emit("join", 'server#email.com')
print '[Connected]'
class ChatNamespace(BaseNamespace, BroadcastMixin):
stats = {
"people" : []
}
def initialize(self):
self.logger = application.logger
self.log("Socketio session started")
def log(self, message):
self.logger.info("[{0}] {1}".format(self.socket.sessid, message))
def report_stats(self):
self.broadcast_event("stats",self.stats)
def recv_connect(self):
self.log("New connection")
def recv_disconnect(self):
self.log("Client disconnected")
if self.session.has_key("email"):
email = self.session['email']
self.broadcast_event_not_me("debug", "%s left" % email)
self.stats["people"] = filter(lambda e : e != email, self.stats["people"])
self.report_stats()
def on_join(self, email):
self.log("%s joined chat" % email)
self.session['email'] = email
if not email in self.stats["people"]:
self.stats["people"].append(email)
self.report_stats()
return True, email
def on_message(self, message):
message_data = {
"sender" : self.session["email"],
"content" : message,
"sent" : time()*1000 #ms
}
self.broadcast_event_not_me("message",{ "sender" : self.session["email"], "content" : message})
return True, message_data
#application.route('/stop', methods=['GET', 'POST'])
def stop():
'''Right here SHOULD simply be Namespace.broadcast("stop") or something.'''
global socketIO
if socketIO == None or not socketIO.connected:
socketIO = SocketIO('http://0.0.0.0:5000')
socketIO.on('connect', on_connect)
global stop_namespace
if stop_namespace == None:
stop_namespace = socketIO.define(StopNamespace, '/chat')
stop_namespace.emit("join", 'server#bayhill.com')
stop_namespace.emit('message', 'STOP')
return "Stop being processed."
#application.route('/', methods=['GET'])
def landing():
return "This is Stop App"
#application.route('/socket.io/<path:remaining>')
def socketio(remaining):
try:
socketio_manage(request.environ, {'/chat': ChatNamespace}, request)
except:
application.logger.error("Exception while handling socketio connection",
exc_info=True)
return Response()
I borrowed code heavily from this project chatzilla which is admittedly pretty different because I am not really working with a browser.
Perhaps Socketio was a bad choice for web sockets and I should have used Tornado, but this seemed like it would work well and this set up helped me easily separate the REST and web socket pieces
I just use Flask-SocketIO for that.
from gevent import monkey
monkey.patch_all()
from flask import Flask
from flask.ext.socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app)
#app.route('/trigger')
def trigger():
socketio.emit('response',
{'data': 'someone triggered me'},
namespace='/global')
return 'message sent via websocket'
if __name__ == '__main__':
socketio.run(app)