Search code examples
delphistreamemail-attachmentsindy

I want to be able to save my attachment data into my mysql database. I am guessing that means I have to save my attachment data into a TStream


I am trying to insert my attachment data from an IMAP Server to a MySQL database using TBlobStream Methods.

procedure TForm1.Button1Click(Sender: TObject);
var
  imap_message_count:Integer;
  current_record:Integer;
  imap_id:String;

  email_parts_count:Integer;
  current_email_part:Integer;


  attachment_stream:TStream;
  blob_stream:TStream;
  final_stream:TStream;

  attachment_data_set:TDataSet;
  attachment_data:TFDQuery;
  blob_field:TField;
begin
  IdIMAP41.Connect();
  if IdIMAP41.SelectMailBox('INBOX') then
  BEGIN
    imap_message_count := IdIMAP41.MailBox.TotalMsgs;
    for current_record := 1 to imap_message_count - 1 do
    begin
      IdIMAP41.GetUID(current_record, imap_id);
      IdIMAP41.UIDRetrieve(imap_id, IdMessage1);
      email_parts_count := IdMessage1.MessageParts.Count;
      for current_email_part := 1 to email_parts_count - 1 do
      begin
        if IdMessage1.MessageParts.Items[current_email_part] is TIdAttachment then
        begin
          attachment_stream := TIdAttachment(IdMessage1.MessageParts.Items[current_email_part]).OpenLoadStream;
          try
           AttachmentsTable.Insert;
           blob_field := AttachmentsTable.FieldByName('attachment');
            blob_stream := AttachmentsTable.CreateBlobStream(blob_field, bmWrite);
              try
                blob_stream.CopyFrom(attachment_stream, 0);
              finally
                AttachmentsTable.Post;
                blob_stream.Free;
              end;
           finally
            TIdAttachment(IdMessage1.MessageParts.Items[current_email_part]).CloseLoadStream;
           end;
        end;
      end;
    end;
  END;

end;

Currently I am able to insert an ID as it is autoincremented but when I look at my Data Base attachment field I end up getting a result of Null. What could be my issue?

I am guessing I am not accessing my blob_stream data correctly.

Thanks in advance


Solution

  • if IdMessage1.MessageParts.Items[current_email_part] is TIdAttachment then
            begin     
                  attachment_stream := TIdAttachment(IdMessage1.MessageParts.Items[current_email_part]).OpenLoadStream;
              try
               AttachmentsTable.Insert;
               blob_field := AttachmentsTable.FieldByName('attachment');
               blob_stream := AttachmentsTable.CreateBlobStream(blob_field, bmWrite);
                  try
                    blob_stream.CopyFrom(attachment_stream, attachment_stream.Size);
                  finally
                    blob_stream.Free;
                    AttachmentsTable.Post;
                  end;
               finally
                TIdAttachment(IdMessage1.MessageParts.Items[current_email_part]).CloseLoadStream;
               end;
            end;