send email with email module in python - python

when I try to send an email with email module I get error
I tried with 3 different mail provider
and it is my code :
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
message = MIMEMultipart()
message["from"] = "Amir Mohammad Fallah"
message["to"] = "*******#gmail.com"
message["subject"] = "python test message"
message.attach(MIMEText("body"))
password = "*******"
user = "*********#gmail.com"
with smtplib.SMTP("smtp.gmail.com", 465) as smtp: # port 587 for icloud and 25 for aol
smtp.ehlo()
smtp.login(user, password)
smtp.send_message(message)
print("it's Done !")
and I after while I got this errors :
Traceback (most recent call last):
File "/Users/mgxc2/PycharmProjects/Advance/Python.py", line 588, in <module>
with smtplib.SMTP("smtp.gmail.com", 465) as smtp: # port 587 for icloud and 25 for aol #mail.cortatech.ir port 587
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 338, in connect
(code, msg) = self.getreply()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 394, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

First and foremost I think you should change with smtplib.SMTP("smtp.gmail.com", 465) to with smtplib.SMTP("smtp.gmail.com", 587) and see what happens... Secondly, you should change your Internet connection, because your code looks okay to me.. but I'll check it soon to know the cause, but first try the corrections I sent across

You should use port 587 because it's the default mail submission port.
Here is an articles that explain witch SMTP port to use for witch action.

Related

How to reslove "socket.gaierror" error of python-smtplib?

Few hours back I have posted a post related to "Django email sending API" and its error. So I thought that first I should try something with "smtplib". Unfortunately, after struggling with "smtplib", I realise that it will also not work, because something is wrong with my code or my network or my machine which I am not able to figure out.
Can any body help me regarding to this?
As of now, after struggling a lot, I have tried hundreds of solution posted here and there and also I have tried to resolve with myself but nothing is working in my case kindly help.
Code is given bellow.
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import socks
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, "172.16.0.2", '8084')
socks.wrapmodule(smtplib)
#smtp = smtplib.SMTP()
msg = MIMEMultipart()
msg['From'] = 'my#yahoo.com'
msg['To'] = 'example#gmail.com'
msg['Subject'] = 'simple email in python'
message = 'here is the email'
msg.attach(MIMEText(message))
mailserver = smtplib.SMTP('smtp.mail.yahoo.com',465)
# identify ourselves to smtp gmail client
mailserver.ehlo()
# secure our email with tls encryption
mailserver.starttls()
# re-identify ourselves as an encrypted connection
mailserver.ehlo()
mailserver.login('my#yahoo.com', 'pswd12345678')
mailserver.sendmail('my#yahoo.com','example#gmail.com',msg.as_string())
mailserver.quit()
This is the error coming again and again:
Traceback (most recent call last):
File "import_mail.py", line 21, in <module>
mailserver = smtplib.SMTP('smtp.mail.yahoo.com',465)
File "/usr/lib/python2.7/smtplib.py", line 256, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 316, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py", line 291, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/lib/python2.7/socket.py", line 557, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -3] Temporary failure in name resolution
This error is raised as the 'EMAIL_BACKEND' definition is missing from the settings file. Make sure that the settings.py file contains the following line:-
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
IF you`re using the gmail account to set up a default interactive mail, use the following values:-
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587 #PORT NO
EMAIL_HOST_USER = #e-MAIL ID
EMAIL_HOST_PASSWORD = #PASSWORD
My system had not a DNS configured and I resolved this issue configuring a google DNS or an openDNS.

Python Mailing timed out error

I cannot send an email from python. Probably there is a security issue. Can somebody give me a hint?
This is the code:
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
#Next, log in to the server
server.login("***#gmail.com", "PASSWORD")
#Send the mail
msg = "Hello!"
# The /n separates the message from the headers
server.sendmail("***#gmail.com", "***#gmail.com", msg)
server.quit()
This is the error I get:
server = smtplib.SMTP('smtp.gmail.com', 587)
File "D:\Tools\Lib\smtplib.py", line 244, in __init__
(code, msg) = self.connect(host, port)
File "D:\Tools\Lib\smtplib.py", line 310, in connect
raise socket.error, msg
error: (10060, 'Operation timed out')
you should use smtplib.SMTP_SSL() because port 587 expects ssl(tls) from the get go.
https://docs.python.org/2/library/smtplib.html#smtplib.SMTP_SSL
check with gmail sometimes gmail blocks the signing from apps

Unable to send email using gmail server using python

I am trying to send email using python. I tried many solution on Stackoverflow but none worked.
my code is -
import smtplib
fromaddr = 'user_me#gmail.com'
toaddrs = 'user_you#gmail.com'
msg = 'msg text here'
username = 'user_me#gmail.com'
password = 'pwd'
server = smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
Code remain stuck at line server = smtplib.SMTP('smtp.gmail.com',587)
Tried port 465 and get this error -
Traceback (most recent call last):
File "gmail-python.py", line 130, in <module>
mainFunction()
File "gmail-python.py", line 101, in mainFunction
mail = smtplib.SMTP('smtp.gmail.com', 465)
File "/usr/lib/python2.7/smtplib.py", line 256, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 317, in connect
(code, msg) = self.getreply()
File "/usr/lib/python2.7/smtplib.py", line 368, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
tried this - smtplib.SMTP_SSL('smtp.gmail.com',465) and got this error
raise SMTPException("STARTTLS extension not supported by server.")
smtplib.SMTPException: STARTTLS extension not supported by server.
removing server.ehlo() had no effect.
removing server.starttls() caused below error -
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (534, '5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbsV\n5.7.14 3GHIcJvaksu56NrYm76aC0MqGI_sFI2cNaKSoFX6CV7TlyW593zn4dnJN7mG4TGI7edfcj\n5.7.14 l-MOV1Sb0Joyewnax8dxiL5BQ28Gg3UsWDfibI5TZ-tEaqqpL4WEzX5hsqYg6ZIQlczjyq\n5.7.14 UbElUx1C2E0QBt-X3uCuueb06uPBqehnwNV-hOlYFCgZpxRR9fdi-rO65oD5c1asYyGaTh\n5.7.14 1VRKgMYJp-o_uMhMjGEyJWKLLYX3A> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 r85sm13251579pfr.48 - gsmtp')
I have enabled less secure app access in my account. Python version 2.7.6 on ubuntu.
Try after turning of Gmail's Security Feature Here.
This may be preventing 3rd party application from accessing Gmail for security purpose
https://www.google.com/settings/security/lesssecureapps

smtplib error: Name or Service unknown

I'm trying to use the following script to send an email behind a proxy server.
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import sys
import urllib2
fromaddr = "abc#gmail.com"
toaddr = "xyz#gmail.com"
cc = "123#gmail.com"
toaddrs = toaddr + cc
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "subject"
body = "body"
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login("user", "pass")
text = msg.as_string()
server.sendmail(fromaddr, toaddrs, text)
server.close()
It gives the following error:
Traceback (most recent call last):
File "script.py", line 18, in <module>
server = smtplib.SMTP('smtp.gmail.com:587')
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 553, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known
I have already set the http_proxy environment variable and fetching webpages using urllib2 in python works but not smtplib. Any help will be appreciated.
That should work:
In [1]: import smtplib
In [2]: server = smtplib.SMTP('smtp.gmail.com:587')
In [3]: server
Out[3]: <smtplib.SMTP at 0x7f80fbaa0ba8>
In [4]: server.ehlo()
Out[4]:
(250,
b'mx.google.com at your service, [46.237.207.180]\nSIZE 35882577\n8BITMIME\nSTARTTLS\nAUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN\nENHANCEDSTATUSCODES\nCHUNKING\nSMTPUTF8')
In [5]: server.starttls()
Out[5]: (220, b'2.0.0 Ready to start TLS')
Make sure your network allows connections to port 587 at this host.

Do I need to add specific information to send mail through python?

I am using the following code below:
import smtplib
import zipfile
import tempfile
from email import encoders
from email.message import Message
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
#...
def send_file_zipped(the_file, recipients, sender='email#email.com'):
myzip = open('file.zip', 'rb')
# Create the message
themsg = MIMEMultipart()
themsg['Subject'] = 'File %s' % the_file
themsg['To'] = ', '.join(recipients)
themsg['From'] = sender
themsg.preamble = 'I am not using a MIME-aware mail reader.\n'
msg = MIMEBase('application', 'zip')
msg.set_payload(myzip.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'attachment', filename=the_file + '.zip')
themsg.attach(msg)
themsg = themsg.as_string()
# send the message
smtp = smtplib.SMTP("smtp.gmail.com", "587")
smtp.connect()
smtp.sendmail(sender, recipients, themsg)
smtp.close()
#running this
send_file_zipped('file.zip', 'email#email.edu')
I have tried different variations to try and make it connect successfully here, but I am at a loss here. The error I am getting is this:
Traceback (most recent call last):
File "/Users/Zeroe/Documents/python_hw/cgi-bin/zip_it.py", line 99, in <module>
send_file_zipped('file.zip', 'email#email.com')
File "/Users/Zeroe/Documents/python_hw/cgi-bin/zip_it.py", line 40, in send_file_zipped
smtp.connect()
File "/usr/local/lib/python3.2/smtplib.py", line 319, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/local/lib/python3.2/smtplib.py", line 294, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/local/lib/python3.2/socket.py", line 404, in create_connection
raise err
File "/usr/local/lib/python3.2/socket.py", line 395, in create_connection
sock.connect(sa)
socket.error: [Errno 61] Connection refused
I am going to assume that my issue lies in connecting with the smtp server, but I don't know what I am missing. Any help would be greatly appreciated!!
smtp.connect() is wrong/redundant. The smtplib.SMTP(...) calls .connect upon initialization. A bare .connect call without any parameters means connection to localhost and if you do not have a SMTP server running on your machine you'll get an error.
However your goal is to send mail through GMail. Note that GMail's SMTP requires authentication, which you are not doing.
Your last lines should be accordingly:
# send the message
smtp = smtplib.SMTP("smtp.gmail.com", 587)
smtp.helo()
smtp.starttls() # Encrypted connection
smtp.ehlo()
smtp.login(username, password) # Give your credentials
smtp.sendmail(sender, recipients, themsg)
smtp.quit()
This may not be your problem, but you're specifying the port number as a string, and that's probably not going to work.

Categories