Solved

Handle exception during sending of mailing (IdSMTP, INDY)

Posted on 2011-09-07
5
4,773 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 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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Jaspersoft Studio is a plugin for Eclipse that lets you create reports from a datasource.  In this article, we'll go over creating a report from a default template and setting up a datasource that connects to your database.
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 columnThat will then direct you to their download page.From that page s…
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 use NetBeans IDE 8.0 for Windows to perform CRUD operations on a MySql database.

738 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