•  

ГлавнаяIndyIdSMTP → Пример создания и отправки текстового сообщения (Indy 10)

Создано: 13.05.2009 13:00:06 · Исправлено: 24.05.2010 23:33:48 · Прочтений: 8075

Небольшой пример иллюстрирует отправку заранее подготовленного сообщения через указанный SMTP сервер.
unit Main;

interface

uses
  Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls,
  SysUtils, Classes, IdMessage, IdBaseComponent, IdComponent,
  IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase,
  IdMessageClient, IdSMTPBase, IdSMTP;

type
  TformMain = class(TForm)
    memoMsg: TMemo;
    Panel1: TPanel;
    Label1: TLabel;
    editFrom: TEdit;
    Label2: TLabel;
    editTo: TEdit;
    Label3: TLabel;
    editSubject: TEdit;
    Label4: TLabel;
    editSMTPServer: TEdit;
    butnSendMail: TButton;
    lboxStatus: TListBox;
    smtpSendMail: TIdSMTP;
    mesgMessage: TIdMessage;
    procedure butnSendMailClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure smtpSendMailStatus(ASender: TObject;
      const AStatus: TIdStatus; const AStatusText: String);
  private
  public
    procedure Status(AMsg: string);
  end;

var
  formMain: TformMain;

implementation
{$R *.dfm}

uses
  INIFiles;

procedure TformMain.butnSendMailClick(Sender: TObject);
begin
  butnSendMail.Enabled := False; try
    with mesgMessage do begin
      Clear;
      From.Text := Trim(editFrom.Text);
      Recipients.Add.Text := Trim(editTo.Text);
      Subject := Trim(editSubject.Text);
      Body.Assign(memoMsg.Lines);
    end;
    with smtpSendMail do begin
      Host := Trim(editSMTPServer.Text);
      Connect; try
        Send(mesgMessage);
      finally Disconnect; end;
    end;
    Status('Completed');
  finally butnSendMail.Enabled := True; end;
end;

procedure TformMain.Status(AMsg: string);
begin
  lboxStatus.ItemIndex := lboxStatus.Items.Add(AMsg);
  // Allow the listbox to repaint
  Application.ProcessMessages;
  Application.ProcessMessages;
  Application.ProcessMessages;
end;

procedure TformMain.FormCreate(Sender: TObject);
var
  LINIFile: string;
begin
  // This routine can be ignored, it is not a functional part of the demo.
  //
  // This is used to load default values during presentations at conferences
  // so attendees do not have to wait for values to be entered each time.
  LINIFile := 'c:\SMTP.ini';
  if FileExists(LINIFile) then begin
    with TINIFile.Create(LINIFile) do try
      editFrom.Text := ReadString('Main', 'From', '');
      editTo.Text := ReadString('Main', 'To', '');
      editSubject.Text := ReadString('Main', 'Subject', '');
      editSMTPServer.Text := ReadString('Main', 'SMTP Server', '');
      memoMsg.Lines.Text := ReadString('Main', 'Message', '');
    finally Free; end;
  end;
end;

procedure TformMain.smtpSendMailStatus(ASender: TObject;
  const AStatus: TIdStatus; const AStatusText: String);
begin
  Status(AStatusText);
end;

end.