我也是被坑了好久才发现。
解决方法:
经过多次测试发现MIMEText()["to"]的数据类型与sendmail(from_addrs,to_addrs,...)的to_addrs不同; 前者为str类型,多个地址使用逗号分隔,后者为list类型。
原本有问题的代码:
def send_mail_attach(receivers, mail_subject, mail_body, pattern="html"): import smtplib from email.mime.text import MIMEText # 设置服务器所需信息 # 163邮箱服务器地址 mail_host = 'hwhzsmtp.qiye.163.com' # 163用户名 mail_user = 'wang123@xxx.one' # 密码(部分邮箱为授权码) mail_pass = '1234567' # 邮件发送方邮箱地址 sender = 'wang123@xxx.one' # 邮件接受方邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发 # 设置email信息 # 邮件内容设置 message = MIMEText(mail_body, pattern, 'utf-8') # 邮件主题 message['Subject'] = mail_subject # 发送方信息 message['From'] = '%s <%s>' % (Header('hours report').encode(), sender) # 接受方信息 if not isinstance(receivers,list): receivers=[receivers] message['To'] = ','.join(receivers) # 登录并发送邮件 try: # smtpObj = smtplib.SMTP(mail_host,25) smtpObj = smtplib.SMTP_SSL(mail_host, 994) # 连接到服务器 # smtpObj.starttls() # smtpObj.ehlo() # 登录到服务器 smtpObj.login(mail_user, mail_pass) # 发送 smtpObj.sendmail( sender, receivers, message.as_string()) # 退出 smtpObj.quit() print('success') except smtplib.SMTPException as e: print('error', e) # 打印错误
经过修改之后的代码如下:
def send_email(mail_subject, mail_body, receivers='wqbin@xxx.one', pattern='plain'): # 设置服务器所需信息 # 163邮箱服务器地址 mail_host = 'hwhzsmtp.qiye.163.com' # 163用户名 mail_user = 'wang123@xxx.one' # 密码(部分邮箱为授权码) mail_pass = '123456' # 邮件发送方邮箱地址 sender = 'wang123@xxx.one' # 邮件接受方邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发 # 设置email信息 # 邮件内容设置 message = MIMEText(mail_body, pattern, 'utf-8') # 邮件主题 message['Subject'] = mail_subject # 发送方信息 message['From'] = '%s' % sender # 接受方信息 # 此处只能填写''',+str''' message['To'] = ','.join(receivers) if isinstance(receivers,list) else receivers # 登录并发送邮件 try: # smtpObj = smtplib.SMTP(mail_host,25) smtpObj = smtplib.SMTP_SSL(mail_host, 994) # 连接到服务器 # smtpObj.starttls() # smtpObj.ehlo() # 登录到服务器 smtpObj.login(mail_user, mail_pass) # 发送 # 此处填写 list格式 if not isinstance(receivers,list): receivers=receivers.split(",") smtpObj.sendmail( sender, receivers, message.as_string()) # 退出 smtpObj.quit() print('success') except smtplib.SMTPException as e: print('error', e) # 打印错误 except Exception as e: print('其他错误',e)
完结!!