Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   FireMonkey (https://www.clubdelphi.com/foros/forumdisplay.php?f=50)
-   -   Enviar Correo con Archivo Ajunto Stream (pdf) (https://www.clubdelphi.com/foros/showthread.php?t=96146)

giantonti1801 06-03-2023 15:51:33

Enviar Correo con Archivo Ajunto Stream (pdf)
 
Buen dia amigo, estoy tratando de enviar un correo desde la aplicacion pero se me presentan 2 problemas:
1. Necesito limpiar los Archivo adjunto antes de enviarlo ya que cuando llega al correo me aparece que tiene varios archivos adjunto (asumo que con todas la pruebas que hice aun conserva en la memori los que envie anteriormente)
2. Nececito Generar un Stream del archivo PDF para no que guardar el archivo en el PC o Movil y obviamente enviar directamente al Destinatario como archivo adjunto.

Les envio el codigo que tengo actualmente aunque aun tiene problema pero quiero ver si alguien me ayude a que funcione:

Código Delphi [-]
procedure TForm1.TMSFMXToolBarButton42Click(Sender: TObject);
var
filename: TStream;
//filename: String;
s1: tStream;
  begin
     s1 := TMemoryStream.Create;
     frxReport1.PrepareReport();
     frxReport1.Export(frxPDFExport1);
     frxReport1.SaveToStream(s1);
    begin
    UniQueryEmail.Close;
    UniQueryEmail.SQL.Clear;
    UniQueryEmail.SQL.Add('Select * from Email');
    UniQueryEmail.SQL.Add('where instrut = :instrut');
    UniQueryEmail.ParamByName('instrut').AsString := LabelRutInst.Text;
    UniQueryEmail.Open;
    if not uniqueryemail.Eof  then
       begin
         filename := s1;
         try
         IdSMTP.Host := UniQueryEmailSMTP_HOST.AsString;
         IdSMTP.Password  := UniQueryEmailSMTP_PASSWORD.AsString;
         IdSMTP.Port := StrToInt(UniQueryEmailSMTP_PORT.AsString);
         IdSMTP.Username := UniQueryEmailSMTP_USERNAME.AsString;
         data.Subject := 'PRUEBA DE ENVIO';//edit3.Text; ???????????????
         data.Recipients.EMailAddresses := LabelPacEmail.Text;
         data.Body := memo1.Lines;
         data.AttachmentTempDirectory := filename;
         TIdAttachmentfile.create(data.MessageParts,filename); //es aquí donde tengo el problema asumo que sea por incompatibilidad de archivo o seguramente no lo estoy haciendo de la forma correcta
           try
           IdSMTP.Connect;
           IdSMTP.Send(Data);
           finally
            IdSMTP.Disconnect(true);
            ShowMessage('Correo enviado con exito');
           end;

         Except

          on E: exception do
             ShowMessage(E.Message)

         end;


       end
       else
       begin
         ShowMessage('No se puede enviar el EMAIL');
       end;
    
    end;
  end;

bucanero 08-03-2023 09:56:57

En tu código veo que declaras dos TStream y no tengo muy claro al final como los manejas....
Cita:

Empezado por giantonti1801 (Mensaje 550658)


Código Delphi [-]
procedure TForm1.TMSFMXToolBarButton42Click(Sender: TObject);
var
filename: TStream;
//filename: String;
s1: tStream;
  begin
...
  end;

Dando por hecho que la parte de guardar el PDF en un stream te funciona bien y el problema es en el envio de correo, te paso una adaptación del codigo que yo utilizo y que espero te pueda servir

Código Delphi [-]
uses
  IdAttachmentFile, IdText, IdAttachment, IdMessageParts; 


function TForm2.prepareMessage(AToMail, ASubject: string; ABody: TStrings; AFileStream: TStream; AFileName: string): Boolean;
var
  CCListMail: string;
  HTMLFormat: Boolean;
begin
  Result := False;
  HTMLFormat := true;
  CCListMail := '';

  with IdMessage do begin
    clear;
    Body.clear;

    Recipients.EMailAddresses := AToMail;

    From.Address := FromMail;
    From.Name := FromNombre;
    ReplyTo.Add.Address := FromMail;
    if (CCListMail <> '') then
      BccList.EMailAddresses := CCListMail;

    Subject := ASubject;

      //se insertan los ficheros adjuntos
    with TIdAttachmentFile.Create(MessageParts) do begin
      AFileStream.Seek(0, 0);
      LoadFromStream(AFileStream);
      FileName := ExtractFileName(AFileName);
    end;

    if HTMLFormat then begin
        //la parte del mensaje que contienes HTML
      ContentType := 'multipart/mixed';
      with TIdText.Create(MessageParts, nil) do begin
        ContentType := 'text/html';
        Body.AddStrings(ABody);
      end;

      Body.Add('This is a multi-part message in MIME format.');
    end
    else begin
      ContentType := 'text/plain';
      Body.AddStrings(ABody);
    end;
  end;

  result := True;
end;

function TForm2.SendMail: Boolean;
begin
  result := false;

  // se carga la configuracion del SMTP
  getSMTPConfig;

  IdSMTP.Connect;
  if IdSMTP.connected then
  try
    IdSMTP.Send(IdMessage);
    result := True;
  finally
    IdSMTP.Disconnect(true);
  end;
end;

procedure LoadBitmapIntoStream(stream: TStream; AFileName: string);
var
  Bitmap: TBitmap;
begin
  /// Aqui es donde se carga el contenido del fichero en en un memoryStream
  /// Para las pruebas yo las he realizado con un simple BMP
  Bitmap := TBitmap.create;
  try
    Bitmap.LoadFromFile(AFileName);
    Bitmap.SaveToStream(stream);
  finally
    Bitmap.Free;
  end;
end;

procedure TForm2.Button1Click(Sender: TObject);
var
  Email, asunto: string;
  FileStream: TStream;
  MailFileName: string;
begin
  FileStream := TMemoryStream.Create;
  try
    /// carga el contenido del fichero en en un memoryStream, puede ser una imagen o un fichero PDF o cualquier otro contenido
    LoadBitmapIntoStream(FileStream, 'c:\a\icon_title2.bmp');

    Email := Destinatario; // 'uncorreo@servidor.com';
    asunto := 'El asunto del correo. Esto es una prueba de correo';
    MailFileName := 'MyImagen.bmp'; 
    /// MailFileName es el nombre que aparecera  en el email del receptor. 
    /// No tiene por que ser el mismo nombre que tiene originalmente.

    if not prepareMessage(Email, asunto, memo1.Lines, FileStream, MailFileName) then
      showMessage('Error en el proceso de preparacion del email')
    else if not SendMail then
      showMessage('No se pudo enviar el EMAIL')
    else
      ShowMessage('Correo enviado con exito');
  finally
    FileStream.Free;
  end;
end;


La franja horaria es GMT +2. Ahora son las 11:42:02.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi