简体   繁体   中英

Not able to Send mail to Outlook.com via SMTP in Python

I am able to send the mail to gmail account via SMTP in Python. But when tried doing the same for Outlook - office365, it is throwing the error.

Code to send mail to gmail (working)

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)

code for Outlook(throwing error)

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 )

The following error occurs when i run the above outlook code:

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]')

i even went through the following links:

[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]

Can somebody help me on how to fix the error??

Meanwhile the below code worked for both gmail and outlook using win32com.client. But i want to do it with SMTP lib. Kindly help

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")

Tried by not giving port number and password. It worked.

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM