首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

BCB6 中使用 Indy 9 發送郵件完整範例

     編輯:關於C++

元件配置

使用兩個 Indy 元件:TIdMessage (命名為 IdMsgSend) 與 TIdSMTP (命名為 SMTP)。

核心發送函數:SendMail

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;
}

SMTP 設定函數:SMTP_Setup

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) 兩種模式。
  • 回傳值:0 成功、-1 失敗 (參考 cMsg)、-2 未先設定 SMTP 屬性。

使用方式

  1. 先呼叫 SMTP_Setup 設定伺服器、連接埠、帳號密碼、驗證模式。
  2. 再呼叫 SendMail 傳入收件人、主旨、內文、附件清單。
  3. 檢查回傳值與 cMsg 判斷結果。

另可利用 Variant 直接操作 TTS,但 Indy 方式更結構化且功能完整。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved