Python - 发送电子邮件时出错(中继访问被拒绝)

时间:2017-08-14 13:19:50

标签: python email smtp

尝试使用python sendmail发送电子邮件时出错。这是我的python代码: (Pas d'objet)

 extra_kwargs = {
     'required': {'required': True},
 }

当我发送此电子邮件时,出现此错误:

#! /usr/bin/python

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# me == my email address
# you == recipient's email address
me = "my@email.com"
you = "email@gmail.com"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
  <head></head>
  <body>
    <p>Hi!<br>
       How are you?<br>
       Here is the <a href="[http://www.python.org">link</a]http://www.python.org">link</a> you wanted.
    </p>
  </body>
</html>
"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)

# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()

我真的不知道为什么它在生产中不起作用,因为它在测试环境中工作。你能帮忙理解吗?

1 个答案:

答案 0 :(得分:1)

Relay access denied消息很重要:听起来您已经成功建立了SMTP连接(到示例代码中的localhost),但是该机器拒绝接受该消息:您可能需要进行调整,

  • 您在localhost上的邮件服务器配置
  • 您的代码以通过localhost邮件服务器接受电子邮件的方式发送电子邮件。

请特别注意,发送到端口25(SMTP的默认端口)的邮件通常用于传入电子邮件。在您的情况下,您希望邮件服务器接受该消息并将其发送到其他位置(“中继”,因此是错误消息)。看来您的邮件服务器(此处为localhost)未设置为接受非本地域的邮件……至少不在端口25上。

SMTP的另一个重要用途是“邮件提交”,通常在其他端口上设置(通常为587,如果SSL加密则为465)。通过在命令行上使用telnet来查看是否是这种情况;如果服务器在端口上响应,还可以使用EHLO <some_hostname>来查看服务器提供的功能(有趣的问题是AUTHSTARTTLS

$ telnet localhost 587
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 localhost.example.org ESMTP Postfix (Ubuntu)
ehlo localhost.example.org
250-localhost.example.org
250-VARIOUS_FEATURES_ON_LINES_LIKE_THIS
250-STARTTLS
250-AUTH LOGIN PLAIN
250-AUTH=LOGIN PLAIN
QUIT
221 2.0.0 Bye
Connection closed by foreign host.

也对端口25进行此操作并比较结果:这应该为您提供进行操作的线索-例如,您可能需要AUTH,或使用端口587,或者您可能需要调整({ {1}})邮件服务器配置,因此它可以充当“智能主机”将电子邮件转发到“网络”。

相关问题