我正在尝试通过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:\Software\Eng_APPS\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "C:\Software\Eng_APPS\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.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:\Software\Eng_APPS\Anaconda3\lib\smtplib.py", line 752, in starttls
(resp, reply) = self.docmd("STARTTLS")
File "C:\Software\Eng_APPS\Anaconda3\lib\smtplib.py", line 420, in docmd
return self.getreply()
File "C:\Software\Eng_APPS\Anaconda3\lib\smtplib.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
答案 0 :(得分:1)
我正在尝试做同样的事情。我认为您无法再使用用户名和密码通过Office 365进行身份验证。您必须按照以下说明进行操作,据我了解,这些要求要求您通过Microsoft Azure服务中的安全应用程序连接到Office 365:
https://pypi.org/project/O365/#different-authentication-interfaces
但是,我设法进行了身份验证,但是无法检索所需的令牌才能进入我的帐户并发送电子邮件。也许您会有更好的成功?如果有人成功完成了此操作,请告诉我们,因为我无法解决。
答案 1 :(得分:-1)
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')