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 have a need to send confidential information, I must use my corporate email.
I have tried a couple things.
535 5.7.3 Authentication unsuccessful
I am unclear on the certificate part, but my steps include, looking online to find out how to export a certificate. Using chrome browser, microsoftonline.com has a chain certificate. I can export the root and the level just below the root but not the last level. I dont know how to pass both of these files, so I have simply passed the root certificate. At this point I get the error: ssl.SSLError: [SSL] PEM lib (_ssl.c:3309)
i got stuck at this point. Any help is appreciated. Code used below
import smtplib mailserver = smtplib.SMTP('smtp.office365.com',587) mailserver.ehlo() mailserver.starttls(certfile='office365.cer') mailserver.ehlo() mailserver.login('[email protected]', 'password') mailserver.sendmail('[email protected]','[email protected]','python email') mailserver.quit()
Requirements for Setting Up SMTP RelayThe sending application (the on-premises email server) must support TLS, connect to the Office 365 servers on port 587 (the SMTP port for Office 365 with encryption enabled), and authenticate with Office 365. A valid certificate must be used.
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('[email protected]', 'password') #Adding a newline before the body text fixes the missing message body mailserver.sendmail('[email protected]','[email protected]','\npython 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
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 = ('[email protected]','YourPassword') m = Message(auth=o365_auth) m.setRecipients('[email protected]') 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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With