Search code examples
delphismtpgmaildelphi-7indy

Access violation on send email with attachment


var
  IdEnviar: TIdMessage;

If I send an email, it works fine

IdSSLIOHandlerSocketOpenSSL1.Host :=  'smtp.gmail.com';
IdSSLIOHandlerSocketOpenSSL1.Port := 587;

but if I try to add attachment adding this 3 lines:

IdEnviar.MessageParts.Clear;
IdAttachmentFile1.Create(IdEnviar.MessageParts, 'c:\file.png');
IdAttachmentFile1.ContentType := 'multipart/mixed';

I get an access violation error.

I'm using the last indy10 files


Solution

  • Your code contains a serious error:

    IdAttachmentFile1.ContentType := 'multipart/mixed';
    

    You've failed to create the TIdAttachmentFile properly, so you're trying to set a property on an object that doesn't exist, and thus getting the AV.

    The proper way to accomplish this is to assign the result of TIdAttachmentFile.Create to a variable, and then set that variable's ContentType:

    var
      Attachment: TIdAttachmentFile;
    
    Attachment := TIdAttachmentFile.Create(IdEnviar.MessageParts, 'c:\file.png');
    Attachment.ContentType := 'multipart/mixed';