?
Solved

Handle exception during sending of mailing (IdSMTP, INDY)

Posted on 2011-09-07
5
Medium Priority
?
4,851 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
5 Comments
 
LVL 4

Assisted Solution

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

Assisted Solution

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

Assisted Solution

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

Accepted Solution

by:
rotem156 earned 2000 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 2000 total points
ID: 36551382
You're welcome.
0

Featured Post

Enroll in August's Course of the Month

August's CompTIA IT Fundamentals course includes 19 hours of basic computer principle modules and prepares you for the certification exam. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

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

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 Go to that link and select download selenium in the right hand column That will then direct you to their download page. From that p…
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…
The viewer will learn how to synchronize PHP projects with a remote server in NetBeans IDE 8.0 for Windows.
Suggested Courses

770 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