2016-08-09 179 views
1

我使用OLE通過Outlook發送電子郵件。我使用的代碼是:通過Outlook和OLE強力發送電子郵件

procedure SendOutlookMail; 
const 
    olMailItem = 0; 
var 
    OKToUse: boolean; 
    Outlook: OleVariant; 
    vMailItem: variant; 
begin 
    OKToUse := false; 
    try 
    Outlook := GetActiveOleObject('Outlook.Application'); 
    OKToUse := true; 
    except 
    try 
     Outlook := CreateOleObject('Outlook.Application'); 
     OKToUse := true; 
    except 
     on e: exception do begin 
     ShowMessage(e.Message); 
     end; 
    end; 
    end; 

    if VarIsType(Outlook, varDispatch) then 
    ShowMessage('Outlook is varDispatch') 
    else 
    ShowMessage('Outlook is ***NOT*** varDispatch'); 

    if OKToUse then begin 
    vMailItem := Outlook.CreateItem(olMailItem); 
    vMailItem.Recipients.Add('[email protected]'); 
    vMailItem.Subject := 'What a wonderful test email'; 
    vMailItem.Body := 'This is a test --> how amazing'; 
    vMailItem.Send; 
    end; 

    VarClear(Outlook); 
end; 

而一直底氣十足,從幾個不同的做題缺口 - 感謝所有。

我在代碼中遇到的問題是Outlook安裝在PC上但關閉。當Outlook打開時,我會看到一個消息框,指出「Outlook是varDispatch」,併發送並接收郵件消息。當Outlook關閉時,我得到相同的消息框「Outlook is varDispatch」,但隨後出現「應用程序中發生錯誤」,我的應用程序突然關閉。

所以兩個問題:

1)如何檢測如果Outlook運行? OKToUse被設置爲true的事實似乎不是正確的方法。

2)如何啓動Outlook,如果它沒有運行,並在發送電子郵件後關閉它?

我使用德爾福10.1柏林,並試圖連接到Outlook 2007

+1

之前如果'GetActiveOleObject()'成功,這顯然是開放的。設置另一個表示這個的「布爾」。否則,使它成爲'假'。如果你必須使用'CreateOleObject()',它必須被打開,而且似乎失敗了。你可能需要先設置一些屬性,然後才能使用它? –

+2

爲什麼不使用COM服務器包裝組件? –

+0

反對嗎?爲了什麼?這個地方有時候太難了:( –

回答

5

添加以下調用CreateItem

vNS := Outlook.GetNamespace('MAPI'); 
vNS.Logon; 
相關問題