报错信息如下:
将发送人邮箱也加入收件人地址中即可解决报错。
更改之前代码:
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.application import MIMEApplication
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
sender = '[email protected]' # 发件人地址
receive = '[email protected]' # 收件人地址
passwd = 'XXX' # 授权码
mailserver = 'smtp.163.com'
port = '465'
sub = 'TEST RESULT' # 邮件主题
try:
msg = MIMEMultipart('related')
msg['From'] = formataddr(["ME", sender])
msg['To'] = formataddr(["YOU", receive])
msg['Subject'] = sub
txt = MIMEText('This is your test result!', 'plain', 'utf-8')
msg.attach(txt)
# 添加附件,以txt为例,可以改成其他文件格式
attach = MIMEApplication(open("D:\xx\hi.txt").read())
attach.add_header('Content-Disposition', 'attachment', filename='hi.txt')
msg.attach(attach)
server = smtplib.SMTP_SSL(mailserver, port)
server.login(sender, passwd)
server.sendmail(sender, receive, msg.as_string())
server.quit()
更改后:
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.application import MIMEApplication
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
sender = '[email protected]' # 发件人地址
receive = '[email protected],[email protected]' # 收件人地址
passwd = 'XXX' # 授权码
mailserver = 'smtp.163.com'
port = '465'
sub = 'TEST RESULT' # 邮件主题
try:
msg = MIMEMultipart('related')
msg['From'] = formataddr(["ME", sender])
msg['To'] = formataddr(["YOU,ME", receive])
msg['Subject'] = sub
txt = MIMEText('This is your test result!', 'plain', 'utf-8')
msg.attach(txt)
# 添加附件,以txt为例,可以改成其他文件格式
attach = MIMEApplication(open("D:\xx\hi.txt").read())
attach.add_header('Content-Disposition', 'attachment', filename='hi.txt')
msg.attach(attach)
server = smtplib.SMTP_SSL(mailserver, port)
server.login(sender, passwd)
server.sendmail(sender, receive, msg.as_string())
server.quit()