Python发邮件的代码以下:python
只须要填写好加粗字体,便可正常使用。服务器
from exchangelib import DELEGATE, Account, Credentials, Message, Mailbox, HTMLBody def Email(to, subject, body): creds = Credentials( username='xxxxxx', password='xxxxxx' ) account = Account( primary_smtp_address='xxx@xxx.com', credentials=creds, autodiscover=True, access_type=DELEGATE ) m = Message( account=account, subject=subject, body=HTMLBody(body), to_recipients = [Mailbox(email_address=to)] ) m.send() Email("xxx@xxx.com", "abc", "def")
可是若是Python环境安装有瑕疵,则报错以下:post
$python3 ab.py
Traceback (most recent call last): File "ab.py", line 22, in <module> Email("xxx@xxx.com", "abc", "def") File "ab.py", line 12, in Email access_type=DELEGATE File "/usr/local/lib/python3.5/site-packages/exchangelib/account.py", line 66, in __init__ credentials=credentials) File "/usr/local/lib/python3.5/site-packages/exchangelib/autodiscover.py", line 214, in discover email=email) File "/usr/local/lib/python3.5/site-packages/exchangelib/autodiscover.py", line 236, in _try_autodiscover return _try_autodiscover(e.server, credentials, email) File "/usr/local/lib/python3.5/site-packages/exchangelib/autodiscover.py", line 262, in _try_autodiscover raise_from(AutoDiscoverFailed('All steps in the autodiscover protocol failed'), None) File "/usr/local/lib/python3.5/site-packages/future/utils/__init__.py", line 398, in raise_from exec(execstr, myglobals, mylocals) File "<string>", line 1, in <module> exchangelib.errors.AutoDiscoverFailed: All steps in the autodiscover protocol failed
至今仍无解。字体
好在我有台机器安装Python3.5.2正常,执行上述彻底没有问题。this
今天终于搞定!!! 2017-12-11
exchange的版本不对,
我本机版本:
pip3 search exchangelib
exchangelib (1.10.6) - Client for Microsoft Exchange Web Services (EWS) INSTALLED: 1.9.4 LATEST: 1.10.6 服务器版本为: $pip3 search exchangelib exchangelib (1.10.6) - Client for Microsoft Exchange Web Services (EWS) INSTALLED: 1.10.4 LATEST: 1.10.6 要作的就是把服务器上的版本下降到1.9.4,就🆗了。 pip3 install exchangelib==1.9.4 再次执行发邮件的操做,bingo,搞定! 多谢大管家【jason.wu】
若是想发送邮件的时候带附件,spa
myfile = FileAttachment(name='report.pdf', content=open('/data/graph/report.pdf','rb').read()) m.attach(myfile)
谢谢!code