使用 Python 示例发送电子邮件失败

发布于 2024-07-11 03:15:06 字数 3487 浏览 6 评论 0原文

我一直在尝试(但失败了)弄清楚如何通过 Python 发送电子邮件。

尝试这里的示例: http://docs.python.org/library/smtplib.html#smtplib.SMTP

但在我收到有关没有 SSL 连接的反弹后添加了行 server = smtplib.SMTP_SSL('smtp.gmail.com', 465)

现在我得到这个:

Traceback (most recent call last):
  File "C:/Python26/08_emailconnects/12_29_EmailSendExample_NotWorkingYet.py", line 37, in <module>
    server = smtplib.SMTP('smtp.gmail.com', 65)
  File "C:\Python26\lib\smtplib.py", line 239, in __init__
    (code, msg) = self.connect(host, port)
  File "C:\Python26\lib\smtplib.py", line 295, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "C:\Python26\lib\smtplib.py", line 273, in _get_socket
    return socket.create_connection((port, host), timeout)
  File "C:\Python26\lib\socket.py", line 512, in create_connection
    raise error, msg
error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
>>> 

想法?


server = smtplib.SMTP("smtp.google.com", 495) 给我一个超时错误。 只是 smtplib.smtp("smtp.google.com", 495) 给了我“SSLError:[Errno 1] _ssl.c:480:错误:140770FC:SSL例程:SSL23_GET_SERVER_HELLO:未知协议”(见下文)。

我正在尝试不同的端口,现在出现了一个全新的错误。 我只会发布全部代码,我可能会犯一些菜鸟错误。

import smtplib

mailuser = '[email protected]'

mailpasswd = 'MYPASSWORD'

fromaddr = '[email protected]'

toaddrs = '[email protected]'

msg = 'Hooooorah!'

print msg

server = smtplib.SMTP_SSL('smtp.google.com')

server = smtplib.SMTP_SSL_PORT=587

server.user(mailuser)

server.pass_(mailpasswd)

server.set_debuglevel(1)

server.sendmail(fromaddr, toaddrs, msg)

server.quit()

然后我收到此错误消息:“

Traceback (most recent call last):
  File "C:/Python26/08_emailconnects/12_29_eMAILSendtryin_stripped.py", line 16, in <module>
    server = smtplib.SMTP_SSL('smtp.google.com')
  File "C:\Python26\lib\smtplib.py", line 749, in __init__
    SMTP.__init__(self, host, port, local_hostname, timeout)
  File "C:\Python26\lib\smtplib.py", line 239, in __init__
    (code, msg) = self.connect(host, port)
  File "C:\Python26\lib\smtplib.py", line 295, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "C:\Python26\lib\smtplib.py", line 755, in _get_socket
    self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
  File "C:\Python26\lib\ssl.py", line 350, in wrap_socket
    suppress_ragged_eofs=suppress_ragged_eofs)
  File "C:\Python26\lib\ssl.py", line 118, in __init__
    self.do_handshake()
  File "C:\Python26\lib\ssl.py", line 293, in do_handshake
    self._sslobj.do_handshake()
SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol

请注意,实际上看起来像“server = smtplib.SMTPSSLPORT=587”的实际上是“server = smtplib.SMTP 下划线 SSL 下划线< /em> PORT=587”,这里发生了某种格式化操作。

I've been trying (and failing) to figure out how to send email via Python.

Trying the example from here:
http://docs.python.org/library/smtplib.html#smtplib.SMTP

but added the line server = smtplib.SMTP_SSL('smtp.gmail.com', 465) after I got a bounceback about not having an SSL connection.

Now I'm getting this:

Traceback (most recent call last):
  File "C:/Python26/08_emailconnects/12_29_EmailSendExample_NotWorkingYet.py", line 37, in <module>
    server = smtplib.SMTP('smtp.gmail.com', 65)
  File "C:\Python26\lib\smtplib.py", line 239, in __init__
    (code, msg) = self.connect(host, port)
  File "C:\Python26\lib\smtplib.py", line 295, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "C:\Python26\lib\smtplib.py", line 273, in _get_socket
    return socket.create_connection((port, host), timeout)
  File "C:\Python26\lib\socket.py", line 512, in create_connection
    raise error, msg
error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
>>> 

Thoughts?


server = smtplib.SMTP("smtp.google.com", 495) gives me a timeout error. just smtplib.smtp("smtp.google.com", 495) gives me "SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol" (see below).

I'm trying different ports and now I'm getting a completely new error. I'll just post the whole bit of code, I'm probably making some rookie mistake.

"

import smtplib

mailuser = '[email protected]'

mailpasswd = 'MYPASSWORD'

fromaddr = '[email protected]'

toaddrs = '[email protected]'

msg = 'Hooooorah!'

print msg

server = smtplib.SMTP_SSL('smtp.google.com')

server = smtplib.SMTP_SSL_PORT=587

server.user(mailuser)

server.pass_(mailpasswd)

server.set_debuglevel(1)

server.sendmail(fromaddr, toaddrs, msg)

server.quit()

"

and then I get this error message: "

Traceback (most recent call last):
  File "C:/Python26/08_emailconnects/12_29_eMAILSendtryin_stripped.py", line 16, in <module>
    server = smtplib.SMTP_SSL('smtp.google.com')
  File "C:\Python26\lib\smtplib.py", line 749, in __init__
    SMTP.__init__(self, host, port, local_hostname, timeout)
  File "C:\Python26\lib\smtplib.py", line 239, in __init__
    (code, msg) = self.connect(host, port)
  File "C:\Python26\lib\smtplib.py", line 295, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "C:\Python26\lib\smtplib.py", line 755, in _get_socket
    self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
  File "C:\Python26\lib\ssl.py", line 350, in wrap_socket
    suppress_ragged_eofs=suppress_ragged_eofs)
  File "C:\Python26\lib\ssl.py", line 118, in __init__
    self.do_handshake()
  File "C:\Python26\lib\ssl.py", line 293, in do_handshake
    self._sslobj.do_handshake()
SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol

"

note that actually the which looks like "server = smtplib.SMTPSSLPORT=587" is actually "server = smtplib.SMTP underscore SSL underscore PORT=587", there's some sort of formatting thing going on here.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

忆离笙 2024-07-18 03:15:06

以下代码对我有用:

import smtplib

FROMADDR = "[email protected]"
LOGIN    = FROMADDR
PASSWORD = "my.real.password"
TOADDRS  = ["[email protected]"]
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('smtp.gmail.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(LOGIN, PASSWORD)
server.sendmail(FROMADDR, TOADDRS, msg)
server.quit()

我正在使用Python 2.5.2。

编辑:按照 ΤΖΩΤΖιΟΥ 的建议将端口从 25 更改为 587,并删除第二个 ehlo()。 现在我很想知道为什么端口 25 在我的机器上完美工作(而端口 465不能)。

The following code works for me:

import smtplib

FROMADDR = "[email protected]"
LOGIN    = FROMADDR
PASSWORD = "my.real.password"
TOADDRS  = ["[email protected]"]
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('smtp.gmail.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(LOGIN, PASSWORD)
server.sendmail(FROMADDR, TOADDRS, msg)
server.quit()

I'm using Python 2.5.2.

Edit: changed port from 25 to 587 as suggested by ΤΖΩΤΖΙΟΥ, and dropped the second ehlo(). Now I would love to know why port 25 works perfectly from my machine (and port 465 does not).

从﹋此江山别 2024-07-18 03:15:06

使用 SSL 连接 GMail 的正确方法是:

server = smtplib.SMTP('smtp.gmail.com', 587)

端口 465 似乎会导致延迟。 这两个端口均在 GMail 常见问题解答中指定。

请注意,对于基于 SSL 的 SMTP,端口 587 的使用更为常见,尽管这只是一些无关紧要的信息,但它没有其他实际用途。

此答案作为社区 wiki 提供,以便被选为“最佳”答案。 请根据需要进行改进。

The correct way to connect to GMail using SSL is:

server = smtplib.SMTP('smtp.gmail.com', 587)

Port 465 seems to cause delays. Both ports are specified in a GMail FAQ.

Note that use of port 587 is more common for SMTP over SSL, although this is just trivial information, it has no other practical use.

This answer is provided as community wiki in order to be chosen as "the" answer. Please improve as needed.

樱&纷飞 2024-07-18 03:15:06

该问题是由于 Python 中的错误造成的。 尝试使用 SMTP_SSL 创建连接将失败,并显示“SMTPServerDisconnected:请先运行 connect()”。

修复已提交,因此您可以修补本地副本。 请参阅名为“smtplib_72551.diff”的附件。

(注意:SMTP_SSL是Python 2.6/3.0及更高版本中添加的新类。)

The problem is due to a bug in Python. Trying to create a connection with SMTP_SSL will fail with "SMTPServerDisconnected: please run connect() first."

A fix has been committed, so you can patch your local copy. See the attachment named "smtplib_72551.diff".

(Note: SMTP_SSL is a new class added to Python 2.6/3.0 and later.)

最冷一天 2024-07-18 03:15:06

这是一个简单的一次性解决方案。 本来想早点把这个贴出来的,但在椅子上睡着了。


import smtplib
import email
import os

username = "[email protected]"
passwd = "password"

def mail(to, subject, text, attach):
   msg = MIMEMultipart()

   msg['From'] = username
   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)

   server = smtplib.SMTP("smtp.gmail.com", 495)
   server.ehlo()
   server.starttls()
   server.ehlo()
   server.login(username, passwd)
   server.sendmail(username, to, msg.as_string())
   server.close()

mail("you", "hi", "hi", "webcam.jpg")

我的假设是,该线程上成功尝试其代码的大多数人都不是在 win32 上。 ;)

*编辑:参见 http://docs.python.org/library/email- example.html 一些很好的“官方”示例。

Here's a simple throw away solution. Meant to paste this earlier, but fell asleep at my chair.


import smtplib
import email
import os

username = "[email protected]"
passwd = "password"

def mail(to, subject, text, attach):
   msg = MIMEMultipart()

   msg['From'] = username
   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)

   server = smtplib.SMTP("smtp.gmail.com", 495)
   server.ehlo()
   server.starttls()
   server.ehlo()
   server.login(username, passwd)
   server.sendmail(username, to, msg.as_string())
   server.close()

mail("you", "hi", "hi", "webcam.jpg")

It's my assumption that most people on this thread that have had successful attempts with their code aren't on win32. ;)

*edit: See http://docs.python.org/library/email-examples.html for some good "official" examples.

残月升风 2024-07-18 03:15:06

好吧,发现这行代码可以解决问题!

server = smtplib.SMTP('smtp.gmail.com', 587 )

原来是GMAIL在端口25上不支持SSL(并且端口465由于某种原因导致挂起)。

多谢你们!

Okay, found out that this line of code does the trick!

server = smtplib.SMTP('smtp.gmail.com', 587 )

Turned out to be GMAIL didn't support SSL on port 25 (and port 465 caused a hang for some reason).

Thanks guys!

ま柒月 2024-07-18 03:15:06

你应该检查你的端口,我不确定谷歌的 SMTP 端口是 65,这可以解释超时。

修改您的来源,如下所示:

smtplib.SMTP_SSL('smtp.google.com', 465)

但是,如果您确定它应该工作但没有工作,则 smtplib.SMTP_SSL 似乎存在一些问题, 此处有一个可用的补丁。

You should check your port, I'm not sure that google's SMTP port is 65, that would explain the timeout.

Modify your sources as such:

smtplib.SMTP_SSL('smtp.google.com', 465)

If, however, you are certain that it ought to work and it doesn't, it appears that there are some problems with smtplib.SMTP_SSL, and there's an available patch for it here.

美男兮 2024-07-18 03:15:06

也许端口错误? 我正在使用 587 作为 smtp.gmail.com,它可以工作。

Incorrect port maybe? I'm using 587 for smtp.gmail.com and it works.

苍风燃霜 2024-07-18 03:15:06
from smtplib import SMTP_SSL as SMTP
from email.mime.text import MIMEText

HOST = 'smtp.gmail.com'
PORT = 465

USERNAME = '[email protected]'
PASSWORD = ''

SENDER = '[email protected]'
RECIPIENT = '[email protected]'

text_subtype = 'plain'

with open('textfile', 'rb') as f:
    msg = MIMEText(f.read(), text_subtype)


msg['Subject'] = 'Python Script'
msg['From'] = SENDER
msg['To'] = RECIPIENT

try:
    connection = SMTP(HOST, PORT)
    connection.login(USERNAME, PASSWORD)
    connection.sendmail(SENDER, RECIPIENT, msg.as_string())
except Exception, e:
    print(e)

上面的代码对我来说效果很好。 正如您所看到的,由于我使用的是 SSL,因此本示例中使用了 PORT = 465。 如果您计划使用端口 587,则需要 TLS

from smtplib import SMTP_SSL as SMTP
from email.mime.text import MIMEText

HOST = 'smtp.gmail.com'
PORT = 465

USERNAME = '[email protected]'
PASSWORD = ''

SENDER = '[email protected]'
RECIPIENT = '[email protected]'

text_subtype = 'plain'

with open('textfile', 'rb') as f:
    msg = MIMEText(f.read(), text_subtype)


msg['Subject'] = 'Python Script'
msg['From'] = SENDER
msg['To'] = RECIPIENT

try:
    connection = SMTP(HOST, PORT)
    connection.login(USERNAME, PASSWORD)
    connection.sendmail(SENDER, RECIPIENT, msg.as_string())
except Exception, e:
    print(e)

The above code works fine for me. As you can see the PORT = 465 is being used in this example since I am using SSL. If you plan to use the port 587 then TLS is required.

无法言说的痛 2024-07-18 03:15:06
import smtplib

content = 'example email stuff here'

mail = smtplib.SMTP('smtp.gmail.com', 587)

mail.ehlo()

mail.starttls()

mail.login('[email protected]','password')

mail.sendmail('[email protected]', '[email protected]', content)

mail.close()
import smtplib

content = 'example email stuff here'

mail = smtplib.SMTP('smtp.gmail.com', 587)

mail.ehlo()

mail.starttls()

mail.login('[email protected]','password')

mail.sendmail('[email protected]', '[email protected]', content)

mail.close()
青瓷清茶倾城歌 2024-07-18 03:15:06

然后我尝试通过 smtp.gmail.com 发送电子邮件,我遇到了同样的错误。 就我而言,互联网提供商关闭了从 IP 地址(从我的网络)到外部网络的传出连接的端口 25(以及 587 和其他端口),仅为其邮件服务器保留开放的第 25 个端口。
因此,首先尝试:

telnet smtp.gmail.com 587

(587是您的端口)

通过这样做,您可以了解您的端口是否被互联网提供商关闭。
您可以联系您的提供商并要求他们为您打开端口。
我的解决方案是连接到其他网络(使用开放端口)
这是我使用的代码:

gmailaddress = "[email protected]"
gmailpassword = "7777777"
mailto = "[email protected]"
msg = input("What is your message? \n ")
mailServer = smtplib.SMTP('smtp.gmail.com' , 587)
mailServer.starttls()
mailServer.login(gmailaddress , gmailpassword)
mailServer.sendmail(gmailaddress, mailto , msg)
print(" \n Sent!")
mailServer.quit()```

Then I had trie to sent email through smtp.gmail.com, I had the same errors. In my case the Internet provider had close the port 25 (and also 587 and other) for outgoing connections from the IP addresses (from my network) to the external network, leaving open the 25th port only for its mail server.
So, at first try:

telnet smtp.gmail.com 587

(587 it your port)

By doing this you can understand, if your port is closed by the Internet provider.
You can contact your provider and ask them to open a port for you.
My solution was connecting to other network (with open port)
Here is the code I used:

gmailaddress = "[email protected]"
gmailpassword = "7777777"
mailto = "[email protected]"
msg = input("What is your message? \n ")
mailServer = smtplib.SMTP('smtp.gmail.com' , 587)
mailServer.starttls()
mailServer.login(gmailaddress , gmailpassword)
mailServer.sendmail(gmailaddress, mailto , msg)
print(" \n Sent!")
mailServer.quit()```
怎会甘心 2024-07-18 03:15:06

经过大量摆弄示例后,例如这里
这现在对我有用:

import smtplib
from email.mime.text import MIMEText

# SMTP sendmail server mail relay
host = 'mail.server.com'
port = 587 # starttls not SSL 465 e.g gmail,port 25 blocked by most ISPs & AWS
sender_email = '[email protected]'
recipient_email = '[email protected]'
password = 'YourSMTPServerAuthenticationPass'
subject = "Server - "
body = "Message from server"

def sendemail(host, port, sender_email, recipient_email, password, subject, body):
    try:
        p1 = f'<p><HR><BR>{recipient_email}<BR>'
        p2 = f'<h2><font color="green">{subject}</font></h2>'
        p3 = f'<p>{body}'
        p4 = f'<p>Kind Regards,<BR><BR>{sender_email}<BR><HR>'
        
        message = MIMEText((p1+p2+p3+p4), 'html')  
        # servers may not accept non RFC 5321 / RFC 5322 / compliant TXT & HTML typos

        message['From'] = f'Sender Name <{sender_email}>'
        message['To'] = f'Receiver Name <{recipient_email}>'
        message['Cc'] = f'Receiver2 Name <>'
        message['Subject'] = f'{subject}'
        msg = message.as_string()

        server = smtplib.SMTP(host, port)
        print("Connection Status: Connected")
        server.set_debuglevel(1)
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(sender_email, password)
        print("Connection Status: Logged in")
        server.sendmail(sender_email, recipient_email, msg)
        print("Status: Email as HTML successfully sent")

    except Exception as e:
            print(e)
            print("Error: unable to send email")

# Run
sendemail(host, port, sender_email, recipient_email, password, subject, body)
print("Status: Exit")

After a lot of fiddling with the examples e.g here
this now works for me:

import smtplib
from email.mime.text import MIMEText

# SMTP sendmail server mail relay
host = 'mail.server.com'
port = 587 # starttls not SSL 465 e.g gmail,port 25 blocked by most ISPs & AWS
sender_email = '[email protected]'
recipient_email = '[email protected]'
password = 'YourSMTPServerAuthenticationPass'
subject = "Server - "
body = "Message from server"

def sendemail(host, port, sender_email, recipient_email, password, subject, body):
    try:
        p1 = f'<p><HR><BR>{recipient_email}<BR>'
        p2 = f'<h2><font color="green">{subject}</font></h2>'
        p3 = f'<p>{body}'
        p4 = f'<p>Kind Regards,<BR><BR>{sender_email}<BR><HR>'
        
        message = MIMEText((p1+p2+p3+p4), 'html')  
        # servers may not accept non RFC 5321 / RFC 5322 / compliant TXT & HTML typos

        message['From'] = f'Sender Name <{sender_email}>'
        message['To'] = f'Receiver Name <{recipient_email}>'
        message['Cc'] = f'Receiver2 Name <>'
        message['Subject'] = f'{subject}'
        msg = message.as_string()

        server = smtplib.SMTP(host, port)
        print("Connection Status: Connected")
        server.set_debuglevel(1)
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(sender_email, password)
        print("Connection Status: Logged in")
        server.sendmail(sender_email, recipient_email, msg)
        print("Status: Email as HTML successfully sent")

    except Exception as e:
            print(e)
            print("Error: unable to send email")

# Run
sendemail(host, port, sender_email, recipient_email, password, subject, body)
print("Status: Exit")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文