错误代码:
class SendFileMailThread(threading.Thread):
"""
异步发送带附件的邮件
"""
def __init__(self, subject, content, recipient_list, file_dict_list=None):
"""
:param subject:
:param content:
:param recipient_list:
:param file_dict_list: [{
"fileName": "",
"filePath": ""
}]
"""
self.read_config = ReadConfig()
self.subject = subject
self.content = content
self.from_email = self.read_config.get_email("EMAIL_HOST_USER")
self.recipient_list = recipient_list
self.file_dict_list = file_dict_list
threading.Thread.__init__(self)
def run(self):
subject = self.subject,
message = self.content,
from_email = self.from_email, # 发件人
recipient_list = self.recipient_list, # 收件人
html_message = self.content,
msg = EmailMultiAlternatives(subject=subject, body=content, from_email=from_email, to=recipient_list)
msg.attach_alternative(content=content, mimetype="text/html")
# add attachment
if self.file_dict_list:
for file_ in self.file_dict_list:
file_name = os.path.basename(file_["fileName"])
# 对文件进行编码处理
b = make_header([(file_name, 'utf-8')]).encode('utf-8')
with open(file_["filePath"], "rb") as fp:
msg.attach(b, fp.read()) # 传入文件名和附件
msg.send()
代码运行后一直报错:
/xxx/xxx/python3.9/site-packages/django/core/mail/message.py", line 96, in sanitize_address
nm, address = addr
ValueError: not enough values to unpack (expected 2, got 1)
最后发现原因是:在def run(self)中, 下列代码赋值后,全都变成了tuple类型。
PS:复制的时候把逗号也复制了,导致赋值错误。
subject = self.subject,
message = self.content,
from_email = self.from_email, # 发件人
recipient_list = self.recipient_list, # 收件人
html_message = self.content,
正确代码:去掉逗号,或者直接用self赋值
class SendFileMailThread(threading.Thread):
"""
异步发送带附件的邮件
"""
def __init__(self, subject, content, recipient_list, file_dict_list=None):
"""
:param subject:
:param content:
:param recipient_list:
:param file_dict_list: [{
"fileName": "",
"filePath": ""
}]
"""
self.read_config = ReadConfig()
self.subject = subject
self.content = content
self.from_email = self.read_config.get_email("EMAIL_HOST_USER")
self.recipient_list = recipient_list
self.file_dict_list = file_dict_list
threading.Thread.__init__(self)
def run(self):
# subject = self.subject
# message = self.content
# from_email = self.from_email # 发件人
# recipient_list = self.recipient_list # 收件人
# html_message = self.content
msg = EmailMultiAlternatives(subject=self.subject, body=self.content, from_email=self.from_email, to=self.recipient_list, headers={'Message-ID': 'foo'})
msg.attach_alternative(content=self.content, mimetype="text/html")
# add attachment
if self.file_dict_list:
for file_ in self.file_dict_list:
file_name = os.path.basename(file_["fileName"])
# 对文件进行编码处理
b = make_header([(file_name, 'utf-8')]).encode('utf-8')
with open(file_["filePath"], "rb") as fp:
msg.attach(b, fp.read()) # 传入文件名和附件
msg.send()
|