使用Python实现Office 365邮件自动化遇多种错误求助
Office 365企业版账号邮件自动化问题排查求助
我尝试了三种Python实现Office 365邮件自动化的方案,均出现不同错误。公司使用企业版Office 365账号,这可能是问题诱因之一。以下是具体方案及对应错误:
方案1:使用smtplib发送邮件
def send_email(): try: # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['From'] = mail_from msg['To'] = mail_to msg['Subject'] = mail_subject # see the code below to use template as body body_text = mail_body_text body_html = mail_body_html # Create the body of the message (a plain-text and an HTML version). # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(body_text, 'plain') part2 = MIMEText(body_html, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) # Send the message via local SMTP server. mail = smtplib.SMTP("smtp.outlook.office365.com", 587, timeout=20) # if tls = True mail.starttls() recepient = [mail_to] mail.login(username, __password) mail.sendmail(mail_from, recepient, msg.as_string()) mail.quit() except Exception as e: raise e
错误信息:
smtplib.SMTPAuthenticationError: (535, b'5.7.139 Authentication unsuccessful, the user credentials were incorrect. [MN2PR11CA0027.namprd11.prod.outlook.com]')
方案2:使用O365库
def maybe_this(): credentials = (username, __password) account = Account(credentials) #Account object from O365.Account. m = account.new_message() m.to.add(mail_to) m.subject = mail_subject m.body = mail_body_html m.send()
错误信息:
RuntimeError: No auth token found. Authentication Flow needed
方案3:针对方案2错误调整后的代码
def maybe_that(): # SPOILER ALERT: It doesn't frigging work. credentials = (username, __password) my_auth_flow_type = 'public' my_token_path = '(path to my python package)' my_token_backend = 'my_token.txt' account = Account(credentials, auth_flow_type=my_auth_flow_type, token_path=my_token_path, token_backend=my_token_backend) m = account.new_message() m.to.add(mail_to) m.subject = mail_subject m.body = mail_body_html m.send()
错误信息:
ValueError: Provide client id only for public flow credentials
恳请协助排查问题,谢谢!
内容的提问来源于stack exchange,提问作者Guitar Geek
相关产品推荐
相关产品推荐

