通过 Office 365 公司帐户从 Python 发送电子邮件



我正在尝试通过 Python 从我的 Office 365 公司帐户向另一个 Office 365 公司帐户发送电子邮件。目标是在脚本成功运行后发送电子邮件。

我已经检查了电子邮件ID和密码,但是,似乎无法弄清楚问题是什么。

import smtplib
message = "Execution Successful"
mailserver = smtplib.SMTP('smtp.office365.com',587)
mailserver.ehlo()
mailserver.starttls()
mailserver.login('userid@corporateemail.com', 'password')
mailserver.sendmail('userid@corporateemail.com', 'userid@corporateemail.com', message)
mailserver.quit()

这应该会触发发送给用户的电子邮件。但是,它给出了一条错误消息。 这是输出:

Traceback (most recent call last):
File "<ipython-input-45-663ff7ed4e61>", line 1, in <module>
runfile('C:/Users/qy115/Desktop/Updated Python/Test/EmailTest.py', wdir='C:/Users/qy115/Desktop/Updated Python/Test')
File "C:SoftwareEng_APPSAnaconda3libsite-packagesspyderutilssitesitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "C:SoftwareEng_APPSAnaconda3libsite-packagesspyderutilssitesitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/qy115/Desktop/Updated Python/Test/EmailTest.py", line 20, in <module>
mailserver.starttls()
File "C:SoftwareEng_APPSAnaconda3libsmtplib.py", line 752, in starttls
(resp, reply) = self.docmd("STARTTLS")
File "C:SoftwareEng_APPSAnaconda3libsmtplib.py", line 420, in docmd
return self.getreply()
File "C:SoftwareEng_APPSAnaconda3libsmtplib.py", line 390, in getreply
+ str(e))
SMTPServerDisconnected: Connection unexpectedly closed: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

我正在尝试做同样的事情。我认为您不能再使用用户名和密码通过 Office 365 进行身份验证。您必须遵循以下说明,据我了解,这些说明要求您通过 Azure 服务中的安全应用程序连接到 Office 365 Microsoft:

https://pypi.org/project/O365/#different-authentication-interfaces

但是,我已经设法进行身份验证,无法检索所需的令牌以进入我的帐户并发送电子邮件。也许你会有更好的成功?如果有人成功地完成了此操作,请告诉我们,因为我无法解决。

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
mail_content = "Hello, This is a simple mail. There is only text, no 
attachments are there The mail is sent using Python SMTP library"
#The mail addresses and password
sender_address = 'userid@corporateemail.com'
sender_pass = 'XXXXXXXXX'
receiver_address = 'userid@corporateemail.com'
#Setup the MIME
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = 'A test mail sent by Python. It has an attachment.'   
#The subject line
#The body and the attachments for the mail
message.attach(MIMEText(mail_content, 'plain'))
#Create SMTP session for sending the mail
session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port
session.starttls() #enable security
session.login(sender_address, sender_pass) #login with mail_id and password
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()
print('Mail Sent')

最新更新