I am trying to send an email from my office365 corporate account using python. I am new to python. This code previously worked when using my hotmail account, however now that I
The code has slightly changed. The above code won't work. Please use the below code. Reference
from O365 import Account
credentials = ('client_id', 'client_secret')
account = Account(credentials)
m = account.new_message()
m.to.add('to_example@example.com')
m.subject = 'Testing!'
m.body = "George Best quote: I've stopped drinking, but only while I'm asleep."
m.send()
I found a library that it's working for me:
https://github.com/O365/python-o365
https://pypi.python.org/pypi/O365
Install it using PIP and then:
from O365 import Message
o365_auth = ('YourAccount@office365.com','YourPassword')
m = Message(auth=o365_auth)
m.setRecipients('reciving@office365.com')
m.setSubject('I made an email script.')
m.setBody('Talk to the computer, cause the human does not want to hear it any more.')
m.sendMessage()
Well, you are almost there. The following code will do the trick:
import smtplib
mailserver = smtplib.SMTP('smtp.office365.com',587)
mailserver.ehlo()
mailserver.starttls()
mailserver.login('user@company.co', 'password')
mailserver.sendmail('user@company.co','user@company.co','python email')
mailserver.quit()
Use the following links for more information:
http://www.aventistech.com/2016/03/07/python-send-email-via-office-365-tls/
https://docs.python.org/3/library/smtplib.html
https://gist.github.com/jasonjoh/3ec367594c3fa662ee983a617bdc7deb
Most likely, the problem is not in your code, but in the Exchange Online configuration.
I bet 535 5.7.3 Authentication unsuccessful
is thrown because authenticated SMTP (SMTP AUTH protocol) is disabled in your Exchange Online organization.
Here you can find my answer explaining how you can enable SMTP AUTH for the user you are sending emails from. You have to be an Office 365 org admin to do that, or you can ask your administrator for help.
After that mailserver.starttls()
should work. Notice that you don't need to specify a certificate in that call.