I trying to send email via python using gmail smtp, but receiving the error:
Code:
import smtplib
FROM = "mail1#gmail.com"
TO = "mail2#gmail.com"
message = "Hello"
# Send the mail
server = smtplib.SMTP('smtp.gmail.com', 465)
server.ehlo()
server.starttls()
server.login('mail1#gmail.com', 'password')
server.sendmail(FROM, TO, message)
server.quit()
Response:
server = smtplib.SMTP('smtp.gmail.com', 465)
File "C:\Python37\lib\smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python37\lib\smtplib.py", line 338, in connect
(code, msg) = self.getreply()
File "C:\Python37\lib\smtplib.py", line 394, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
According to example at python documentation
https://docs.python.org/3/library/smtplib.html
your code is missing the “From: and To:” headers
import smtplib
def prompt(prompt):
return input(prompt).strip()
fromaddr = prompt("From: ")
toaddrs = prompt("To: ").split()
print("Enter message, end with ^D (Unix) or ^Z (Windows):")
# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
% (fromaddr, ", ".join(toaddrs)))
while True:
try:
line = input()
except EOFError:
break
if not line:
break
msg = msg + line
print("Message length is", len(msg))
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
run the above example, then modify to your code posted.
Related
I am running the below code in Ubuntu OS. When I run this code in stand alone machine, I am not getting any error.
But when I connect the remote machine and run the same code, I am getting the following error message.
I have also modified the port value and try multiple times but the issue is not fixing. I am wondering where i need to check to resolve the issue.
import smtplib
message = ' '
sender = ' '
receivers = ' '
SUBJECT = ' '
TEXT = ' '
sender = 'sender1#abc.com'
receivers = ['rec1#abc.com','rec2#abc.com']
# prepare message
SUBJECT = "Test mail "
TEXT = """Message line1 \n
Message line2 \n """
message = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT)
try:
smtpObj = smtplib.SMTP(<Value>)
smtpObj.sendmail(sender, receivers, message)
smtpObj.close()
except smtplib.SMTPConnectError:
print "Error: unable to send email"
except smtplib.SMTPException:
print "Error: unable to send email"
Error message:
Traceback (most recent call last):
File "sampa.py", line 23, in <module>
smtpObj = smtplib.SMTP(<Value>)
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 571, in create_connection
raise err
socket.error: [Errno 111] Connection refused
try:
smtpObj = smtplib.SMTP(smtp_server, port)
smtpObj.ehlo() # Can be omitted
smtpObj.starttls(context=context) # Secure the connection
smtpObj.ehlo() # Can be omitted
smtpObj.login(sender, password)
smtpObj.sendmail(sender, receivers, email_text)
Hi all I am new to python. I am trying to send an image to my gmail account and getting the below error can someone help me with this.
I have searched and searched and can't find an answer I have tried changing the port.
I have turned on the google less secure apps and not sure what else to do.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
import os
gmail_user = "you#gmail.com"
gmail_pwd = "pass"
to = "you#gmail.com"
subject = "Report"
text = "Picture report"
attach = 'web.png'
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 465)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
Traceback (most recent call last):
File "C:\Users\scott\Desktop\PYTHON NEW\newemail.py", line 31, in <module>
mailServer = smtplib.SMTP("smtp.gmail.com", 465)
File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 337, in connect
(code, msg) = self.getreply()
File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 393, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
i have changed the port to 587 and got a different error
Traceback (most recent call last):
File "C:\Users\scott\Desktop\PYTHON NEW\newemail.py", line 35, in <module>
mailServer.login(gmail_user, gmail_pwd)
File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 729, in login
raise last_exception
File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 720, in login
initial_response_ok=initial_response_ok)
File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 641, in auth
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbt4\n5.7.14 ah5smKPNBMdR8EDhHji_lOLermVkofD0XZiYZtx04cUZGJIvjm6scA9FeCEhJhB--aeW58\n5.7.14 O3uS9IVuNfqKe4HYqXgdBMbvtMSOSSMM4oGYwlvDIoXpIK0IJYKSyAfvPyPcjiF8Q_Es4n\n5.7.14 33gUceqr9ZjlNI066kXt-uTq2V39X6YUS2-ixCCKfoozS9zoQ1KJuLSWU1IhB3gTsGtB9m\n5.7.14 N-AEdgucbByvuI7zr2KG-DZwlvrWw> 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 b65sm27550600wrd.26 - gsmtp')
Your code can be shortened down to just two lines:
import smtplib
mailServer = smtplib.SMTP("smtp.gmail.com", 465)
And if you get smtplib.SMTPServerDisconnected, this means that your question is not about the code. Something is blocking your network connection to port 465.
A SMTP server on port 465 is listening for encrypted TLS connections. The client is not supposed to start the encryption with STARTTLS, because TLS is active from the beginning. That SMTP command is used on port 587 where SMTP servers are listening for plaintext connections.
you can use flask_mail library for sending mail.Here is just quick review..
'
from flask_mail import Mail, Message
app.config['SECRET_KEY'] = 'your secretkey'
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = 'your gmail id'
app.config['MAIL_PASSWORD'] = 'and its password'
mail = Mail(app)
msg = Message(subject=subject, sender=(master().user(),
app.config['MAIL_USERNAME']), recipients=[recipients])
msg.body = "%s %s" % (body, msg.sender)
if html is not None:
msg.html = str(html)
mail.connect()
mail.send(msg)
'
***Note :- do not forget to turn off 2-step verification and also turn on Allow less secure apps from sign-in & security > device activity & security events
Hi I am trying to send an email through python. I use this code to send:
server = smtplib.SMTP(host='send.one.com',port=465)
server.starttls()
server.login(USER, PASS)
text = msg.as_string()
server.sendmail(mailFrom, mailTo, text)
server.quit()
but I get an error on the first line:
File "/home/emil/Name_Generator/VoteMail.py", line 69, in sendVoteMail
server = smtplib.SMTP(host='send.one.com',port=465)
File "/usr/lib/python3.4/smtplib.py", line 242, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python3.4/smtplib.py", line 323, in connect
(code, msg) = self.getreply()
File "/usr/lib/python3.4/smtplib.py", line 376, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
Has anyone else tried to connect to one.com smtp server with Python?
For everyone else that use one.com for your email and you want to connect to theire SMTP server thene I found out that they use SSL, and that was why my code did't work the proper way to do it is as follow:
server = smtplib.SMTP_SSL(host='send.one.com',port=465)
server.login(USER, PASS)
text = msg.as_string()
server.sendmail(mailFrom, mailTo, text)
server.quit()
I just write this code in Python under Raspbian OS:
import smtplib
fromaddr = '*****#hotmail.de'
toaddrs = '*****#hotmail.de'
msg = 'Testmail'
username = '*****#hotmail.de'
password = '*****'
server = smtplib.SMTP('smtp.live.com',587)
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
And get following Error-Message:
python ail.py
Traceback (most recent call last):
File "ail.py", line 14, in <module>
server.login(username, password)
File "/usr/lib/python2.7/smtplib.py", line 601, in login
AUTH_PLAIN + " " + encode_plain(user, password))
File "/usr/lib/python2.7/smtplib.py", line 385, in docmd
return self.getreply()
File "/usr/lib/python2.7/smtplib.py", line 358, in getreply
+ str(e))
smtplib.SMTPServerDisconnected: Connection unexpectedly closed: [Errno 1] _ssl.c:1359:
error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number
What is my fault? Could somebody help me - please?
Regards
After I've signed in on http://live.com and validated my account; your code worked as is on Ubuntu python 2.7 and python3.3:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Send email via live.com."""
import smtplib
from email.mime.text import MIMEText
from email.header import Header
login, password = ...
msg = MIMEText(u'body…', 'plain', 'utf-8')
msg['Subject'] = Header(u'subject…', 'utf-8')
msg['From'] = login
recipients = [login]
msg['To'] = ", ".join(recipients)
s = smtplib.SMTP('smtp.live.com', 587, timeout=10)
s.set_debuglevel(1)
try:
s.starttls()
s.login(login, password)
s.sendmail(msg['From'], recipients, msg.as_string())
finally:
s.quit()
Check whether openssl can connect to it (ca-certificates is installed and it is not this bug):
$ openssl s_client -starttls smtp -connect smtp.live.com:587
If it is successful; you could replace smtplib.SMTP.starttls() method (in a subclass) to set appropriate ssl parameters.
I can't figure out why this isn't working. I'm trying to send an email from my school email address with this code I got online. The same code works for sending from my GMail address. Does anyone know what this error means? The error occurs after waiting for about one and a half minutes.
import smtplib
FROMADDR = "FROM_EMAIL"
LOGIN = "USERNAME"
PASSWORD = "PASSWORD"
TOADDRS = ["TO_EMAIL"]
SUBJECT = "Test"
msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n"
% (FROMADDR, ", ".join(TOADDRS), SUBJECT) )
msg += "some text\r\n"
server = smtplib.SMTP('OUTGOING_SMTP', 465)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(LOGIN, PASSWORD)
server.sendmail(FROMADDR, TOADDRS, msg)
server.quit()
And here's the error I get:
Traceback (most recent call last):
File "emailer.py", line 13, in
server = smtplib.SMTP('OUTGOING_SMTP', 465)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 239, in init
(code, msg) = self.connect(host, port)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/socket.py", line 514, in create_connection
raise error, msg
socket.error: [Errno 60] Operation timed out
It's likely that your school's SMTP server does not permit outside access to port 587. Gmail does, and requires authentication to ensure that you are who you say you are (and so that spammers can't send email appearing to be from you unless they know your password). Your school may have chosen to set up their mail server so that only connections from within the school can send mail in this way.