此代码可以正常工作,并向我发送一封邮箱:

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()

但是,如果我try 将其包装成这样的函数:

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

有人能告诉我为什么吗?

推荐答案

我建议您一起使用标准包emailsmtplib来发送邮箱.请看下面的例子(转载自Python documentation).请注意,如果遵循此方法,"简单"任务确实很简单,而更复杂的任务(如附加二进制对象或发送纯文本/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 documentation中的示例进行操作:

# 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()

如您所见,MIMEText对象中的头To必须是由逗号分隔的邮箱地址组成的字符串.另一方面,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)部分构成列表中的一个字符串,用逗号分隔.

从你们的问题来看,我推断你们还没有通过the Python tutorial级考试——如果你想在Python中取得任何进展,这是必须的——对于标准库来说,这些文档基本上是非常优秀的.

Python相关问答推荐

使用子字符串动态更新Python DataFrame中的列

Python中的锁定类和线程以实现dict移动

如何在telegram 机器人中发送音频?

跟踪我已从数组中 Select 的样本的最有效方法

为什么tkinter框架没有被隐藏?

将数据框架与导入的Excel文件一起使用

如何将Docker内部运行的mariadb与主机上Docker外部运行的Python脚本连接起来

用NumPy优化a[i] = a[i-1]*b[i] + c[i]的迭代计算

使用setuptools pyproject.toml和自定义目录树构建PyPi包

如果值发生变化,则列上的极性累积和

对象的`__call__`方法的setattr在Python中不起作用'

把一个pandas文件夹从juyter笔记本放到堆栈溢出问题中的最快方法?

NumPy中条件嵌套for循环的向量化

Odoo 16使用NTFS使字段只读

Pandas—在数据透视表中占总数的百分比

如何指定列数据类型

考虑到同一天和前2天的前2个数值,如何估算电力时间序列数据中的缺失值?

ruamel.yaml dump:如何阻止map标量值被移动到一个新的缩进行?

使用Openpyxl从Excel中的折线图更改图表样式

Odoo16:模板中使用的docs变量在哪里定义?