Can't send E-Mails with Python - python

I have this code as I am trying to send E-Mails using Python.
def Mail():
import smtplib
import textwrap
SERVER = "localhost"
FROM = "fromemail"
TO = ["toemail"]
SUBJECT =(input('What is the subject of your E-Mail'))
TEXT =(input('What do you want the E-Mail to say?'))
message = textwrap.dedent("""\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT))
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
This is the error message I get.
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
Mail()
File "E:\Coursework\EMail.py", line 26, in Mail
server = smtplib.SMTP(SERVER)
File "C:\Python33\python-3.3.5\lib\smtplib.py", line 241, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python33\python-3.3.5\lib\smtplib.py", line 322, in connect
(code, msg) = self.getreply()
File "C:\Python33\python-3.3.5\lib\smtplib.py", line 375, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

The 'Connection unexpectedly closed' shows that the server is probably ON but unable to create a connection to smtplib.
You could check the status of the port 25 smtp service to verify that,
# netstat -an | grep -i :25
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN
Then, check the status of the service occupying the port 25,
# netstat -plnt | grep -i :25
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 30860/master
You probably will have the same,
then just check the status of the master/postfix process,
# systemctl status postfix
If you get the error highlighted as,
fatal: cannot handle socket type AF_INET6 with "inet_protocols = ipv4"
then quickly go to the postfix configuration file at /etc/postfix/main.cf and check if you have this text and uncomment it,
inet_protocols = ipv4
Then restart postfix,
# systemctl restart postfix
then check status, hopefully you shouldn't get any errors.
Then check if python is able to connect to the SMTP server!
$ python -c 'import smtplib; smtplib.SMTP("localhost");'
You shouldn't get any output which shows that python is able to connect to the SMTP server.
you can run your email sending script now!

Related

Connection to test SFTP server on 0.0.0.0

I am trying to connect and upload / download a text file via Python, but I am getting this error:
Traceback (most recent call last):
File "C:\Users\Abdul\OneDrive\Desktop\SFTP neu\main3.py", line 8, in <module>
c.connect(hostname = "0.0.0.0",port = 22, username = "tester", pkey = k)
File "D:\Python\lib\site-packages\paramiko\client.py", line 349, in connect
retry_on_signal(lambda: sock.connect(addr))
File "D:\Python\lib\site-packages\paramiko\util.py", line 283, in retry_on_signal
return function()
File "D:\Python\lib\site-packages\paramiko\client.py", line 349, in <lambda>
retry_on_signal(lambda: sock.connect(addr))
OSError: [WinError 10049] Die angeforderte Adresse ist in diesem Kontext ungültig
I'm using Rebex TinySFTP Server.
At first I thought my host was wrong, but that wasn't it.
In this example I used 0.0.0.0.
Here is my code:
#!/usr/bin/python3
import paramiko
k = paramiko.RSAKey.from_private_key_file("C:\\Users\\Abdul\\OneDrive\\Desktop\\RebexServer\\private-rsa-key.pem")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print("connecting")
c.connect(hostname = "0.0.0.0",port = 22, username = "tester", pkey = k)
print("connected")
commands = ["C:\\Users\\Abdul\\OneDrive\\Desktop\\RebexServer\\data\\testfile.txt", "C:\\Users\\Abdul\\OneDrive\\Desktop\\SFTP neu\\data\\testfile1.txt"]
for command in commands:
print("Executing {0}".format( command ))
stdin , stdout, stderr = c.exec_command(command)
print(stdout.read())
print("Errors")
print(stderr.read())
c.close()
At first I thought my host was wrong, but that wasn't it. In this example I used 0.0.0.0
0.0.0.0 is often used when starting a server to indicate that the server should bind to all available IP addresses. But it's not what you should use in your client.
Use one of the actual IP addresses your server is binding to. If both are on the same machine, try 127.0.0.1 or whatever IP address you are using locally. Addresses starting with 192.168. are common in home and small office networks.

Getting SMTPServerDisconnected error sending email through python

When trying to send the email with the host:cpanel.freehosting.com
P it is raising an error like
This is my code:
import smtplib
s = smtplib.SMTP('cpanel.freehosting.com', 465)
s.starttls()
s.login("myusername", "mypassword")
message = "Message_you_need_to_send"
s.sendmail("myemailid", "receiver_email_id", message)
s.quit()
This is the error i got:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python3.5/smtplib.py", line 337, in connect
(code, msg) = self.getreply()
File "/usr/lib/python3.5/smtplib.py", line 393, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
Considering the port number you are using I'd try with SMTP_SSL instead of SMTP and starttls().
https://docs.python.org/3/library/smtplib.html:
An SMTP_SSL instance behaves exactly the same as instances of SMTP.
SMTP_SSL should be used for situations where SSL is required from the
beginning of the connection and using starttls() is not appropriate.
If host is not specified, the local host is used. If port is zero, the
standard SMTP-over-SSL port (465) is used.
STARTTLS is a form of opportunistic TLS, it is supposed to be used with old protocols, that originally did't support TLS, to upgrade the connection.
The port 465 was used before the introduction of STARTTLS for SMTPS, which is now deprecated.
import smtplib
s = smtplib.SMTP_SSL('cpanel.freehosting.com', 465)
s.login("myusername", "mypassword")
message = "Message_you_need_to_send"
s.sendmail("myemailid", "receiver_email_id", message)
s.quit()
Alternatively you should be able to use port 25 with your original code.
import smtplib
s = smtplib.SMTP('cpanel.freehosting.com', 25)
s.starttls()
s.login("myusername", "mypassword")
message = "Message_you_need_to_send"
s.sendmail("myemailid", "receiver_email_id", message)
s.quit()
In both examples you can completely omit the port number as you are using the default ports.

websocket-client: failed CONNECT via proxy status: 503

I'm testing basic code, and it is working, as it should
import websocket
ws = websocket.WebSocket()
ws.connect("wss://echo.websocket.org/")
send_string = "Testing WebSocket"
print "Sending: ",send_string
ws.send(send_string)
result = ws.recv()
print "Received: ",result
ws.close()
But after changing websocket address to my desire "wss://10.240.118.148:51443/ws/" I have:
Traceback (most recent call last):
File "testws.py", line 5, in <module>
ws.connect("wss://10.240.118.148:51443/ws/")
File "/usr/lib/python2.7/site-packages/websocket/_core.py", line 213, in connect
options.pop('socket', None))
File "/usr/lib/python2.7/site-packages/websocket/_http.py", line 72, in connect
sock = _tunnel(sock, hostname, port, auth)
File "/usr/lib/python2.7/site-packages/websocket/_http.py", line 224, in _tunnel
"failed CONNECT via proxy status: %r" % status)
websocket._exceptions.WebSocketProxyException: failed CONNECT via proxy status: 503
Of course connection to websocket is working:
wscat -n -c wss://10.240.118.148:51443/ws/
connected (press CTRL+C to quit)
> test
< {"error":{"code":-32700,"data":"parse error - unexpected 't'","message":"Parse error"},"id":null,"jsonrpc":"2.0"}
Do you have any idea what can be wrong ?
"failed CONNECT via proxy status: 503 is" really is a server error and not a Proxy error, you would have to consult your server's error log files to find out the reason for the problem.

Send email from server python

I am trying to send an email form my server with python, I asked my server provider what port to use for this and they said "choose SMTP Ports 465 (Secure SSL/TLS outgoing server) , 25 ( Non-SSL outgoing server)." Not sure what this exactly means but currently I am using 25, here is my code
#! /usr/bin/python
import smtplib
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 25)
#Next, log in to the server
server.login("youremailusername", "password")
#Send the mail
msg = "\nHello!" # The /n separates the message from the headers
server.sendmail("you#gmail.com", "target#example.com", msg)
I filled in my username (which is my email address right) and password,a dn the target but it is not working, when I try to navigate to the url where my py script is, it just doesn't load. I have an internet connection cause I am loving other things, and go to other pages on my server. I have also tried running with cron jobs but that also doesn't work.
The permissions on the script are 0755, is there a problem with the script?
When i ran with cron jobs here is the traceback
Traceback (most recent call last):
File "/home/spencerf/public_html/cgi-bin/send_email.py", line 6, in <module>
server = smtplib.SMTP('smtp.gmail.com', 25)
File "/usr/lib64/python2.6/smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib64/python2.6/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib64/python2.6/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/usr/lib64/python2.6/socket.py", line 567, in create_connection
raise error, msg
socket.error: [Errno 101] Network is unreachable
Thanks for the help in advance.
EDIT
here is updated error log with the port at 587
Traceback (most recent call last):
File "/home/spencerf/public_html/cgi-bin/send_email.py", line 7, in <module>
server = smtplib.SMTP('smtp.gmail.com', 587)
File "/usr/lib64/python2.6/smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib64/python2.6/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib64/python2.6/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/usr/lib64/python2.6/socket.py", line 567, in create_connection
raise error, msg
socket.error: [Errno 101] Network is unreachable
EDIT 2
When I had server = smtplib.SMTP('telnet smtp.gmail.com', 587)
I got this error
Traceback (most recent call last):
File "/home/spencerf/public_html/cgi-bin/send_email.py", line 8, in <module>
server = smtplib.SMTP('telnet smtp.gmail.com', 587)
File "/usr/lib64/python2.6/smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib64/python2.6/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib64/python2.6/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/usr/lib64/python2.6/socket.py", line 553, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known
BUG:
First of all you are using gmail server not your company server to send mail .For gmail server the output port is 587
The code:
Due to security issues gmail blocks accessing mail via code or program
But still you can use gmail to send mail via code if you do the following things
What i have done in code :
1.Added a error object to get the error message
import smtplib
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
#Next, log in to the server
server.login("youremailusername", "password")
#Send the mail
msg = "\nHello!" # The /n separates the message from the headers
server.sendmail("you#gmail.com", "target#example.com", msg)
print "Successfully sent email"
except smtplib.SMTPException,error:
print str(error)
print "Error: unable to send email"
If u ran this code u would see a error message like this stating that google is not allowing u to login via code
Things to change in gmail:
1.Login to gmail
2.Go to this link https://www.google.com/settings/security/lesssecureapps
3.Click enable then retry the code
Hopes it help :)
But there are security threats if u enable it
Updated
import smtplib
try:
content = 'test'
mail = smtplib.SMTP('smtp.gmail.com',587)
mail.ehlo()
mail.starttls()
mail.login("ABC#gmail.com", "password")
mail.sendmail("ABC#gmail.com", "recivermailaddress", content)
mail.quit
print "Successfully sent email"
except smtplib.SMTPException,error:
print str(error)
In python, please download yagmail (disclaimer: I'm the developer):
pip install yagmail
It is then simply a matter of:
import yagmail
yag = yagmail.SMTP("you#gmail.com", "password")
yag.send("target#example.com", 'This is the subject', 'Hello!')
I guess it mostly just has to do with the fact that you gave a wrong port (smtp.gmail.com is not at 25).
On the github you can also see a common list of errors.

Emailing smtp with Python error

I can't figure out why this isn't working. I'm trying to send an email from my school email address with this code I got online. The same code works for sending from my GMail address. Does anyone know what this error means? The error occurs after waiting for about one and a half minutes.
import smtplib
FROMADDR = "FROM_EMAIL"
LOGIN = "USERNAME"
PASSWORD = "PASSWORD"
TOADDRS = ["TO_EMAIL"]
SUBJECT = "Test"
msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n"
% (FROMADDR, ", ".join(TOADDRS), SUBJECT) )
msg += "some text\r\n"
server = smtplib.SMTP('OUTGOING_SMTP', 465)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(LOGIN, PASSWORD)
server.sendmail(FROMADDR, TOADDRS, msg)
server.quit()
And here's the error I get:
Traceback (most recent call last):
File "emailer.py", line 13, in
server = smtplib.SMTP('OUTGOING_SMTP', 465)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 239, in init
(code, msg) = self.connect(host, port)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/socket.py", line 514, in create_connection
raise error, msg
socket.error: [Errno 60] Operation timed out
It's likely that your school's SMTP server does not permit outside access to port 587. Gmail does, and requires authentication to ensure that you are who you say you are (and so that spammers can't send email appearing to be from you unless they know your password). Your school may have chosen to set up their mail server so that only connections from within the school can send mail in this way.

Categories

Resources