首页 > 解决方案 > 无法通过 Python 中的 SMTP 向 Outlook.com 发送邮件

问题描述

我可以通过 Python 中的 SMTP 将邮件发送到 gmail 帐户。但是,当尝试对 Outlook - office365 执行相同操作时,它会抛出错误。

将邮件发送到 gmail 的代码(工作)

import smtplib
sender_email = "ABC@gmail.com"
rec_email = "ABC@gmail.com"
password = input(str("pwd:"))
message = "hey sent using python"
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(sender_email,password)
print("Login success")
server.sendmail(sender_email,rec_email, message)
print("Email sent to",rec_email)

Outlook 代码(抛出错误)

import smtplib
sender_email = "ABC@companydomain.com"
rec_email = "ABC@companydomain.com"
password = input(str("pwd:"))
message = "hey sent using python"
server = smtplib.SMTP('smtp.outlook.com',587)
server.starttls()
server.login(sender_email,password)
print("Login success")
server.sendmail(sender_email,rec_email, message)
print("Email sent to",rec_email )

运行上述 Outlook 代码时出现以下错误:

Traceback (most recent call last):
File "C:/Users/ABC/Python/Python37/pythonmail.py", line 32, in <module>
  server.login(sender_email,password)
File "C:\Users\ABC\Python\Python37\lib\smtplib.py", line 730, in login
  raise last_exception
File "C:\Users\ABC\Python\Python37\lib\smtplib.py", line 721, in login
  initial_response_ok=initial_response_ok)
File "C:\Users\ABC\Python\Python37\lib\smtplib.py", line 642, in auth
  raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, b'5.7.3 Authentication unsuccessful 
  [BM1PR01CA0154.INDPRD01.PROD.OUTLOOK.COM]')

我什至浏览了以下链接:

[https://stackoverflow.com/questions/57203843/unable-to-send-mail-in-python-on-outlook-with-the-smtplib][1]

[https://www.pythonanywhere.com/forums/topic/1961/][2]

[https://stackoverflow.com/questions/66061531/send-mail-from-alias-mail-id-using-python-smtplib][2]

有人可以帮我解决错误吗?

同时,以下代码适用于 gmail 和使用 win32com.client 的 Outlook。但我想用 SMTP lib 来做。请帮助

import win32com.client as client
outlook = client.Dispatch("Outlook.Application")
message = outlook.CreateItem(0)
message.Display()
message.To = 'ABC@domain.com'
message.subject = 'Test Mail'
message.body = 'Sending a test mail :)'
message.send
print("mail sent successfully")

标签: pythonemailsmtplib

解决方案


尝试不提供端口号和密码。有效。

import smtplib
sender_email = "test_mail@company.com"
rec_email = ["ABC@company.com"]
message = "hey sent using python"
server = smtplib.SMTP('smtp.corp.company.com')
print("Login success")
server.sendmail(sender_email,rec_email, message)
print("Email sent to",rec_email )

推荐阅读