[PYTHON]Email and file connection error - python

I tried to find some topic related, found some, tried some suggested solution, but seems not to work.
I'm trying to figure out where I did it wrong, I'm basically listing a directory and putting the output into a text file that I want to send via smtp to dest address.
#!/usr/bin/python
import os, sys
import smtplib
from email.mime.text import MIMEText
# GRABE LISTED DIRECTORY AND CREATE THE FILE #
#open folder and list it
Winpath = "C:\"
dirs = os.listdir(Winpath)
#Put it into file
fo = open("activitygraber.txt", "w+")
for file in dirs:
fo.write(file + "\n")
# EMAIL IT TO GIVEN ADDRESS #
msg = MIMEText(fo.read())
fo.close()
msg["Subject"] = "Test ActivityGrab"
msg["From"] = "test#test.me"
msg["To"] = "dest#dest.com"
s = smtplib.SMTP("localhost")
s.sendmail("test#test.me", "dest#dest.com", msg.as_string())
s.quit()
That's simple code mostly from Python documentation (I'm in the learning curve).
The file is being created and ready to send I guess, but somehow the connection is not being created. I guess it's because my smtp port in not open ? should I tried to connect to a mail service ? then send it from there ?
Here the message I get when I try to send it:
Traceback (most recent call last):
File "C:\Users\PC\Desktop\testfile.py", line 33, in <module>
s = smtplib.SMTP("localhost")
File "C:\Python27\lib\smtplib.py", line 250, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python27\lib\smtplib.py", line 310, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python27\lib\smtplib.py", line 285, in _get_socket
return socket.create_connection((host, port), timeout)
File "C:\Python27\lib\socket.py", line 571, in create_connection
raise err
socket.error: [Errno 10061] No connection could be made because the target machine actively refused it
Any help of hint would really be appreciated thanks !
Meanwhile I'm gonna continue to search the cause.
Cheers,

s = smtplib.SMTP("localhost") isn't going to work unless you have a running SMTP server on your local machine (which you probably don't...).
If you do, make sure it's listening on port 25.
If you don't, you will have to use a remote SMTP server. You can use google's if you have a gmail account, or find a free one that is set up as a mail relay (that means you can use it anonymously), but these are very rare these days.

Related

Python Smtplib WinError 100022

I'm trying to send an email using Python and I used the material I found on the official site (https://docs.python.org/3/library/email.examples.html) but I'm getting an error when sending an email. Using the port and server works when I use Java but when using the same details in Python the code doesn't work.
The code that I am testing:
import smtplib
from email.message import EmailMessage
port = 25
server = "172.xxx.xxx.xxx"
from_add = "test#fakemail.com"
to_add = "test#fakemail.com"
message = "This is a test Email"
subject = "Test Email"
msg = EmailMessage()
msg.set_content(message)
msg["Subject"] = subject
msg["From"] = from_add
msg["To"] = to_add
#Send the message via our own SMTP server
s = smtplib.SMTP(server)
s.send_message(msg)
s.quit()
When I run my code I get the below error. I have been searching the net and all I am finding are errors concerning sockets (I tried adding which I haven't seen in any examples. My firewall admin tells me he doesn't see any traffic being blocked his end. Does anyone know if what I am coding is wrong?
Original
Traceback (most recent call last):
File "X:/test/test_email.py", line 21, in <module>
s = smtplib.SMTP(server)
File "X:\Enviroments_For_Python\PROD\lib\smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "X:\Enviroments_For_Python\PROD\lib\smtplib.py", line 336, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "X:\Enviroments_For_Python\PROD\lib\smtplib.py", line 307, in _get_socket
self.source_address)
File "X:\Enviroments_For_Python\PROD\lib\socket.py", line 728, in create_connection
raise err
File "X:\Enviroments_For_Python\PROD\lib\socket.py", line 711, in create_connection
sock = socket(af, socktype, proto)
File "X:\Enviroments_For_Python\PROD\lib\socket.py", line 151, in __init__
_socket.socket.__init__(self, family, type, proto, fileno)
OSError: [WinError 10022] An invalid argument was supplied
Process finished with exit code 1
Socket change (didn't work)
s.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sock.bind(server, port)
I found the problem. I am using Anaconda and had created a different environment. When I switched to the root environment my code worked without a problem.

Error to send e-mail using module smtplib

I'm doing a code to send emails automatically using Python and a local server (where I work). I don't know why this error happens.
I've tried to connect the server using commands from module smtplib -> smtplib.SMTP_SSL(hot, port) and smtplib.SMTP(hot,port) but both doesn't work.
import smtplib
server = smtplib.SMTP('IPfromCompanyServer')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\dbou\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "C:\Users\dbou\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 336, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Users\dbou\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 307, in _get_socket
self.source_address)
File "C:\Users\dbou\AppData\Local\Programs\Python\Python37\lib\socket.py", line 727, in create_connection
raise err
File "C:\Users\dbou\AppData\Local\Programs\Python\Python37\lib\socket.py", line 716, in create_connection
sock.connect(sa)
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
Make sure you're getting to Mail server IP and port number right. And some clients like Gmail don't allow you to send mails automatically without disabling the secure mail transfer feature.
Additionally you could add this piece of code to your program before you log in.
try:
self.smtp.ehlo()
self.smtp.starttls()
self.smtp.ehlo
except:
print "No TLS "
#login here
And maybe this link outta help out a little:
https://superuser.com/questions/1292420/sending-an-email-from-python-using-local-python-smtp-server

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.

How to send simple email using Python

Before you mark this as a duplicate; I've read the other threads as well. I'm trying to send an email as simple as using the mail() function in php. I simply tried the example from the official python docs. But when I try to connect with the localhost on my linux machine I get:
>>> import smtplib
>>> smtplib.SMTP('localhost')
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/lib/python2.7/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 311, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py", line 286, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/lib/python2.7/socket.py", line 571, in create_connection
raise err
error: [Errno 111] Connection refused
I thought this example didn't need an email server to run (just like the php mail() function doesn't need an email-server to run).
Any ideas what I might be doing wrong or how I can get this to send an email? All tips are welcome!
The php mail() function does need a relay to send messages. It defaults to sendmail on Linux machines.
On Windows you have to give it the address of a SMTP server.
In order for any program to send email, you need to connect to a SMTP server. There is no running around that.

Network is unreachable if running script on webhosting

The next script runs fine on my mac. When I try to run it on my WebHosting (bluehost) I'm getting socket.error: [Errno 101] Network is unreachable. Any idea how can I fix it?
#!/usr/bin/python
# Required header that tells the browser how to render the text.
print "Content-type: text/html\r\n\r\n";
import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('user#gmail.com', 'password')
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("inbox") # connect to inbox.
print mail.list()
Traceback (most recent call last):
File "test2.py", line 6, in <module>
mail = imaplib.IMAP4_SSL('imap.gmail.com')
File "/home4/user/python27/lib/python2.7/imaplib.py", line 1148, in __init__
IMAP4.__init__(self, host, port)
File "/home4/user/python27/lib/python2.7/imaplib.py", line 163, in __init__
self.open(host, port)
File "/home4/user/python27/lib/python2.7/imaplib.py", line 1159, in open
self.sock = socket.create_connection((host, port))
File "/home4/user/python27/lib/python2.7/socket.py", line 571, in create_connection
raise err
socket.error: [Errno 101] Network is unreachable
Their support isn't helpful at all.
Can it be port related or maybe SSL?
On bluehosts help pages they mention that outgoing connnections are restricted, so ther problem isn't with your program. The only way of getting outbound connections to be allowed seems to pay for it.

Categories

Resources