Delphi-Kylix
  Home arrow Delphi-Kylix arrow Page 5 - Creating an SMTP Server
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Moblin 
JMSL Numerical Library 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
DELPHI-KYLIX

Creating an SMTP Server
By: Leidago
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 8
    2006-05-08

    Table of Contents:
  • Creating an SMTP Server
  • Setting the database connections
  • Optional
  • The Code
  • Conclusion

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Creating an SMTP Server - Conclusion


    (Page 5 of 5 )

    To test the server in Outlook Express enter "localhost" for both POP3/SMTP servers and use the username and passwords from the database's users table. Note that Outlook Express requires both an SMTP and POP3 server to be running prior to sending messages, so use the code from my previous POP3 Server tutorial to build a POP3 Server and run them both on your machine. Then start sending email messages! You can of course use these programs in a LAN environment or in a company as long as there's a network. I've included an empty MS Access database (available for download at the beginning of this article) for testing purposes.

    The Entire Code

    unit usmtps;

    interface

    uses
      Windows, Messages, SysUtils, Variants, Classes, Graphics,
    Controls, Forms,
      Dialogs, StdCtrls, IdIntercept, IdServerInterceptLogBase,
      IdServerInterceptLogFile, DB, ADODB, IdBaseComponent,
    IdComponent,
      IdCustomTCPServer, IdTCPServer, IdCmdTCPServer,
      IdExplicitTLSClientServerBase, IdSMTPServer,
    IdMessage,idcontext,idsync,ActiveX;

    type
     // just some testrecord
      TTestRec = record
        IntField  : integer;
        CharField : char;
        ByteField : byte;
        StrField  : string[20];
      end;
      PTTestRec = ^TTestRec;
     TShowMessageSync = class(TIdSync)
            protected
                FMsg: TIdMessage;
            public
                procedure DoSynchronize; override;
                constructor Create(tMsg: TIdMessage); reintroduce;
                class procedure Show(tMsg: TIdMessage);
            end;

      TForm1 = class(TForm)
        btnserveron: TButton;
        btnserveroff: TButton;
        IdSMTPServer1: TIdSMTPServer;
        ado1: TADOTable;
        q: TADOQuery;
        ADOConnection1: TADOConnection;
        LogFile: TIdServerInterceptLogFile;
        mess: TIdMessage;
        Label1: TLabel;
        StaticText1: TStaticText;
        StaticText2: TStaticText;
        Label2: TLabel;
        Label3: TLabel;
        StaticText3: TStaticText;
        Memo1: TMemo;
        Label4: TLabel;
        StaticText4: TStaticText;
        procedure btnserveronClick(Sender: TObject);
        procedure btnserveroffClick(Sender: TObject);
        procedure IdSMTPServer1MsgReceive(ASender:
    TIdSMTPServerContext;
          AMsg: TStream; var LAction: TIdDataReply);
        procedure IdSMTPServer1Connect(AContext: TIdContext);
        procedure IdSMTPServer1RcptTo(ASender: TIdSMTPServerContext;
          const AAddress: String; var VAction: TIdRCPToReply;
          var VForward: String);
        procedure IdSMTPServer1Received(ASender:
    TIdSMTPServerContext;
          var AReceived: String);
        procedure IdSMTPServer1UserLogin(ASender:
    TIdSMTPServerContext;
          const AUsername, APassword: String; var VAuthenticated:
    Boolean);
        procedure IdSMTPServer1MailFrom(ASender:
    TIdSMTPServerContext;
          const AAddress: String; var VAction: TIdMailFromReply);
        procedure FormCreate(Sender: TObject);
        procedure IdSMTPServer1Execute(AContext: TIdContext);
        procedure IdSMTPServer1Exception(AContext: TIdContext;
          AException: Exception);
      private
        { Private declarations }
      public
        { Public declarations }
      end;

    var
      Form1: TForm1;

    implementation

    {$R *.dfm}
    constructor TShowMessageSync.Create(tMsg: TIdMessage);
        begin
            inherited Create;
            FMsg := tMsg;
        end;

        procedure TShowMessageSync.DoSynchronize;
        begin
            Form1.Label2.Caption := FMsg.From.Address;
            Form1.Label1.Caption := FMsg.Recipients.EMailAddresses;
            Form1.Label3.Caption := FMsg.Subject;
            Form1.Memo1.Lines.AddStrings(FMsg.Body);
        end;

        class procedure TShowMessageSync.Show(tMsg: TIdMessage);
        begin
            with Create(tMsg) do try
                Synchronize;
            finally
                Free;
            end;
        end;

    procedure TForm1.btnserveronClick(Sender: TObject);
    begin
     btnServerOn.Enabled := False;
     btnServerOff.Enabled := True;
     IdSMTPServer1.active := true;
    end;

    procedure TForm1.btnserveroffClick(Sender: TObject);
    begin
     btnServerOn.Enabled := True;
     btnServerOff.Enabled := False;
     IdSMTPServer1.active := false;
    end;

    procedure TForm1.IdSMTPServer1MsgReceive(ASender:
    TIdSMTPServerContext;
      AMsg: TStream; var LAction: TIdDataReply);
     var
     lmsg : TIdMessage;
     LStream : TFileStream;
     toad,from,sub,body:string;
     abuff:tstrings;
     six:int64;
      begin

     CoInitialize(nil);
      six:=amsg.Size;
      LStream := TFileStream.Create(ExtractFilePath
    (Application.exename) + 'test.eml', fmCreate);
    Try
     LStream.CopyFrom(AMsg, 0);
    Finally
     FreeAndNil(LStream);
    End;

      mess.NoDecode:=true;
     mess.LoadFromFile('test.eml',false);
     label4.Caption:=datetostr(mess.Date);
      label1.Caption:=mess.Recipients.EMailAddresses;
      label2.Caption:=mess.From.Address;
      label3.Caption:=mess.Subject;
      memo1.Lines.Text:=mess.Body.Text;
    //if mess.From.Address <> '' then begin
    ado1.TableName:='email';
    ado1.Active:=true;
    ado1.Insert;
    ado1.FieldByName('to').Text:=mess.Recipients.EMailAddresses;
    ado1.FieldByName('from').Text:= mess.From.Address;
    ado1.FieldByName('subject').Text:=mess.Subject;
    ado1.FieldByName('mbody').AsString:=mess.Body.Text;
    //Date: Wed, 1 Feb 2006 17:34:43 +0000
    ado1.FieldByName('mdate').AsDateTime:=mess.Date;
    ado1.FieldByName('msize').value:=six;
    ado1.FieldByName('ismarked').value:=0;
    ado1.Post;
    CoUnInitialize;
    //end;
    end;

    procedure TForm1.IdSMTPServer1Connect(AContext: TIdContext);
    begin
    //idsmtpserver1.Greeting.SetReply(220,'Welcome to Leidago
    Server');
    //logfile.Accept(acontext.Connection);
    end;

    procedure TForm1.IdSMTPServer1RcptTo(ASender:
    TIdSMTPServerContext;
      const AAddress: String; var VAction: TIdRCPToReply;
      var VForward: String);
    begin

      // The following actions can be returned to the server:
     {
        rAddressOk, //address is okay
        rRelayDenied, //we do not relay for third-parties
        rInvalid, //invalid address
        rWillForward, //not local - we will forward
        rNoForward, //not local - will not forward - please use
        rTooManyAddresses, //too many addresses
        rDisabledPerm, //disabled permanently - not accepting E-Mail
        rDisabledTemp //disabled temporarily - not accepting E-Mail
     }
      if Pos('@', AAddress) > 0 then  begin
     VAction := rAddressOk;
     end
     else begin
      VAction :=rInvalid;
     end;
    end;

    procedure TForm1.IdSMTPServer1Received(ASender:
    TIdSMTPServerContext;
      var AReceived: String);
    begin
      // This is a new event in the rewrite of IdSMTPServer for Indy
    10.
     // It lets you control the Received: header that is added to the
    e-mail.
     // If you do not want a Received here to be added, set
    AReceived := '';
     // Formatting 'keys' are available in the received header --
    please check
     // the IdSMTPServer source for more detail.
     AReceived := '';
    end;

    procedure TForm1.IdSMTPServer1UserLogin(ASender:
    TIdSMTPServerContext;
      const AUsername, APassword: String; var VAuthenticated:
    Boolean);
    begin
    // This event is fired if a user attempts to login to the server
     // Normally used to grant relay access to specific users etc.
    //Search for the username and password in "users" table..
    q2.SQL.Text := 'SELECT * from users WHERE uname=:user AND
    upass=:pwd';
            q2.Parameters.ParamByName('user').Value :=AUsername;
            q2.Parameters.ParamByName('pwd').Value := APassword;
            q2.open;
    //if the user is not found, set authentication to false
    if q2.RecordCount = 0 then begin

    VAuthenticated := False;
     end else begin
     VAuthenticated := True;
     end;

    end;

    procedure TForm1.IdSMTPServer1MailFrom(ASender: TIdSMTPServerContext;
      const AAddress: String; var VAction: TIdMailFromReply);
    begin
    // Here we are testing the MAIL FROM line sent to the server.
     // MAIL FROM address comes in via AAddress. VAction sets the
    return action to the //server.
    // The following actions can be returned to the server:
     { mAccept, mReject }

       if Pos('@', AAddress) > 0 then  begin
     VAction:= mAccept;

     end

     else begin
      VAction := mReject;
     end;   
    end;

    procedure TForm1.FormCreate(Sender: TObject);
    begin

    idsmtpserver1.Greeting.SetReply(220,'Welcome to SMTP Server');
    end;

    procedure TForm1.IdSMTPServer1Execute(AContext: TIdContext);
    begin
    logfile.DoLogWriteString(acontext.Connection.IOHandler.ReadLn);

    end;

    procedure TForm1.IdSMTPServer1Exception(AContext: TIdContext;
      AException: Exception);
    begin
    acontext.Connection.IOHandler.Write(aexception.Message);
    end;

    end.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · I'd like to see an article that created an SMTP/POP3 proxy so I could writecode to...
       · I will certainly look into it!Thanks
       · This not working for me, I use Delphi7, do i need to use some library to get this...
     

    DELPHI-KYLIX ARTICLES

    - Building a Server Application for an Interne...
    - Building an Internet Access Control Applicat...
    - Client Dataset: Working with Data Packets an...
    - Using the Client Dataset in an N-Tiered Appl...
    - Using the Client Dataset in Two-Tiered Clien...
    - Using the Client Dataset in File-Based Archi...
    - Demystifying the Client Dataset
    - Working with INI Files in Delphi
    - Creating Data Link (UDL) Files in Delphi
    - Looking at the Details for an Invoicing Appl...
    - Invoicing in Delphi: Show Me the Money
    - Saving Images and Binary Files to a Database...
    - Saving Files to a Database using Delphi: Sav...
    - Creating CF Applications and Integrating a S...
    - Using Try and Finally to Help Prevent Memory...







    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway