python smtplib office365邮箱发送邮件问题

  • l
    lilarcor
    请教一下,office 365 帐号开启了多重验证,现在发邮件就报错了,用python3怎么处理呢?smtplib.SMTPAuthenticationError: (535, b'5.7.3 Authentication unsuccessful [HK0PR03CA0111.apcprd03.prod.outlook.com]')


    1. #!/usr/bin/env python3
    2. # coding: utf-8


    3. import smtplib # 加载smtplib模块
    4. from email.mime.text import MIMEText
    5. from email.utils import formataddr
    6. from email.mime.multipart import MIMEMultipart
    7. from email.mime.application import MIMEApplication
    8. import time

    9. class SendMail(object):
    10. def __init__(self,sender,title,content):
    11. self.sender = sender #发送地址
    12. self.title = title # 标题
    13. self.content = content # 发送内容
    14. self.sys_sender = '[email protected]' # 系统账户
    15. self.sys_pwd = '123456' # 系统账户密码

    16. def send(self,file_list):
    17. """
    18. 发送邮件
    19. :param file_list: 附件文件列表
    20. :return: bool
    21. """
    22. try:
    23. # 创建一个带附件的实例
    24. msg = MIMEMultipart()
    25. # 发件人格式
    26. msg['From'] = formataddr(["", self.sys_sender])
    27. # 收件人格式
    28. msg['To'] = formataddr(["", self.sender])
    29. # 邮件主题
    30. msg['Subject'] = self.title

    31. # 邮件正文内容
    32. msg.attach(MIMEText(self.content, 'plain', 'utf-8'))

    33. # 多个附件
    34. for file_name in file_list:
    35. print("file_name",file_name)
    36. # 构造附件
    37. xlsxpart = MIMEApplication(open(file_name, 'rb').read())
    38. # filename表示邮件中显示的附件名
    39. xlsxpart.add_header('Content-Disposition','attachment',filename = '%s'%file_name)
    40. msg.attach(xlsxpart)

    41. # SMTP服务器
    42. server = smtplib.SMTP("smtp.office365.com", 587,timeout=10)
    43. server.ehlo()
    44. server.starttls()
    45. # 登录账户
    46. server.login(self.sys_sender, self.sys_pwd)
    47. # 发送邮件
    48. server.sendmail(self.sys_sender, [self.sender, ], msg.as_string())
    49. # 退出账户
    50. server.quit()
    51. return True
    52. except Exception as e:
    53. print(e)
    54. return False

    55. if __name__ == '__main__':
    56. # 发送地址
    57. sender = "[email protected]"
    58. # 标题
    59. title = "测试告警"
    60. # 开始时间
    61. start_time = time.strftime('%Y-%m-%d %H:%M:%S')
    62. ip = "xx.xx.xx.xx"
    63. # 发送内容
    64. content = "{} ip: {} 掉线".format(start_time,ip)
    65. # 附件列表
    66. file_list = []
    67. ret = SendMail(sender, title, content).send(file_list)
    68. print(ret,type(ret))

    69. ##原文链接:https://blog.csdn.net/shykevin/java/article/details/106633036
    复制代码
  • F
    FQX
    应该可以生成设备专用密码? iOS fly ~
  • l
    lilarcor
    目前我是这样处理了,但是不方便,安全性也不大好。我再看看能否用otp或app iOS fly ~