Solved

Handle exception during sending of mailing (IdSMTP, INDY)

Posted on 2011-09-07
5
4,671 Views
Last Modified: 2016-10-03
Hi,

The following code I use for sending E-mail within a thread.
As there are serveral things that might go wrong I want to supply the enduser with a informative message about the error and also handle accordingly.

Stuff that needs to be coverred:
Losing internetconnection
Losing networkconnection
Wrong SMTP connection parameters
Wrong Emailadresses
Any other SMTP-errors (like server rejects mailing for any reason)


Can anybody give advise about handling these errors correctly. Also supply me with errorcodes en exception-types, etc..
procedure TMailingPerEmailThread.Execute;
var IdSMTP : TIdSMTP;
    IdMessage : TIdMessage;
    i, j, MaxEmailsPerBatch, TijdTussenBatches : Integer;
begin
  MailingPerEmailIsBezig := True;
  MaxEmailsPerBatch := DM.QGebruikers.FieldByName('EmailLimietWebHost').AsInteger;
  TijdTussenBatches := DM.QGebruikers.FieldByName('EmailLimietInterval').AsInteger;
  try
    IdSMTP := TIdSMTP.Create(nil);
    IdSMTP.Host     := DM.QGebruikers.FieldByName('SMTPHost').AsString;
    IdSMTP.Port     := DM.QGebruikers.FieldByName('SMTPPoort').AsInteger;         // smtp is normaal gesproken op poort 25
    IdSMTP.Password := XTeaDecryptStr(HexToString(DM.QGebruikers.FieldByName('SMTPWachtwoord').AsString), TiGiDkCeHc);
    IdSMTP.Username := DM.QGebruikers.FieldByName('SMTPGebruikersnaam').AsString; 

    if not IdSMTP.Connected then
      IdSMTP.Connect;

    HuidigeEmail     := '';
    MailingVerzonden := 0;
    MailingDoublures := 0;
    try
      IdMessage := TIdMessage.Create(nil);
      IdMessage.AttachmentEncoding := 'MIME';
      IdMessage.ConvertPreamble    := True;
      IdMessage.Encoding           := meDefault;
      IdMessage.Subject            := FOnderwerp;
      IdMessage.From.Address       := FVan;
      // Bijlage toevoegen
      If (FBijlage <> '') then
        TIdAttachmentFile.Create(IdMessage.MessageParts, FBijlage);

      // Klantafhankelijke gegevens per E-mail
      for i := 1 to DM.QMailingPerEmail.RecordCount do
      begin
        if (ANSICompareText(HuidigeEmail, DM.QMailingPerEmail.fieldbyname('Email').Text) <> 0) then
        begin
          IdMessage.Recipients.EMailAddresses := DM.QMailingPerEmail.FieldByName('Email').Text;
          FBodyKopie := FBody;

          for j := 0 to pred(TIdMessage(IdMessage).MessageParts.Count) do
          begin
            if TIdMessage(IdMessage).MessageParts[j] is TIdText then
            begin
              TIdMessage(IdMessage).MessageParts[j].Free;
            end;
          end;

          // E-mail body in Tekst
          With TIdText.Create(IdMessage.MessageParts, nil) do
          begin
            Body.Text := FBodyKopie;
            ContentType := 'text/plain';
          end;

          try
            // Verstuur de E-mail
            IdSMTP.send(IdMessage);
            MailingVerzonden := MailingVerzonden + 1;

            // Wachten bij opgegeven Limiet per mailing
            If (MaxEmailsPerBatch > 0) then
            begin
              if (MaxEmailsPerBatch = MailingVerzonden) then
                Sleep(TijdTussenBatches * 1000);
            end;
          except
            on E: EIdSMTPReplyError do
            begin
              // Re-connect the IdSMTP
              IdSMTP.Disconnect;
              Sleep(5000);     
              // Re-connect
              IdSMTP.Connect;
              try
                // Verstuur de E-mail opnieuw
                IdSMTP.send(IdMessage);
                MailingVerzonden := MailingVerzonden + 1;

                // Wachten bij opgegeven Limiet per mailing
                If (MaxEmailsPerBatch > 0) then
                begin
                  if (MaxEmailsPerBatch = MailingVerzonden) then
                    Sleep(TijdTussenBatches * 1000);
                end;
              except
                on E: EIdSMTPReplyError do
                begin
                  // Thread afbreken.
                  Raise;
                  Break; // De loop afbreken
                end;
              end;
            end;
            on E:Exception do
            begin
              // Thread afbreken.
              Raise;
              Break; // De loop afbreken
            end;
          end;
        end else
        begin
          MailingDoublures := MailingDoublures + 1;
        end;
        DM.QMailingPerEmail.Next;
      end;
    finally
      FreeAndNil(IdMessage);
    end;
  except
    on E: Exception do
    begin
      MyMessageDlg(Format(wzzMessageFout
                        , [ConstantP])
                 , Format(wzzMailingPerEmailFout
                        , [E.Message])
                 , dkFout, NMV);
      if IdSMTP.Connected then
        IdSMTP.Disconnect;
      MailingPerEmailIsBezig := False;
      Raise;
    end;
  end;
  if IdSMTP.Connected then
    IdSMTP.Disconnect;
  IdSMTP.Free;
  MailingPerEmailIsBezig := False;
end;

Open in new window

0
Comment
Question by:Delphiwizard
  • 5
5 Comments
 
LVL 4

Assisted Solution

by:rotem156
rotem156 earned 500 total points
ID: 36534883
You're welcome.
0
 
LVL 4

Assisted Solution

by:rotem156
rotem156 earned 500 total points
ID: 36534971
You're welcome.
0
 
LVL 4

Assisted Solution

by:rotem156
rotem156 earned 500 total points
ID: 36551362
You're welcome.
0
 
LVL 4

Accepted Solution

by:
rotem156 earned 500 total points
ID: 36551376
Try to see if it has an event that is triggered when a specific operation failed.
0
 
LVL 4

Assisted Solution

by:rotem156
rotem156 earned 500 total points
ID: 36551382
You're welcome.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In our object-oriented world the class is a minimal unit, a brick for constructing our applications. It is an abstraction and we know well how to use it. In well-designed software we are not usually interested in knowing how objects look in memory. …
Here is a helpful source code for C++ Builder programmers that allows you to manage and manipulate HTML content from C++ code, while also handling HTML events like onclick, onmouseover, ... Some objects defined and used in this source include: …
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now