我正在尝试使用python脚本发送邮件。我没有依恋就尝试过它。
现在我尝试使用附件我收到了断言错误。
以下是代码:
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os
import time
import random
msg_from = "xyz@abc.com"
to = "xyz@abc.com"
text = "test-Hello"
subject = "Test"
f = "output1.pdf"
def generate_message_id(msg_from):
domain = msg_from.split("@")[1]
r = "%s.%s" % (time.time(), random.randint(0, 100))
mid = "<%s@%s>" % (r, domain)
return mid
def send_mail(msg_from, to, subject, text,
files=[],server="10.10.10.10", debug=False):
assert type(to)==list
assert type(files)==list
msg = MIMEMultipart()
msg['From'] = msg_from
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
text = text.encode("utf-8")
text = MIMEText(text, 'plain', "utf-8")
msg.attach(text)
msg.add_header('Message-ID', generate_message_id(msg_from))
for file in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(f,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'
for file in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(f,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'
% os.path.basename(file))
msg.attach(part)
if not debug:
smtp = smtplib.SMTP(server)
smtp.sendmail(msg_from, to, msg.as_string())
smtp.close()
return msg
send_mail(msg_from, to, subject, text,files=[],server="10.10.10.10", debug=False)
我得到的错误:
Traceback (most recent call last):
File "testmail1.py", line 53, in <module>
send_mail(msg_from, to, subject, text,files=[],server="10.10.10.10", debug=False)
File "testmail1.py", line 24, in send_mail
assert type(to)==list
AssertionError
我使用的是linux os并使用python 2.7
请帮我解决
答案 0 :(得分:3)
您的to
字段应该是一个列表,因为理论上您可以将您的电子邮件发送给多个人。所以我建议:
to = ["xyz@abc.com"]
send_mail
方法首先检查您的to
字段是否为列表,这就是您收到错误的原因。
另请查看documentation