通过 Outlook 和 OLE 稳健地发送电子邮件

Robustly sending emails through Outlook and OLE

我正在使用 OLE 通过 Outlook 发送电子邮件。我使用的代码是:

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('mike@example.com');
    vMailItem.Subject := 'What a wonderful test email';
    vMailItem.Body := 'This is a test --> how amazing';
    vMailItem.Send;
  end;

  VarClear(Outlook);
end;

它已经从几个不同的 SO 问题中被毫不掩饰地删掉了 - 感谢所有人。

我遇到的代码问题是当 PC 上安装了 Outlook,但已关闭。当 Outlook 打开时,我收到一个消息框,上面写着 "Outlook is varDispatch" 并且发送和接收了一封邮件。当 Outlook 关闭时,我得到相同的消息框 "Outlook is varDispatch",但随后 "An error occurred in the application" 并且我的应用程序突然关闭。

所以两个问题:

1) 如何检测 Outlook 是否为 运行?将 OKToUse 设置为 true 似乎不是正确的方法。

2) 如果 Outlook 不是 运行,我该如何启动它并在发送电子邮件后将其关闭?

我正在使用 Delphi 10.1 Berlin 并尝试连接到 Outlook 2007。

在调用 CreateItem 之前添加以下内容

vNS := Outlook.GetNamespace('MAPI');
vNS.Logon;