SSL Error while Sending Email with Python (Raspbian OS) - python

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.

Related

Cannot to sent email via Python

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.

Error trying to send email to gmail python

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

How to send email attachments with Python 3.6

would you mind helping me, please!
I use all code's from this page How to send email attachments with Python
but it didn't work =(
This is last version which i used
import smtplib
from smtplib import SMTP_SSL
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
import os
filepath = 'D:/files/1.jpg'
fromaddr = "name#gmail.com"
toaddr = "name2#gmail.com"
password = '********'
mail_adr = 'smtp.gmail.com'
mail_port = 587
# Compose attachment
part = MIMEBase('application', "octet-stream")
part.set_payload(open(filepath, "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % os.path.basename(filepath))
# Compose message
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg.attach(part)
# Send mail
smtp = SMTP_SSL()
smtp.set_debuglevel(1)
smtp.connect(mail_adr, mail_port)
smtp.login(fromaddr, password)
smtp.sendmail(fromaddr, toaddr, msg.as_string())
smtp.quit()
and here are the errors I fall
connect: ('smtp.gmail.com', 587)
connect: ('smtp.gmail.com', 587)
Traceback (most recent call last):
File "C:/Users/Oleg/Desktop/444.py", line 31, in <module>
smtp.connect(mail_adr, mail_port)
File "C:\Users\Oleg\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 335, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Users\Oleg\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 1037, in _get_socket
server_hostname=self._host)
File "C:\Users\Oleg\AppData\Local\Programs\Python\Python36-32\lib\ssl.py", line 401, in wrap_socket
_context=self, _session=session)
File "C:\Users\Oleg\AppData\Local\Programs\Python\Python36-32\lib\ssl.py", line 808, in __init__
self.do_handshake()
File "C:\Users\Oleg\AppData\Local\Programs\Python\Python36-32\lib\ssl.py", line 1061, in do_handshake
self._sslobj.do_handshake()
File "C:\Users\Oleg\AppData\Local\Programs\Python\Python36-32\lib\ssl.py", line 683, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:749)
Have you tried emailpy? (I am the author)
It supports any attachment format unless your email provider restricts it.
Example:
import emailpy
emailManager = emailpy.EmailManager('yourcooladdress#domain.com', 'youremailpassword') # this may take a few seconds to generate
emailManager.send(['sendsomething#gmail.com', 'anotheremail#hotmail.com'], \
subject = 'Subject here', body = 'body text here', html = 'some html here', \
attachments = ['file1.png', 'file2.txt', 'file3.py'], \
nofileattach = {'file.txt': 'hi, this is some data'})
# send email to sendsomething#gmail.com and anotheremail#hotmail.com with subject "Subject here"
#, body "body text here", html "some html here", and some attachments:
# "file1.png", "file2.txt", "file3.py". Also, it adds a file called file.txt
# that has the contents "hi, this is some data"
The emailpy docs can either be downloaded on its PyPI page, or from here
All email servers have been successfully tested with emailpy, and there will be no errors with emailpy if you use it on python 3.x (emailpy is not supported in python 2, mainly because of the syntax)

Python SMTP error: "(10013, 'Permission denied')"

So I have this Python send-email file that sends an email (the text from a file) to a recipient specified inside the code:
import smtplib
from email.mime.text import MIMEText
msgContent = open(Sourcefilelocation, "rb")
msg = MIMEText(spam.read())
msgContent.close()
msg['Subject'] = SUBJECT
msg['From'] = FROM_CLIENT_EMAIL
msg['To'] = TO_CLIENT_EMAIL
#THE ERROR BELOW
s = smtplib.SMTP('localhost')
I understand that there is no mail server on localhost, but how do I make a mail server on that and if I can't then why does s = smtplib.SMTP('gmail.com') take so long if it even works? What do I need to make it work? Any help is appreciated.
output: >> Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
s = smtplib.SMTP('gmail.com')
File "C:\Python25\lib\smtplib.py", line 244, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python25\lib\smtplib.py", line 310, in connect
raise socket.error, msg
error: (10013, 'Permission denied')
And the gmail smtp code takes too long.

Emailing smtp with Python error

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.

Categories

Resources