218

此代码可以正常工作并向我发送电子邮件:

import smtplib
#SERVER = "localhost"

FROM = 'monty@python.com'

TO = ["jon@mycompany.com"] # must be a list

SUBJECT = "Hello!"

TEXT = "This message was sent with Python's smtplib."

# Prepare actual message

message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail

server = smtplib.SMTP('myserver')
server.sendmail(FROM, TO, message)
server.quit()

但是,如果我尝试将其包装在这样的函数中:

def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
    import smtplib
    """this is some test documentation in the function"""
    message = """\
        From: %s
        To: %s
        Subject: %s
        %s
        """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
    # Send the mail
    server = smtplib.SMTP(SERVER)
    server.sendmail(FROM, TO, message)
    server.quit()

并称之为我收到以下错误:

 Traceback (most recent call last):
  File "C:/Python31/mailtest1.py", line 8, in <module>
    sendmail.sendMail(sender,recipients,subject,body,server)
  File "C:/Python31\sendmail.py", line 13, in sendMail
    server.sendmail(FROM, TO, message)
  File "C:\Python31\lib\smtplib.py", line 720, in sendmail
    self.rset()
  File "C:\Python31\lib\smtplib.py", line 444, in rset
    return self.docmd("rset")
  File "C:\Python31\lib\smtplib.py", line 368, in docmd
    return self.getreply()
  File "C:\Python31\lib\smtplib.py", line 345, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

谁能帮我理解为什么?

4

14 回答 14

223

我建议您使用标准包emailsmtplib一起发送电子邮件。请查看以下示例(转载自Python 文档)。请注意,如果您采用这种方法,“简单”任务确实很简单,而更复杂的任务(如附加二进制对象或发送纯/HTML 多部分消息)可以非常快速地完成。

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.mime.text import MIMEText

# Open a plain text file for reading.  For this example, assume that
# the text file contains only ASCII characters.
with open(textfile, 'rb') as fp:
    # Create a text/plain message
    msg = MIMEText(fp.read())

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()

要向多个目的地发送电子邮件,您还可以按照Python 文档中的示例进行操作:

# Import smtplib for the actual sending function
import smtplib

# Here are the email package modules we'll need
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = ', '.join(family)
msg.preamble = 'Our family reunion'

# Assume we know that the image files are all in PNG format
for file in pngfiles:
    # Open the files in binary mode.  Let the MIMEImage class automatically
    # guess the specific image type.
    with open(file, 'rb') as fp:
        img = MIMEImage(fp.read())
    msg.attach(img)

# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
s.sendmail(me, family, msg.as_string())
s.quit()

如您所见,对象To中的标头MIMEText必须是由逗号分隔的电子邮件地址组成的字符串。另一方面,sendmail函数的第二个参数必须是字符串列表(每个字符串都是一个电子邮件地址)。

因此,如果您有三个电子邮件地址:person1@example.comperson2@example.comperson3@example.com,您可以执行以下操作(省略明显的部分):

to = ["person1@example.com", "person2@example.com", "person3@example.com"]
msg['To'] = ",".join(to)
s.sendmail(me, to, msg.as_string())

",".join(to)部分从列表中生成一个字符串,用逗号分隔。

根据您的问题,我了解到您还没有阅读Python 教程- 如果您想了解 Python 的任何地方,这是必须的 - 文档对于标准库来说非常好。

于 2011-06-07T20:07:33.873 回答
87

当我需要在 Python 中发送邮件时,我使用mailgun API,它在发送邮件时会遇到很多麻烦。他们有一个很棒的应用程序/api,可让您每月发送 5,000 封免费电子邮件。

发送电子邮件将是这样的:

def send_simple_message():
    return requests.post(
        "https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
        auth=("api", "YOUR_API_KEY"),
        data={"from": "Excited User <mailgun@YOUR_DOMAIN_NAME>",
              "to": ["bar@example.com", "YOU@YOUR_DOMAIN_NAME"],
              "subject": "Hello",
              "text": "Testing some Mailgun awesomness!"})

您还可以跟踪事件等等,请参阅快速入门指南

于 2016-02-09T16:16:14.457 回答
58

我想通过建议 yagmail 包来帮助您发送电子邮件(我是维护者,很抱歉打广告,但我觉得它真的很有帮助!)。

您的整个代码将是:

import yagmail
yag = yagmail.SMTP(FROM, 'pass')
yag.send(TO, SUBJECT, TEXT)

请注意,我为所有参数提供了默认值,例如,如果您想发送给自己,则可以省略TO,如果您不想要主题,也可以省略它。

此外,目标还在于使附加 html 代码或图像(和其他文件)变得非常容易。

在放置内容的地方,您可以执行以下操作:

contents = ['Body text, and here is an embedded image:', 'http://somedomain/image.png',
            'You can also find an audio file attached.', '/local/path/song.mp3']

哇,发送附件多么容易!如果没有 yagmail,这将需要 20 行;)

此外,如果您设置一次,则无需再次输入密码(并将其安全存储)。在您的情况下,您可以执行以下操作:

import yagmail
yagmail.SMTP().send(contents = contents)

这更简洁!

我会邀请你看看github或者直接用pip install yagmail.

于 2015-12-07T17:44:36.563 回答
17

有缩进问题。下面的代码将起作用:

import textwrap

def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
    import smtplib
    """this is some test documentation in the function"""
    message = textwrap.dedent("""\
        From: %s
        To: %s
        Subject: %s
        %s
        """ % (FROM, ", ".join(TO), SUBJECT, TEXT))
    # Send the mail
    server = smtplib.SMTP(SERVER)
    server.sendmail(FROM, TO, message)
    server.quit()

于 2015-08-12T06:21:41.007 回答
14

这是一个关于 Python 的示例3.x,比2.x

import smtplib
from email.message import EmailMessage
def send_mail(to_email, subject, message, server='smtp.example.cn',
              from_email='xx@example.com'):
    # import smtplib
    msg = EmailMessage()
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = ', '.join(to_email)
    msg.set_content(message)
    print(msg)
    server = smtplib.SMTP(server)
    server.set_debuglevel(1)
    server.login(from_email, 'password')  # user & password
    server.send_message(msg)
    server.quit()
    print('successfully sent the mail.')

调用这个函数:

send_mail(to_email=['12345@qq.com', '12345@126.com'],
          subject='hello', message='Your analysis has done!')

以下仅适用于中国用户:

如果使用126/163、网易邮箱,需要设置“客户端授权密码”,如下图:

在此处输入图像描述

参考:https ://stackoverflow.com/a/41470149/2803344 https://docs.python.org/3/library/email.examples.html#email-examples

于 2017-11-30T10:59:21.220 回答
5

在函数中缩进代码时(没关系),您还缩进了原始消息字符串的行。但前导空白意味着标题行的折叠(连接),如RFC 2822 - Internet Message Format的 2.2.3 和 3.2.3 节所述:

每个标题字段在逻辑上是单行字符,包括字段名称、冒号和字段正文。然而,为了方便起见,并处理每行 998/78 个字符的限制,标题字段的字段主体部分可以拆分为多行表示;这称为“折叠”。

在您sendmail调用的函数形式中,所有行都以空格开头,因此“展开”(连接)并且您正在尝试发送

From: monty@python.com    To: jon@mycompany.com    Subject: Hello!    This message was sent with Python's smtplib.

除了我们的想法之外,smtplib将不再理解To:andSubject:标头,因为这些名称仅在行首被识别。相反smtplib,将假设一个很长的发件人电子邮件地址:

monty@python.com    To: jon@mycompany.com    Subject: Hello!    This message was sent with Python's smtplib.

这不起作用,所以你的例外。

解决方案很简单:只保留message以前的字符串。这可以通过函数(如 Zeeshan 建议的那样)或立即在源代码中完成:

import smtplib

def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
    """this is some test documentation in the function"""
    message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
    # Send the mail
    server = smtplib.SMTP(SERVER)
    server.sendmail(FROM, TO, message)
    server.quit()

现在展开不会发生,你发送

From: monty@python.com
To: jon@mycompany.com
Subject: Hello!

This message was sent with Python's smtplib.

这就是您的旧代码的工作原理和所做的工作。

请注意,我还保留了标题和正文之间的空行以适应RFC的第 3.5 节(这是必需的),并根据 Python 样式指南PEP-0008(这是可选的)将包含放在函数之外。

于 2016-02-08T05:38:33.063 回答
3

它可能会在您的消息中添加标签。在将消息传递给 sendMail 之前打印出消息。

于 2011-06-07T19:52:47.047 回答
2

确保您已授予发件人和收件人在电子邮件帐户中发送和接收来自未知来源(外部来源)的电子邮件的权限。

import smtplib

#Ports 465 and 587 are intended for email client to email server communication - sending email
server = smtplib.SMTP('smtp.gmail.com', 587)

#starttls() is a way to take an existing insecure connection and upgrade it to a secure connection using SSL/TLS.
server.starttls()

#Next, log in to the server
server.login("#email", "#password")

msg = "Hello! This Message was sent by the help of Python"

#Send the mail
server.sendmail("#Sender", "#Reciever", msg)

在此处输入图像描述

于 2018-12-29T14:51:29.173 回答
1

因为我刚刚弄清楚这是如何工作的,所以我想我会在这里输入我的两个位。

看来您没有在 SERVER 连接设置中指定端口,当我尝试连接到未使用默认端口的 SMTP 服务器时,这对我产生了一点影响:25。

根据 smtplib.SMTP 文档,您的 ehlo 或 helo 请求/响应应自动得到处理,因此您不必担心这一点(但如果所有其他方法都失败,则可能需要确认)。

要问自己的另一件事是您是否允许 SMTP 服务器本身上的 SMTP 连接?对于 GMAIL 和 ZOHO 等网站,您必须实际进入并激活电子邮件帐户中的 IMAP 连接。您的邮件服务器可能不允许不是来自“本地主机”的 SMTP 连接?有什么要调查的。

最后一件事是您可能想尝试在 TLS 上启动连接。大多数服务器现在都需要这种类型的身份验证。

您会看到我在电子邮件中塞入了两个收件人字段。msg['TO'] 和 msg['FROM'] msg 字典项允许正确的信息显示在电子邮件本身的标题中,人们可以在电子邮件的接收端的 To/From 字段中看到这些信息(您甚至可以在此处添加回复字段。收件人和发件人字段本身就是服务器所需要的。我知道我听说过一些电子邮件服务器如果没有正确的电子邮件标头会拒绝电子邮件。

这是我在函数中使用的代码,它可以让我使用本地计算机和远程 SMTP 服务器(如图所示的 ZOHO)通过电子邮件发送 *.txt 文件的内容:

def emailResults(folder, filename):

    # body of the message
    doc = folder + filename + '.txt'
    with open(doc, 'r') as readText:
        msg = MIMEText(readText.read())

    # headers
    TO = 'to_user@domain.com'
    msg['To'] = TO
    FROM = 'from_user@domain.com'
    msg['From'] = FROM
    msg['Subject'] = 'email subject |' + filename

    # SMTP
    send = smtplib.SMTP('smtp.zoho.com', 587)
    send.starttls()
    send.login('from_user@domain.com', 'password')
    send.sendmail(FROM, TO, msg.as_string())
    send.quit()
于 2016-06-10T23:10:28.367 回答
0

另一个使用 gmail 的实现让我们说:

import smtplib

def send_email(email_address: str, subject: str, body: str):
"""
send_email sends an email to the email address specified in the
argument.

Parameters
----------
email_address: email address of the recipient
subject: subject of the email
body: body of the email
"""

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login("email_address", "password")
server.sendmail("email_address", email_address,
                "Subject: {}\n\n{}".format(subject, body))
server.quit()
于 2021-12-22T09:52:04.197 回答
0

值得注意的是,SMTP 模块支持上下文管理器,因此无需手动调用 quit(),这样可以保证即使出现异常也始终调用它。

    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
        server.ehlo()
        server.login(user, password)
        server.sendmail(from, to, body)
于 2020-07-03T10:56:01.230 回答
0
import smtplib, ssl

port = 587  # For starttls
smtp_server = "smtp.office365.com"
sender_email = "170111018@student.mit.edu.tr"
receiver_email = "professordave@hotmail.com"
password = "12345678"
message = """\
Subject: Final exam

Teacher when is the final exam?"""

def SendMailf():
    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)
        print("mail send")
于 2021-09-24T09:27:26.780 回答
0

我对发送电子邮件的软件包选项并不满意,我决定制作并开源我自己的电子邮件发件人。它易于使用并且能够处理高级用例。

安装:

pip install redmail

用法:

from redmail import EmailSender
email = EmailSender(
    host="<SMTP HOST ADDRESS>",
    port=<PORT NUMBER>,
)

email.send(
    sender="me@example.com",
    receivers=["you@example.com"],
    subject="An example email",
    text="Hi, this is text body.",
    html="<h1>Hi,</h1><p>this is HTML body</p>"
)

如果您的服务器需要用户和密码,只需将user_name和传递passwordEmailSender.

我在该send方法中包含了很多功能:

  • 包括附件
  • 将图像直接包含到 HTML 正文中
  • Jinja 模板
  • 开箱即用的更漂亮的 HTML 表格

文档: https ://red-mail.readthedocs.io/en/latest/

源代码:https ://github.com/Miksus/red-mail

于 2022-01-01T19:38:55.390 回答
-1

就您的代码而言,它似乎没有任何根本性的错误,只是不清楚您实际上是如何调用该函数的。我能想到的是,当您的服务器没有响应时,您将收到此 SMTPServerDisconnected 错误。如果你在 smtplib 中查找 getreply() 函数(摘录如下),你就会明白。

def getreply(self):
    """Get a reply from the server.

    Returns a tuple consisting of:

      - server response code (e.g. '250', or such, if all goes well)
        Note: returns -1 if it can't read response code.

      - server response string corresponding to response code (multiline
        responses are converted to a single, multiline string).

    Raises SMTPServerDisconnected if end-of-file is reached.
    """

检查https://github.com/rreddy80/sendEmails/blob/master/sendEmailAttachments.py上的一个示例,该示例还使用函数调用来发送电子邮件,如果这就是您要执行的操作(DRY 方法)。

于 2016-02-12T11:48:49.220 回答