Unable to send email using gmail server using python - 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

Related

send email with email module in 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.

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

Sending gmail from web server

In my python file I am sending mail from gmail:
I used
server = smtplib.SMTP("smtp.gmail.com", 587)
I am successfully sending mails from my local system,
I executed same code in the web server I got this error:
File "/usr/lib/python2.4/smtplib.py", line 244, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.4/smtplib.py", line 306, in connect
raise socket.error, msg
socket.error: (97, 'Address family not supported by protocol')
How to send mails using gmail in web server using python?
Try SMTP_SSL, based on the below it'll probably help:
https://docs.python.org/2/library/smtplib.html

Socket Error - Sending email using gmail

I am using the code from this article to send an email using gmail.
The code is as follows
import smtplib
def sendemail(from_addr, to_addr_list, cc_addr_list,
subject, message,
login, password,
smtpserver='smtp.gmail.com:587'):
header = 'From: %s\n' % from_addr
header += 'To: %s\n' % ','.join(to_addr_list)
header += 'Cc: %s\n' % ','.join(cc_addr_list)
header += 'Subject: %s\n\n' % subject
message = header + message
server = smtplib.SMTP(smtpserver)
server.starttls()
server.login(login,password)
problems = server.sendmail(from_addr, to_addr_list, message)
server.quit()
return problems
When i run it, I however get the following socket error.
socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions
EDIT: Traceback
O:\Send Email With Attachment>SendEmail_Ver2.py
Traceback (most recent call last):
File "O:\Send Email With Attachment\SendEmail_Ver2.py", line 26, in <module>
password = 'XXXXXXXXXXX')
File "O:\SendEmail_Ver2.py", line 13, in sendemail
server = smtplib.SMTP(smtpserver)
File "C:\Program Files (x86)\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Program Files (x86)\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Program Files (x86)\Python26\lib\smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "C:\Program Files (x86)\Python26\lib\socket.py", line 561, in create_connection
raise error, msg socket.error: [Errno 10013] An attempt was made to access a socket in
a way forbidden by its access permissions`
How do I get privileges for the script to use port 587? Or is there a higher port number that gmail can use?
Thanks
The problem was McAfee Antivirus. It was blocking the socket connection.
From McAfee Access Protection Log
23/08/2013 10:23:54 a.m. Blocked by port blocking rule C:\Program Files (x86)\Python26\python.exe Anti-virus Standard Protection:Prevent mass mailing worms from sending mail 74.125.25.108:25
I disabled McAfee completely and it worked fine after that.
The problem for me was also McAfee. But instead of disabling McAfee completely as user1494941 did, I would recommend adding python.exe to the list of excepted programs:
In the VirusScan Console,
Right-click on 'Access Protection', select 'Properties'
In Categories, Select 'Anti-virus Standard Protection'
In the Rules panel, select 'Prevent mass mailing worms from sending email'
Select 'Edit', to edit the rules for this protection.
Add python.exe to the list of processes to exclude and then OK.

Categories