How to send simple email using Python - 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.

Related

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

python- error sending an email

I am able to send from one gmail account to another gmail account and from one outlook account to another outlook account.
But I am facing problem when I am trying to send mail from outlook to gmail.
Here is the code
import smtplib
content ='example email stuff here'
email='xyz#outlook.com'
password="password"
fromemail="xyz#outlook.com"
receive="abc#gmail.com"
mail=smtplib.SMTP('smtp-mail.outlook.com',587)
mail.ehlo()
mail.starttls()
mail.login(email,password)
mail.sendmail(fromemail,receive,content)
mail.close()
When I am running the script I am getting the following error
Traceback (most recent call last):
File "smtp_google.py", line 7, in <module>
mail=smtplib.SMTP('smtp-mail.outlook.com',587)
File "C:\Python27\lib\smtplib.py", line 256, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python27\lib\smtplib.py", line 316, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python27\lib\smtplib.py", line 291, in _get_socket
return socket.create_connection((host, port), timeout)
File "C:\Python27\lib\socket.py", line 575, in create_connection
raise err
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
Solution 1:
Try by giving timeout in:
mail=smtplib.SMTP('smtp-mail.outlook.com',587)
as
mail=smtplib.SMTP('smtp-mail.outlook.com',587, timeout=120)
or try connecting via SSL instead of TLS/STARTTLS
mail=smtplib.SMTP_SSL('smtp-mail.outlook.com',587)
solution 2:
Your email account must allow smtp, which is not necessarily enabled by default. You can try to change the settings by following the steps given here enable smtp authentication

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.

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.

sending email via django send_mail

I have been using django send_mail for a long while. however on a new project which use django 1.4 and I changed my dev machine I have a very strange problem.
when I call send_mail on the standard backend with all the settings (EMAIL_HOST='localhost' EMAIL_PORT=25,etc) I am getting the error :
File "c:\python27\lib\site-packages\django\core\mail\backends\smtp.py", line 4
8, in open local_hostname=DNS_NAME.get_fqdn())
File "c:\python27\lib\smtplib.py", line 249, in __init__
(code, msg) = self.connect(host, port)
File "c:\python27\lib\smtplib.py", line 309, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "c:\python27\lib\smtplib.py", line 284, in _get_socket
return socket.create_connection((port, host), timeout)
File "c:\python27\lib\socket.py", line 571, in create_connection
raise err
socket.error: [Errno 10013] An attempt was made to access a socket in a way forb
idden by its access permissions
I have no clue what I am doing wrong, I have debugged it and it seems that the connect function recieve the right port and host however its getting forbidden. I suspected its maybe my antivirus but disabling it didnt help.
I am running on administrator privilages (UAC disabled) if anyone consider this to be the problem.
Strange. I changed my email server (python SMTPd) to port 1025 instead of 25 and everything back to normal....

Categories

Resources