I have tried to attached a file to the mail using python.
Code:
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from smtplib import SMTPException
def send_Email():
file1="abc.txt"
message = "Test mail"
msg = MIMEMultipart()
msg.attach(MIMEText(file(file1).read()))
try:
smtpObj = smtplib.SMTP('smtp server name',port)
smtpObj.sendmail(sender, EmailId, message, msg.as_string() )
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Bt I have get the error: socket.gaierror: [Errno 11001] getaddrinfo failed
full error message:
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 553, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno 11001] getaddrinfo failed
I know for sure that gaierror comes up when you are working from behind proxy.
The problem is that the DNS lookup for 'smtp server name' is failing - if this is your exact code then you can see why - if not and you have the valid qualified name for the SMTP server then you may have issues with the firewall/internet connection, etc., also port has to be set to a valid value to match your servers SMTP configuration, (usually port 25 but not absolutely always).
The below answer may be quite irrelevant to the question. But,some users may have a different scenario.
If a server can be reached only through VPN and if we try to reach it with VPN disconnected, this error : "gaierror: [Errno 11001] getaddrinfo failed" crops up.
Connect to VPN and then executing the code should work good.
In my case was a host problem. Using debug mode, I spotted that in (host, port, 0, SOCK_STREAM) I got host=local and it should be host=localhost.
In the run.py I defined localhost and the file hosts (c:\windows\system32\drivers\etc\hosts) was defined local.
They have to be equal, otherwise you get the socket.gaieeror.
There seems to be a bug in urllib3 version 1.25.9 package. This produced "socket.gaierror: [Errno 11001] getaddrinfo failed" error for me (working from behind an authenticated proxy server).
Downgrading to urllib3 version 1.25.8 solved the problem.
you might did a little mistake in settings.py file..
check your code one more time in your settings file
settings.py:
EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'your_email'
EMAIL_HOST_PASSWORD = 'your_password'
EMAIL_PORT = 587
EMAIL_USE_TLS=True
I got this error when I tried using flask-mail
I just had to resend the message and it worked perfectly well.
I don't know why I got the error the first time perhaps it might be a bug in the library...
You need to login using your credential. Try:
smtpObj = smtplib.SMTP('smtp server name',port)
smtpObj .starttls()
smtpObj .login(email, password)
smtpObj.sendmail(sender, EmailId, message, msg.as_string() )
print "Successfully sent email"
I prefer u guys to run the file as administrator for eg
open cmd as administrator then
type
cd C:\into ur .py file path
and then type
python filename.py
it worked for me.
good luck
You need to activate IMAP/SMTP service active for your host mail.
Related
import smtplib
my_email = "*******#gmail.com"
password = "***********"
with smtplib.SMTP("smtp.gmail.com") as connection:
connection.starttls()
connection.login(user=my_email, password=password)
connection.sendmail(from_addr=my_email, to_addrs="*******#yahoo.com",
msg="Subject:Hello\n\n This is the body of my email.")
In gmail the "less secure apps" feature was enabled. Conversely, in Yahoo, the "Generate App Password" feature was used and still got the same response for both instances.
There can be many reasons for this error - typically it means something has gone wrong in setting up the smtplib connection and your email hasn't set.
To get a more descriptive and helpful error message, you need to enable debugging.
To do that add, add this line of code:
connection.set_debuglevel(1)
That will print out much more descriptive debugger messages to the console.
try to set a port like 465 for gmail, smptlib.SMTP("smtp.gmail.com", 465)
if none of that work try to change your transfer security from starttls() to SMTP_SSL, so your code look like this:
import smtplib, ssl #import ssl module
port = 465 # For SSL
# Create a secure SSL context
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
server.login(my_email, password)
server.sendmail(from_addr=my_email, to_addrs=reciver_email, msg=message)
A program I wanted to create requires to login to a mail server.
I was able to login using smtplib on Gmail, but it didn't work on Yahoo mail.
SMTP Port 465
Server mail: smtp.mail.yahoo.co.jp
python code on IDLE
import smtplib
smtp_obg = smtplib.SMTP("smtp.mail.yahoo.co.jp", 465)
Error message
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
smtp_obg = smtplib.SMTP("smtp.mail.yahoo.co.jp", 465)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/smtplib.py", line 253, in __init__
(code, msg) = self.connect(host, port)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/smtplib.py", line 341, in connect
(code, msg) = self.getreply()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/smtplib.py", line 398, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
I would appreciate if someone could help. Thank you in advance.
You must run login after creating smtp_obj (smtp_obg.login('username', 'password')). If you trying to login, please mention it.
You must activate SMTP feature at Yahoo's web page (Same as Gmail). Sorry for Japanese, but not sure if yahoo.co.jp is using somewhere outside Japan. :)
In English, this parameter should be called like: IMAP/POP/SMTP access and mail transfer
I checked my account. STMP access is disabled by default.
When you create a connection to your smtp server you need to know more about the server about what way you want to connect to it.
There are normal with and without SSL connection based on port number to your SMTP server.
I use this site https://settings.email/yahoo-co-jp-email-settings/ to get more info about your SMTP server you want to use from yahoo and it says the port 465 is an SSL connection so you need to connect with SSL connection else you can't sending out this way.
in smtplib in python you have smtplib.SMTP and smtplib.SMTP_SSL functions to work with, the first it's used when it's not SSL requirement, and the second its used when you need SSL like yahoo smtp.
Can you try out to use smtplib.SMTP_SSL function and see about its working for you?
import smtplib
smtp_obg = smtplib.SMTP_SSL("smtp.mail.yahoo.co.jp", 465)
Mabey its required a username and password to sending out, I did not have so much info about yahoo SMTP to can explain that part for you.
I recently registered a domain on bluehost.com. For now, I want to send simple 'reset password' emails. Using the "Standard (without SSL/TLS) Settings" works fine.
However, the bluehost documentation suggests using Secure SSL/TLS Settings, so I want to give that a try:
Username: Your email address: john#example.com
Password: The password for that email account.
Outgoing Server: mail.example.com
Outgoing Port: 465 (SMTP)
Here is my code (anonymized parameters):
import smtplib, ssl, os
# Params
port = 465
smtp_server = "mail.mydomain.com"
sender_email = "sender#mydomain.com"
receiver_email = "receiver#gmail.com"
password = os.environ.get("SMTP_PASSWORD")
# As documented in https://docs.python.org/3/library/smtplib.html
""" Deprecated since version 3.6: keyfile and certfile are deprecated
in favor of context. Please use ssl.SSLContext.load_cert_chain() instead,
or let ssl.create_default_context() select the system’s trusted
CA certificates for you. """
context = ssl.create_default_context()
# Create the connection and authenticate
with smtplib.SMTP_SSL(smtp_server, port, context=context) as s:
s.set_debuglevel(1)
s.login(sender_email, password)
s.quit()
The code fails on:
...Python37-32\lib\ssl.py", line 1117, in do_handshake
self._sslobj.do_handshake()
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
I contacted bluehost tech support, who clarified no certificates were missing or anything. Their answer was unsatisfying in the sense that they just said "SSL sometimes doesn't work. Reset your password and try again" (the latter didn't work).
I'm hoping I'm simply overlooking a mistake in my code. Can someone point me in the right direction? I've run out of Google.
So I have tried at least 5-10 examples online to send an email, but I keep getting the same error.
Traceback (most recent call last):
File "C:/Users/alxu/Project/LogFilter.py", line 88, in ?
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
File "C:\Python24\lib\smtplib.py", line 244, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python24\lib\smtplib.py", line 292, in connect
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
socket.gaierror: (11004, 'getaddrinfo failed')
The last example I used code was like this...
import smtplib
to = 'mkyong2002#yahoo.com'
gmail_user = 'mkyong2002#gmail.com'
gmail_pwd = 'yourpassword'
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:testing \n'
print header
msg = header + '\n this is test msg from mkyong.com \n\n'
smtpserver.sendmail(gmail_user, to, msg)
print 'done!'
smtpserver.close()
I am using Python 2.4.3.
EDIT: McAfee is has host intrusion prevention so all the times I attempted to do this it blocked it.
Since you are behind a corporate proxy, you can't directly connect to any outside server, you need to connect through the proxy. In this case, you're trying to connect to a SMTP server, which uses port 25 or 587. I assume you're behind a HTTP proxy that doesn't block SMTP ports. If your corporate proxy blocks these ports, then there's nothing you can do to connect to the server.
The smtplib module doesn't include the functionality to connect to a SMTP server through a proxy. As a workaround, I wrote the custom class ProxySMTP, which I have posted here along with instructions on how to use it.
Let me know if it works for you.
Your last example code should work. One thing you need to do is to make sure you allow access to less secure apps by going to the following link.
google settings for secure apps
The reason for this is google flags such automated email scripts as less secure. You should also be aware of the risks. Make sure you change this setting back if you are not gonna need it.
I encountered an error today while trying to retrieve an XML by sending a 'GET' HTTP request.
from httplib import HTTPConnection
import urllib
params = urllib.urlencode({'sK': 'test', 'sXML': 1})
httpCon = HTTPConnection("http://www.podnapisi.net",80)
httpCon.request('GET', '/en/ppodnapisi/search',params)
r1 = httpCon.getresponse()
and here is the error i got:
.....
File "C:\Python27\lib\socket.py", line 553, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno 11004] getaddrinfo failed
The XML that I am trying to retrieve HERE
How can I fix this error ?
Thanks in Advance ...
No scheme (http://) in the HTTPConnection constructor:
httpCon = HTTPConnection("www.podnapisi.net",80)
It already knows it's HTTP, it's an HTTPConnection object :)
You accidentally included the protocol prefix in the domain argument to HTTPConnection. You want:
httpCon = HTTPConnection("www.podnapisi.net", 80)
Generally, This error indicates there was a problem resolving the domain name to an IP address. In It might be just intermittent. If the problem persists, check the DNS configuration on your system.
For example, you can set it to use Google's public DNS server. For more information about how to configure your DNS server on Microsoft Windows, refer to Microsoft's knowledge database.