This question already has answers here:
Configure Flask-Mail to use GMail
(2 answers)
Closed 3 years ago.
when i execute this code it shows ConnectionRefusedError: [WinError 10061] No connection could be made because the
target machine actively refused it
import os
import smtplib
from flask import *
from flask_mail import *
app = Flask(__name__)
mail = Mail(app)
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT']=465
app.config['MAIL_USERNAME'] = os.environ.get('User' )
app.config['MAIL_PASSWORD'] = os.environ.get('Password' )
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = True
#app.route('/')
def index():
msg = Message('HEllo',sender=["joyciimmaculate#gmail.com"], recipients = ["joyciimmaculate#gmail.com"])
msg.body = "hi bulk sms"
msg.html ="<img src="/static/deepa.jpg" style='width:500px;height:228px;'>"
mail.send(msg)
return "mail sent"```
Based on the description of the error, this is not a problem with your Python code, but rather that the network connection to smtp.gmail.com is being blocked/rejected (possibly by a firewall or some other network issue).
Note that if you are running this on a home machine, most ISPs will actively block outbound SMTP connections to anything except the ISP's own SMTP servers (some hosting providers also do the same), to prevent spammers from exploiting the service. You may need to change your settings to use your ISP's outbound mail host instead of connecting directly to smtp.gmail.com.
Related
I tried to configure using localhost. I ran this in my cmd line.
(python -m smtpd -c DebuggingServer -n localhost:1025)
import smtplib, ssl
smtp_server = "localhost"
port = 1025 # For starttls
sender_email = "my outlook email"
password = input("Type your password and press enter: ")
# Create a secure SSL context
context = ssl.create_default_context()
# Try to log in to server and send email
try:
server = smtplib.SMTP(smtp_server,port)
server.ehlo() # Can be omitted
server.starttls(context=context) # Secure the connection
server.ehlo() # Can be omitted
server.login(sender_email, password)
print("server connected")
# TODO: Send email here
except Exception as e:
# Print any error messages to stdout
print(e)
finally:
server.quit()
But it is giving "connection refused" error.
To resolve connection refused error, you can try following ways:
Firewall might be blocking access to port 1025
Alternatively, you can try using port 25
As per documentation:
For Enterprise Dev/Test subscriptions, port 25 is blocked by default. It is possible to have this block removed. To request to have the block removed, go to the Cannot send email (SMTP-Port 25) section of the Diagnose and Solve blade in the Azure Virtual Network resource in the Azure portal and run the diagnostic. This will exempt the qualified enterprise dev/test subscriptions automatically.
You can refer to Send emails from Azure Databricks
import smtplib, ssl
import dns.resolver,socket
smtp_server= 'smtp.gmail.com'
port = 465
sender = 'reddy#gmail.com'
pssword = ''
addressToVerify = 'raghavareddy#smatbot.com'
context = ssl.create_default_context()
domain_name = addressToVerify.split('#')[1]
print('domain_name : '+domain_name)
records = dns.resolver.resolve(domain_name, 'MX')
mxRecord = records[0].exchange
print(mxRecord)
host = socket.gethostname()
print('hosttttttttttt==',host)
try:
server = smtplib.SMTP_SSL(smtp_server,port)
server.ehlo()
#server.starttls(context = context)
server.ehlo()
server.login(sender,pssword)
ss = server.connect(str(mxRecord),465)
#print(ss)
pp = server.verify(addressToVerify)
print(pp)
ss = server.rcpt(addressToVerify)
print(ss)
print('ok')
except Exception as e:
print(e)
I was trying to verify the email address but it was throwing an error while it was not connecting mxrecords
[WinError 10060] A connection attempt failed because the connected party did not properly respond
after a period of time, or established connection failed because connected host has failed to respond
It is not connecting to the MX records.
while verifying at
RCPT (503, b'5.5.1 MAIL first. p2-20020a17090ad30200b001cd4989feb7sm14376983pju.3 - gsmtp')
This 503 error code representing that `The server has encountered a bad sequence of commands, or it requires an authentication.
Suggest a standard way of verifying an email, please.
Suggest a standard way of verifying an email, please.
You can not, without sending an email with a nonce, and waiting for it to be used in some timeframe.
Servers won't let you arbitrarily test the existence of email addresses, otherwise this would be an heaven for spammers.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I want to connect my laptop (and later a raspberry pi/Jetson nano) to a Server. The goal is to be able to send data to the server then process and evaluate it and send the output (GPS coordinates) back to the client (laptop/raspberry pi/Jetson nano).
Ideally, I would just plug in the public IP address of the Google Server into the code that is run on the client and connect to the server.
However, running the server code:
import socket
HOST = '127.0.0.1' # Standard loopback interface address (localhost)
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
and the client code:
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
provided by: https://realpython.com/python-sockets/ .
Will only work with the default local IP address otherwise it returns a IP address couldn't be found error.
EDIT: The answer was more directed towards internet connection via the google cloud API. The solution illustrates this perfectly, however my question was not explicit enough sorry!
There's a large number of ways to do this, but I would recommend using either a GCE instance as your server, or an App Engine deployment. Cloud Run and Cloud Functions also would work. (EDIT: forgot k8s)
Note that when using a GCE instance you will need to open up your firewall as per documentation.
Also note that unless you assign a static IP address to the GCE instance, it will be ephemeral. If you use App Engine, you can just use https://project-id.appspot.com/ as the server address in your client.
You'll need to set up a simple web server using Flask, FastAPI or another webapp framework. It makes life easier to use a simple framework as it will take load of your hands.
You can have your client perform a request with the data it needs to send as parameters and have the web app perform magic and provide a response. I would highly advise to return a JSON response as this is more or less standard for APIs. (which your web app would basically be). Also, as you might know, JSON is easily converted into something useable in python.
See this very simple example below.
server code
from flask import Flask, request
import json
app = Flask(__name__)
longitude_divisor = 0.004167
#app.route("/api/gettimediff")
def gettimediff():
longitude = float(request.args.get("Longitude"))
# http://www.cs4fn.org/mobile/owntimezone.php
seconds = longitude / longitude_divisor
response = json.dumps({"seconds": seconds}, indent=4)
return response
#app.route("/api/switch")
def switch():
longitude = float(request.args.get("Longitude"))
latitude = float(request.args.get("Latitude"))
response = json.dumps({"Latitude": longitude, "Longitude": latitude})
return response
if __name__ == "__main__":
# This is used when running locally only. When deploying to Google App
# Engine, a webserver process such as Gunicorn will serve the app. This
# can be configured by adding an `entrypoint` to app.yaml.
# Flask's development server will automatically serve static files in
# the "static" directory. See:
# http://flask.pocoo.org/docs/1.0/quickstart/#static-files. Once deployed,
# App Engine itself will serve those files as configured in app.yaml.
app.run(host="127.0.0.1", port=8080, debug=True)
client code
import requests
import json
serveraddress = "http://127.0.0.1:8080/"
data = {"Latitude": 48.85837, "Longitude": 2.294481}
print("switch")
response = requests.get(
f"{serveraddress}api/switch",
params=data
)
print(data)
print(response.text)
print("seconds")
response = requests.get(
f"{serveraddress}api/gettimediff",
params=data
)
print(data)
print(response.text)
converted = json.loads(response.text)
print(converted)
from flask import Flask
from flask_mail import Mail, Message
import os
app = Flask(__name__)
mail_settings = {
"MAIL_SERVER": 'mail.hi.in',
"MAIL_PORT": 465,
"MAIL_USE_TLS": False,
"MAIL_USE_SSL": True,
"MAIL_USERNAME": abcde,
"MAIL_PASSWORD": password
}
app.config.update(mail_settings)
mail = Mail(app)
if __name__ == '__main__':
with app.app_context():
msg = Message(subject="Hello",
sender=app.config.get("support#hi.in"),
recipients=["dfjhnk#gmail.com"],
body="This is a test email I sent with Gmail and Python!")
mail.send(msg)
Error Saying:
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
This is a test email I sent with Gmail and Python!
I see that you use Gmail, so if you don't have enabled "Less secure apps on your google account" go here
as indicated by the title I am having trouble sending an email via my gmail account through a python application.I have searched online for a solution but nothing seems to solve it and I thought I might ask here.
My code is the following:
FROMADDR = "myemail#gmail.com"
LOGIN = FROMADDR
PASSWORD = "mypass"
TOADDRS = "varis81#hotmail.com"
msg = "Test message"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(LOGIN, PASSWORD)
server.sendmail(FROMADDR, TOADDRS, msg)
server.quit()
print "E-mail succesfully sent"
I get the message:
socket.error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I tried different ports but it doesn't work also.I also tried hotmail but it causes the same problem.I am using Python 2.7 (don't ask :) ) on a Windows 7 machine developing on Eclipse using PyDev.
Any help would be great!
Thank you in advance.
I'm using the same construct on one of my servers. My code is below.
The only difference is the extra .ehlo() after '.starttls()`. This should not be the issue; from the RFC:
5.2 Result of the STARTTLS Command
The client SHOULD send an EHLO command as the first
command after a successful TLS negotiation.
According to the RFC, the server should not sever a connection if the client does not send ehlo after starttls, but Google could be more restrictive on their SMTP server. I'd check that first. (I've seen providers tighten down on these kinds of conditions to reduce spam, see Mailinator's 2007 writeup for instance.)
It could also be filtered ports - try running the code in the REPL and confirm which line is exceptioning, if it's the connect() you'll know it's network. If it's after, it's likely your usage of smtplib.
Of note, I also experienced occasional unclean shutdowns, resulting in the try/except around .close().
import smtplib
s = smtplib.SMTP()
s.connect("smtp.gmail.com")
s.ehlo()
s.starttls()
s.ehlo()
s.login("from#gmail.com", "frompass")
s.sendmail("fromname#gmail.com", toAddr, bytes)
try:
s.close()
except: pass
Well, since I cant post comments yet I'll have to attempt an answer..
Judging by this: Python SMTP Errno 10060
Perhaps a timeout would help?