首页 > 解决方案 > office365上的两步认证

问题描述

我下面的代码用于自动向某些客户发送电子邮件,

但是今天,我们有MFA(2 step verification)我的office365帐户,每次我登录我的Outlook时,Outlook都会向我发送代码,另外只需使用我的电子邮件密码。

这很烦人,我试图用谷歌搜索错误代码,但没有找到任何东西。

我想知道有人可能有同样的问题,所以我在这里发布这个问题

def send_mail(send_to, subject, text, files=None):
    assert isinstance(send_to, list)

    msg = MIMEMultipart()
    msg['From'] = USERNAME
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(MIMEText(text))

    for f in files or []:
        with open(f, "rb") as fil:
            part = MIMEApplication(
                fil.read(),
                Name=basename(f)
            )
        # After the file is closed
        part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
        msg.attach(part)


    server = smtplib.SMTP('smtp.office365.com')
    #server.ehlo_orhelo_if_needed()
    server.starttls()
    #server.ehlo_or_helo_if_needed()
    server.login(USERNAME,PASSWORD)
    server.sendmail(USERNAME, send_to, msg.as_string())
    server.close()
%%time
send_mail( send_to,
        subject,
        text,
        files )
print("email sent")
---------------------------------------------------------------------------
SMTPAuthenticationError                   Traceback (most recent call last)
<ipython-input-12-fd2296e1a0ed> in <module>
      2         subject,
      3         text,
----> 4         files )

<ipython-input-11-aa257f0c232c> in send_mail(send_to, subject, text, files)
     25     server.starttls()
     26     #server.ehlo_or_helo_if_needed()
---> 27     server.login(USERNAME,PASSWORD)
     28     server.sendmail(USERNAME, send_to, msg.as_string())
     29     server.close()

~\Anaconda3\lib\smtplib.py in login(self, user, password, initial_response_ok)
    728 
    729         # We could not login successfully.  Return result of last attempt.
--> 730         raise last_exception
    731 
    732     def starttls(self, keyfile=None, certfile=None, context=None):

~\Anaconda3\lib\smtplib.py in login(self, user, password, initial_response_ok)
    719                 (code, resp) = self.auth(
    720                     authmethod, getattr(self, method_name),
--> 721                     initial_response_ok=initial_response_ok)
    722                 # 235 == 'Authentication successful'
    723                 # 503 == 'Error: already authenticated'

~\Anaconda3\lib\smtplib.py in auth(self, mechanism, authobject, initial_response_ok)
    640         if code in (235, 503):
    641             return (code, resp)
--> 642         raise SMTPAuthenticationError(code, resp)
    643 
    644     def auth_cram_md5(self, challenge=None):

SMTPAuthenticationError: (535, b'5.7.3 Authentication unsuccessful [HK2PR0401CA0006.apcprd04.prod.outlook.com]')

标签: pythonoutlook

解决方案


推荐阅读