使用兩個 Indy 元件:TIdMessage (命名為 IdMsgSend) 與 TIdSMTP (命名為 SMTP)。
int __fastcall TM::SendMail(const char *cTo, const char *cCc, const char *cBcc,
const char *cSubject, const char *cBody, const char *cAttachList, char *cMsg)
{
int iRet = 0;
if (!SetupOk) return -2; // 未設定 SMTP 屬性
IdMsgSend->Clear();
IdMsgSend->ContentType = ContentType;
IdMsgSend->From->Text = LocalMail;
if (ReturnReciept)
IdMsgSend->ReceiptRecipient->Text = IdMsgSend->From->Text;
else
IdMsgSend->ReceiptRecipient->Text = "";
IdMsgSend->Recipients->EMailAddresses = cTo;
IdMsgSend->Subject = cSubject;
IdMsgSend->CCList->EMailAddresses = cCc;
IdMsgSend->BccList->EMailAddresses = cBcc;
IdMsgSend->Priority = TIdMessagePriority(Priority);
IdMsgSend->Body->Text = String(cBody);
// 處理附件
if (strlen(cAttachList)) {
TStringList *sl = new TStringList;
sl->Text = String(cAttachList); // 以 \n 分隔
for (int i = 0; i < sl->Count; i++) {
IdMsgSend->MessageParts->Add();
new TIdAttachment(IdMsgSend->MessageParts, sl->Strings[i]);
}
delete sl;
}
// 連線 SMTP
if (!SMTP->Connected()) {
try { SMTP->Connect(); }
catch (Exception &e) {
strcpy(cMsg, "連接 SMTP 伺服器失敗!錯誤訊息:");
strcat(cMsg, e.Message.c_str());
return -1;
}
}
// 發送郵件
if (SMTP->Connected()) {
try { SMTP->Send(IdMsgSend); }
catch (Exception &e) {
strcpy(cMsg, e.Message.c_str());
iRet = -1;
}
} else {
strcpy(cMsg, "連接 SMTP 伺服器失敗!");
iRet = -1;
}
return iRet;
}
int __fastcall TM::SMTP_Setup(const char *cHost, const int iPort, const char *cLocalMail,
const int iAuth, const char *cUsername, const char *cPassword)
{
int iRet = 0;
if (SMTP->Connected()) SMTP->Disconnect();
SMTP->Host = String(cHost);
SMTP->Port = iPort;
LocalMail = String(cLocalMail);
switch (iAuth) {
case 0: SMTP->AuthenticationType = atNone; break;
case 1: SMTP->AuthenticationType = atLogin; break; // Simple Login
}
SMTP->Username = cUsername;
SMTP->Password = cPassword;
SetupOk = true;
return iRet;
}
IdMsgSend->Clear() 必須呼叫,否則保留上次郵件資訊。\n 分隔,逐一建立 TIdAttachment 加入 MessageParts。try-catch 捕捉例外,錯誤訊息回傳 cMsg。atNone) 與簡單登入驗證 (atLogin) 兩種模式。cMsg)、-2 未先設定 SMTP 屬性。SMTP_Setup 設定伺服器、連接埠、帳號密碼、驗證模式。SendMail 傳入收件人、主旨、內文、附件清單。cMsg 判斷結果。另可利用 Variant 直接操作 TTS,但 Indy 方式更結構化且功能完整。