My code below is used to automatically sending emails to some clients,
but today, we have MFA(2 step verification) on my office365 account, which is Outlook will send me the code every time I login in my Outlook in addition just use my email password.
This is annoying, I tried to google the error code, but nothing is found.
I am wondering someone may have the same problem, so I post this question here
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]')