如何修复ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056)错误?

80

我正在尝试使用Python发送电子邮件,但它一直显示ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056)。这是我的代码:

server = smtplib.SMTP_SSL('smtp.mail.com', 587)
server.login("something0@mail.com", "password")
server.sendmail(
"something0@mail.com", 
"something@mail.com", 
"email text")
server.quit()

你知道出了什么问题吗?


2
你的操作系统是什么?Python版本和OpenSSL版本是多少?如果你打开命令解释器,输入import sslprint(ssl.OPENSSL_VERSION),会输出什么? - CristiFati
1
@CristiFati Windows 10 Home,3.7,OpenSSL 1.1.0j 20 Nov 2018 - TheRealTengri
您正在使用错误的端口进行SSL连接 587是用于TLS的端口 465是用于SSL的端口 - Bilal Naqvi
4个回答

82

SSL端口为465而不是587,但当我使用SSL时邮件却被归为垃圾邮件。

对我而言,有效的方法是使用常规SMTP上的TLS代替SMTP_SSL

请注意,这是一种安全的方法,因为TLS也是一种加密协议(与SSL类似)。

import smtplib, ssl

port = 587  # For starttls
smtp_server = "smtp.gmail.com"
sender_email = "my@gmail.com"
receiver_email = "your@gmail.com"
password = input("Type your password and press enter:")
message = """\
Subject: Hi there

This message is sent from Python."""

context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
    server.ehlo()  # Can be omitted
    server.starttls(context=context)
    server.ehlo()  # Can be omitted
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)

感谢Real Python教程提供此内容。


2

这是我解决同样问题的方法

import ssl


sender = "youremail@yandex.ru"
password = "password123"
    
where_to_email = "reciever@anymail.com"
theme = "this is subject"
message = "this is your message, say hi to reciever"
    
sender_password = password
session = smtplib.SMTP_SSL('smtp.yandex.ru', 465)
session.login(sender, sender_password)
msg = f'From: {sender}\r\nTo: {where_to_email}\r\nContent-Type: text/plain; charset="utf-8"\r\nSubject: {theme}\r\n\r\n'
msg += message
session.sendmail(sender, where_to_email, msg.encode('utf8'))
session.quit()

如果您想使用yandex邮件,您必须在设置中打开“保护代码”。


1

谷歌不再允许您关闭此功能,这意味着无论您做什么,它都无法正常工作,雅虎似乎也是如此。


-1

使用 Python 发送电子邮件的代码:

import smtplib , ssl
import getpass
server = smtplib.SMTP_SSL("smtp.gmail.com",465)
server.ehlo()
server.starttls
password = getpass.getpass()   # to hide your password while typing (feels cool)
server.login("example@gmail.com", password)
server.sendmail("example@gmail.com" , "sender-example@gmail.com" , "I am trying out python email through coding")
server.quit()

#关闭“较不安全的应用程序访问权限”,以使其在您的 Gmail 上正常工作


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接