Solved

Handle exception during sending of mailing (IdSMTP, INDY)

Posted on 2011-09-07
5
4,644 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
Comment Utility
You're welcome.
0
 
LVL 4

Assisted Solution

by:rotem156
rotem156 earned 500 total points
Comment Utility
You're welcome.
0
 
LVL 4

Assisted Solution

by:rotem156
rotem156 earned 500 total points
Comment Utility
You're welcome.
0
 
LVL 4

Accepted Solution

by:
rotem156 earned 500 total points
Comment Utility
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
Comment Utility
You're welcome.
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Programmer's Notepad is, one of the best free text editing tools available, simply because the developers appear to have second-guessed every weird problem or issue a programmer is likely to run into. One of these problems is selecting and deleti…
How to install Selenium IDE and loops for quick automated testing. Get Selenium IDE from http://seleniumhq.org (http://seleniumhq.org) Go to that link and select download selenium in the right hand columnThat will then direct you to their downlo…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.

763 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

9 Experts available now in Live!

Get 1:1 Help Now