Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Internet (https://www.clubdelphi.com/foros/forumdisplay.php?f=3)
-   -   Como puedo pegar una imagen en un mail? (https://www.clubdelphi.com/foros/showthread.php?t=50059)

Nayla 07-11-2007 09:58:13

Como puedo pegar una imagen en un mail?
 
Buenas :)

Tengo que hacer una aplicacion donde se genera una serie de mails de forma automatica. Los mails se generan ya bien y se envian correctamente.

El problema que tengo es que el contenido es en formato html y tengo que añadir algunas imagenes dentro de este codigo html. Las imagenes las tengo que recoger de una BD (un campo BLOB de una tabla de ORACLE).

Existe alguna forma de recoger esta imagen (JPG o GIF) de la BD e incrustarla dentro del contenido del cuerpo del mail?

Muchas gracias por adelantado, espero haberme explicado bien en lo que quiero hacer.

fide 07-11-2007 11:14:07

Imagen en Email..
 
Mira, si no me equivoco, en el cuerpo del mensaje debes de poner por ejemplo...

<html>
<img src="NombreImagen.jpg" width="60" height="70">
<body>
Hola. Aqui va el cuerpo del mensaje...
</body>
</html>

Y para que esto surta efecto, me parece que basta con adjuntar al IMAIL la imagen que se debe de mostrar, es decir una imagen con el nombre y extension que tu allas puesto dentro de la etiqueta img...

Espero resulte. Saludos y suerte. Ha, me dices si te funciono...

Nayla 08-11-2007 07:23:05

Hola fide,

pues he probado lo que me dices pero cuando añado el adjunto de la imagen deja de interpretarme el código html del mail. Me sale todo como si fuese texto plano.

Seguire investigando

ArdiIIa 08-11-2007 11:22:58

Supongo que estás utilizando las INDY (IdSMTP) para el envío de los mensajes ??

Nayla 08-11-2007 11:27:22

Si, estoy usando las INDY.

He leido por ahi que tengo que hacer el mensaje multipart, y hacer como dos partes, una con el texto html y otra con la imagen.

Estoy haciendo pruebas pero todavia no he conseguido resultados.

ArdiIIa 08-11-2007 11:33:26

Ok.
Te pongo unas porciones de código que utilizo para enviar emails mediante un Thread en Backgorund.

La idea es extraer las imágenes de la BD a un directorio temporal y seguidamente procesarlas para incluirlas en el cuerpo del mensaje.

Como te digo, son partes de código que seguramente te sea de ayuda, el resultado final, dependerá de tu pericia.

Código Delphi [-]

constructor TSendMail.Create(TmpDir: String);
begin
  inherited Create(True);
  FTempDir := TmpDir;
  Priority := tpIdle;
  FreeOnTerminate := True;
  FTmpStream := TMemoryStream.Create;
  IdSMTP := TIdSMTP.Create(nil);
  IdMessage := TIdMessage.Create(NIL);
  p :=  IdMessage.MessageParts;
  slBody := TstringList.Create;

    slBody.Add('');
    slBody.Add('');
    slBody.Add('');
    slBody.Add('');

     if findFirst(FTempDir + '*.jpg',faAnyFile ,sr) = 0 THEN
        REPEAT
        OpenfileJPG :=  FTempDir + SR.Name;
        slBody.Add('');
        idAttach := TidAttachment.Create(p, OpenfileJPG);
        idAttach.ContentType := 'image/jpeg';
        idAttach.ContentDisposition := 'inline';
        idAttach.ExtraHeaders.Values['content-id'] := Sr.Name;
        idAttach.DisplayName := Sr.Name;
        until FindNext(sr) <> 0;
        FindClose(sr);
    slBody.Add('');
    slBody.Add('');
FormMain.ProgressBar.Position := 0;
FormMain.ProgressBar.Visible := True;
end;


procedure TSendMail.Execute;
Var cTemp : String;
begin
  try
    while GlobalFindAtom('SEND_MAIL_BACK')  <> 0 do
    BEGIN
    SLEEP(1000);
    END;

    GlobalAddAtom('SEND_MAIL_BACK');
    Cuentas := TAccountItems.Create;
    LoadOptions(Cuentas);
    cTemp := '@' + copy(Cuentas[Cuentas.Principal].ServerPop3,1 + Pos('.', Cuentas[Cuentas.Principal].ServerPop3),99);
    IdMessage.From.Address := Cuentas[Cuentas.Principal].Login + cTemp;
    IdMessage.From.Name := Cuentas[Cuentas.Principal].Name;
    IdMessage.Recipients.Add;
    IdMessage.ContentType := 'multipart/mixed';
    IdSMTP.Username  := Cuentas[Cuentas.Principal].Login;
    IdSMTP.Host      := Cuentas[Cuentas.Principal].ServerSMTP;
    IdSMTP.Password  := Cuentas[Cuentas.Principal].Password;
    idText1 := TidText.Create(p, slBody);
    idText1.ContentType := 'text/html';
    idText2 := TidText.Create(p);
    idText2.ContentType := 'text/plain';
    idText2.Body.Add('UTILICE EL MODO APAISADO DE IMPRESIÓN SI DESEA IMPRIMIR EL DOCUMENTO, ');
    IdMessage.Body.Assign(slBody);
    IdMessage.SaveToStream(FTmpStream,False);
    FormMain.ProgressBar.Max := FTmpStream.Size;
    FormMain.ProgressBar.Position := 0;
    FormMain.ProgressBar.Visible := True;
    IdSMTP.OnWork := IdSMTPWork;
    IdSMTP.OnStatus := IdSMTPStatus;
    IdSMTP.AuthenticationType := atNone;
    IdSMTP.Connect;
    if IdSMTP.AuthSchemesSupported.IndexOf('LOGIN')>-1 then
    begin
      IdSMTP.AuthenticationType := atLogin;
      IdSMTP.Authenticate;
    end;
    idSMTP.Send(idMessage);

    Synchronize(Sound);
    FStatus := 'MAIL ENVIADO CORRECTAMENTE';
    Synchronize(UpdateStatus);
     //Borrado de ficheros y directorio temporal
    if findFirst(FTempDir + '*.*',faAnyFile ,sr) = 0 THEN
     REPEAT
     DeleteFile(FTempDir + SR.Name);
     until FindNext(sr) <> 0;
     FindClose(sr);
     RemoveDir(FTempDir);

   finally
   FStatus := 'ERROR INDETERMINADO';
   Synchronize(UpdateStatus);
   CleanUP;
   end;
end;

Nayla 08-11-2007 14:29:09

Pues no se lo que hago mal pero sigue sin funcionar :confused:

Pongo un poco del codigo a ver si alguien me puede iluminar




Código Delphi [-]
 
with IdMessage do begin
ContentType := 'multipart/mixed';
From.Address := 'midireccion';
From.Name := vRemitent
Subject := 'MiAsunto'
Recipients.EMailAddresses := vMail;
Body.Clear;
end;
vNomArxiu := 'nombreImagen.jpg';
slBody := TStringList.Create;
slBody.Assign(ConstruirCosMissatge(pIdClient, pDataPublic, Usuari)); 
 
vIdText := TidText.Create(idMessage.MessageParts, slBody);
vIdText.ContentType := 'text/html';
 
if FileExists(vPathTemp + vNomArxiu) then begin
vIdAttach := TIdAttachment.Create(idMessage.MessageParts, vPathTemp + vNomArxiu);
vIdAttach.ContentType := 'image/jpeg';
vIdAttach.ContentDisposition := 'inline';
vIdAttach.ExtraHeaders.Values['content-id'] := vNomArxiu;
vIdAttach.DisplayName := vNomArxiu;
end;
 
idMessage.Body.Assign(slBody);
 
with idSMTP do begin
Host := 'MiHost';
Port := 25;
HeloName := 'Loquesea';
AuthenticationType := atLogin;
Username := 'MiUsuario';
Password := 'MiPassword';
Connect();
Send(IdMessage);
end;


Gracias de antemano :)

Nayla 08-11-2007 14:50:37

Perdon que no dije que lo que me pasa con el codigo anterior es que recibo un mail con dos attachment, uno de texto, y otro con la imagen.

No consigo que funcione bien todavia :(

gluglu 08-11-2007 15:24:19

Echale un vistazo a este documento.

En él se explica perfectamente todos los tipos de mensajes, y como definirlos correctamente.

Saludos ;)

Nayla 08-11-2007 15:58:12

Gracias gluglu

pero me he mirado el documento que me enlazabas y sigo sin ver el error :(

Los mails que recibo me salen con estas opciones de cabecera:
This is a multi-part message in MIME format
--=_NextPart_2relrfksadvnqindyw3nerasdf
Content-Type: text/plain
Content-Transfer-Encoding: 7bit
--=_NextPart_2relrfksadvnqindyw3nerasdf
Content-Type: image/jpeg;
name="logo_endesa.jpg"
Content-Transfer-Encoding: base64
Content-Disposition: inline;
filename="logo_endesa.jpg"
content-id: logo_endesa.jpg
--=_NextPart_2relrfksadvnqindyw3nerasdf--
Parece como si estuviera "pasando" de esta parte del codigo que le pongo:

Código Delphi [-]
  vIdText := TidText.Create(idMessage.MessageParts, slBody);
  vIdText.ContentType := 'text/html';

O no se, hay alguna cosa que se me escapa y que no entiendo lo que esta pasando.

gluglu 08-11-2007 16:27:57

Cuando yo mando un mensaje con imágenes dentro del texto HTML, mi cabecera del mensaje es la siguiente :

Cita:

This is a multi-part message in MIME format
--caML6cRopV0jyVq6oi0rFDqp=_13MyJWkT
Content-Type: text/html ; charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<html><body>
<img src=3D"cid:0001">

....
....

--caML6cRopV0jyVq6oi0rFDqp=_13MyJWkT
Content-Type: image/jpeg;
name="AT0001.JPG"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="AT0001.JPG"
Content-ID: 0001
A mi al menos me funciona perfectamente de esta manera. Y mira que en su momento hice muchísimas pruebas. Compara mi cabecera con la que tu expones y a ver si te ayuda en algo. Está claro que la forma de usarlo es diferente.

Espero que te sirva de ayuda. ;)

Nayla 08-11-2007 20:50:34

Ya si yo lo que digo es que a pesar de que le estoy intentando forzar a que el content-type del idtext sea "text/html" me sigue saliendo "text/plain" y no sé por qué :(

gluglu 08-11-2007 22:54:59

He revisado mi código :

Código Delphi [-]
IdMessage1.ContentType := 'multipart/related; type="text/html"';
 
...
 
// Just HTML Text, No Attachments, No Embedded Images
MessageType := 1;
IdMessage1.ContentType := 'multipart/alternative';
...
// HTML Text + Attachments, No Embedded Images
MessageType := 2;
IdMessage1.ContentType := 'multipart/mixed';
...
// HTML Text + Attachments + Embedded Images
MessageType := 3;
IdMessage1.ContentType := 'multipart/mixed';
with TIdText.Create(IdMessage1.MessageParts, nil) do begin
  ContentType := 'multipart/related; type="multipart/alternative"';
end;
with TIdText.Create(IdMessage1.MessageParts, nil) do begin
  ContentType := 'multipart/alternative';
  ParentPart := 0;
end;
...
// HTML Text + Embedded Images, No Attachments
MessageType := 4;
IdMessage1.ContentType := 'multipart/related; type="text/html"';

// MessageType
// 1 = Only Text HTML
// 2 = Text + File Attachments
// 3 = Text + File Attachments + Embedded Images
// 4 = Text + Embedded Images
 
with TIdText.Create(IdMessage1.MessageParts, nil) do begin
  Body.Assign(html);
  ContentType := 'text/html';
  if MessageType = 3 then ParentPart := 1;
  CharSet     := 'iso-8859-1';
end;
 
with TIdAttachmentFile.Create(IdMessage1.MessageParts, 'C:\AT0001.JPG') do begin
  ContentID   := '0001';
  ContentType := 'image/jpeg';
  FileName    := 'AT0001.JPG';
  if MessageType = 3 then ParentPart := 0;
end;

with TIdAttachmentFile.Create(IdMessage1.MessageParts, 'C:\AT0002.JPG') do begin
  ContentID   := '0002';
  ContentType := 'image/jpeg';
  FileName    := 'AT0002.JPG';
  if MessageType = 3 then ParentPart := 0;
end;

A ver si con estas líneas de código ya te funciona. :rolleyes:

Nayla 09-11-2007 10:19:10

Buenas de nuevo :)

pues, haciendo mas pruebas he visto que me pasa una cosa un poco rara :p

el mail que envio lo envio por cada usuario que tiene asignado determinado cliente. El caso es que he visto, que el primer usuario recibe mal el mail. Pero el segundo usuario, lo recibe perfecto. Los dos pasan por la misma funcion de EnviarMail asi que no entiendo porque con la segunda pasada del bucle funciona bien y con la primera funciona mal. El mail que tendrian que recibir es el mismo.


La franja horaria es GMT +2. Ahora son las 12:22: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