Ⅰ 用python調用outlook發郵件的問題
我把你的錯誤信息列印出來。''這個意思是「已終止操作」
現在看來是com出了錯誤。我沒有調 過outlook。不過我覺著應該可以成功。因為COM介面的文檔少。
你可以先從VBA文檔 里學習一下這個介面。再找一些C++調用outlook的例子。
下面是我從網上找的一個例子。僅供參考
#!/usr/bin/envpython
"""
Asimpleaddressbookbrowser.Descendintothedepthsof
list.Thenextractthosecontacts!
NOTE:.
MailMessages
-------------
InMSDN,"Messagingand
Collaboration","CollaborationDataObjects","CDOfor
Windows2000","CDOforWindows2000","Messaging",
"Concepts","CDOMessagingCOMInterfaces","TheIMessage
COMInterface","IMessageProperties".
Unfortunately,.
Indeed,the'gen_py'directoryinside'site-packages'maybe
.
SavedItems
-----------
typedefenum{
olTXT=0,
olRTF=1,
olTemplate=2,
olMSG=3,
olDoc=4,
olHTML=5,
olVCard=6,
olVCal=7
}OlSaveAsType;
.
.
.
.
"""
importwin32com.client
importsys,os
#.
outlook=win32com.client.Dispatch("Outlook.Application")
classView:
"Aviewontonamespaces."
def__init__(self,encoding):
"'encoding'."
self.encoding=encoding
classConsoleView(View):
"Aconsole-styleview."
show_namespace_property_mapping={
win32com.client.constants.olFolder:
("+","Name"),
win32com.client.constants.olContact:
(">","Email1Address"),
win32com.client.constants.olMail:
(">","Subject"),
None:
("?","Name")
}
def__init__(self,encoding,page_width=80,page_limit=20):
"""
'encoding'andtheoptional
'page_width'and'page_limit'.
"""
View.__init__(self,encoding)
self.page_width=page_width
self.page_limit=page_limit
defupdate_status(self,counter,max_value):
"'counter'valueand'max_value'."
last_counter=max(counter-1,0)
last_width=int((last_counter*self.page_width)/max_value)
width=int((counter*self.page_width)/max_value)
sys.stdout.write("."*(width-last_width))
ifcounter==max_value:
sys.stdout.write(" ")
deferror(self):
sys.stdout.write("!")
defshow_namespace(self,items):
"Showthenamespace,givenalistof'items'."
iflen(items)>self.page_limit:
print"!","Showingthefirst",self.page_limit,"itemsonly."
forvalueinitems[:self.page_limit]:
try:
decoration,property=self.show_namespace_property_mapping[value.Class]
exceptKeyError:
decoration,property=self.show_namespace_property_mapping[None]
printdecoration,self.get_property(value,property).encode(self.encoding)
defget_property(self,object,property,default=""):
try:
#NOTE:Hack!
ifproperty=="SentOn":
returngetattr(object,property).Format()
returngetattr(object,property)
exceptAttributeError:
returndefault
classExtractor:
"/objectsfromfolders."
extract_type_mapping={
win32com.client.constants.olAppointment:
(win32com.client.constants.olVCal,"vcs"),
win32com.client.constants.olContact:
(win32com.client.constants.olVCard,"vcf"),
win32com.client.constants.olMail:
(win32com.client.constants.olTXT,"txt"),
None:
(win32com.client.constants.olTXT,"txt")
}
def__init__(self,view=None):
"'view'."
self.view=view
defextract(self,items,filename):
"Extractthegiven'items'toafilewiththegiven'filename'."
total_number=len(items)
foriinrange(0,total_number):
value=items[i]
try:
save_as_type,suffix=self.extract_type_mapping[value.Class]
exceptKeyError:
save_as_type,suffix=self.extract_type_mapping[None]
try:
value.SaveAs(os.path.join(filename,str(i)+"."+suffix),
save_as_type)
exceptAttributeError:
ifself.view:
self.view.error()
exceptwin32com.client.pywintypes.com_error:
ifself.view:
self.view.error()
ifself.view:
self.view.update_status(i+1,total_number)
classExplorer:
"."
def__init__(self,view=None):
globaloutlook
self.current=self.ns=outlook.GetNamespace("MAPI")
self.view=view
self._get_namespace()
defup(self):
"."
ifself.current!=self.ns:
self.current=self.current.Parent
self._get_namespace()
return1
return0
defdown(self,name):
"""
'name'returningwhetherit
couldbedone.
"""
ifself.choices.has_key(name):
self.current=self.choices[name]
self._get_namespace()
return1
return0
defget_items(self):
"."
returnself.items
defget_choices(self):
"."
returnself.choices
def_get_namespace(self):
"""
.
"""
self.choices,self.items=get_namespace(self.current,self.view)
defget_namespace(namespace,view=None):
"""
Getthecontentsofthegiven'namespace',returningadictionaryof
choices(appropriateforfolders)andalistofitems(appropriatefor
messages).
"""
d={}
l=[]
#Firsttrylookingforfolders.Thenlookforitems.Andsoon.
forpropertiesin(("Folders","Name"),("Items",None)):
#:folders,items,etc.
object_name=properties[0]
try:
subobject=getattr(namespace,object_name)
exceptAttributeError:
#
#thenextiteration.
continue
#.
#Cannotsliceitems,.
total_number=len(subobject)
foriinrange(1,total_number+1):
try:
field_name=properties[1]
#,if
#specified.
l.append(subobject[i])
iffield_nameisnotNone:
d[getattr(subobject[i],field_name)]=subobject[i]
exceptAttributeError:
pass
#Crudestatusindicator.
ifview:
view.update_status(i,total_number)
returnd,l
defmain():
#Gettheencodingifspecified.
iflen(sys.argv)>2:
encoding=sys.argv[2]
else:
encoding="UTF-8"
view=ConsoleView(encoding)
explorer=Explorer(view)
while1:
#Prompttheuser.
print"-"*60
view.show_namespace(explorer.get_items())
print"-"*60
print"[U]p[D]own[E]xtract[Q]uit[H]elpthen<Return>!"
print"-"*60
s=raw_input().strip().upper()[0]
#Findtherightaction.
ifs=="U":
#Up!
explorer.up()
elifs=="D":
#Promptforthefoldertoenter.
print"Downinto:"
name=raw_input()
ifnotexplorer.down(name):
print"Nosuchobject."
elifs=="E":
#Promptforthefiletoextractto.
print"Extractto:"
filename=raw_input()
print"Extracting..."
extractor=Extractor(view)
extractor.extract(explorer.get_items(),filename)
elifs=="Q":
print"Exiting..."
raiseSystemExit
elifs=="H":
print"TypetheDkeythen<Return>toenterafolder."
print"<Return>."
print"TypetheUkeythen<Return>tomoveuponelevel."
print"TypetheQkeythen<Return>toquit."
print"TypetheHkeythen<Return>toreadthisagain."
print"TypetheEkeythen<Return>toextractitems."
print"<Return>."
print"Goodluck!"
else:
print"Nosuchcommand."
if__name__=="__main__":
main()
#vim:tabstop=4expandtabshiftwidth=4
Ⅱ python 發送郵件
以下腳本測試通過!!!!!
fromTkinterimportTk
fromtimeimportsleep
importwin32com.clientaswin32
warn=lambdaapp:showwarning(app,"Exit?")
Range=range(3,8)
defoutlook():
app="Outlook"
olook=win32.gencache.EnsureDispatch("%s.Application"%app)
mail=olook.CreateItem(win32.constants.olMailItem)
recip=mail.Recipients.Add("[email protected]")
subj=mail.Subject="Python-to-%sDemo"%app
body=["Line%d"%iforiinRange]
body.insert(0,"%s "%subj)
body.append(" Th-th-th-that'sallfolks!")
mail.Body=" ".join(body)
mail.Send()
'''
ns=olook.GetNamespace("MAPI")
obox=ns.GetDefaultFolder(win32.constants.olFolderOutbox)
obox.Display()
obox.Items.Item(1).Display()
'''
warn(app)
olook.Quit()
if__name__=="__main__":
Tk().withdraw()
outlook()