Ir para conteúdo
Fórum Script Brasil
  • 0

Envio De Email


Annelise

Pergunta

GALERA ESTOU TENTANDO ENVIAR EMAIL ATRAVES DO DELPHI.....

ESTE E O MEU CODIGO (QUE ME PASSARAM....) SE alguém PUDER ME AJUDAR....AGRADECEREI...

unit Unit1;

interface

uses

Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Mapi,

StdCtrls, Buttons;

type

TForm1 = class(TForm)

BitBtn1: TBitBtn;

procedure BitBtn1Click(Sender: TObject);

private

{ Private declarations }

public

{ Public declarations }

end;

var

Form1: TForm1;

implementation

{$R *.DFM}

function SendEMail(Handle: THandle; Mail: TStrings):

Cardinal;

type

TAttachAccessArray = array [0..0] of TMapiFileDesc;

PAttachAccessArray = ^TAttachAccessArray;

var

MapiMessage: TMapiMessage;

Receip: TMapiRecipDesc;

Attachments: PAttachAccessArray;

AttachCount: Integer;

i1: integer;

FileName: string;

dwRet: Cardinal;

MAPI_Session: Cardinal;

WndList: Pointer;

begin

dwRet := MapiLogon(Handle,

PChar(''),

PChar(''),

MAPI_LOGON_UI or MAPI_NEW_SESSION,

0, @MAPI_Session);

if (dwRet <> SUCCESS_SUCCESS) then

begin

MessageBox(Handle,

PChar('Error while trying to send email'),

PChar('Error'),

MB_ICONERROR or MB_OK);

end

else

begin

FillChar(MapiMessage, SizeOf(MapiMessage), #0);

Attachments := nil;

FillChar(Receip, SizeOf(Receip), #0);

if Mail.Values['to'] <> '' then

begin

Receip.ulReserved := 0;

Receip.ulRecipClass := MAPI_TO;

Receip.lpszName :=

StrNew(PChar(Mail.Values['to']));

Receip.lpszAddress := StrNew(PChar('SMTP:' +

Mail.Values['to']));

Receip.ulEIDSize := 0;

MapiMessage.nRecipCount := 1;

MapiMessage.lpRecips := @Receip;

end;

AttachCount := 0;

for i1 := 0 to MaxInt do

begin

if Mail.Values['attachment' + IntToStr(i1)] = ''

then

break;

Inc(AttachCount);

end;

if AttachCount > 0 then

begin

GetMem(Attachments, SizeOf(TMapiFileDesc) *

AttachCount);

for i1 := 0 to AttachCount - 1 do

begin

FileName := Mail.Values['attachment' +

IntToStr(i1)];

Attachments[i1].ulReserved := 0;

Attachments[i1].flFlags := 0;

Attachments[i1].nPosition := ULONG($FFFFFFFF);

Attachments[i1].lpszPathName :=

StrNew(PChar(FileName));

Attachments[i1].lpszFileName :=

StrNew(PChar(ExtractFileName(FileName)));

Attachments[i1].lpFileType := nil;

end;

MapiMessage.nFileCount := AttachCount;

MapiMessage.lpFiles := @Attachments^;

end;

if Mail.Values['subject'] <> '' then

MapiMessage.lpszSubject :=

StrNew(PChar(Mail.Values['subject']));

if Mail.Values['body'] <> '' then

MapiMessage.lpszNoteText :=

StrNew(PChar(Mail.Values['body']));

WndList := DisableTaskWindows(0);

try

Result := MapiSendMail(MAPI_Session, Handle,

MapiMessage, MAPI_DIALOG, 0);

finally

EnableTaskWindows( WndList );

end;

for i1 := 0 to AttachCount - 1 do

begin

StrDispose(Attachments[i1].lpszPathName);

StrDispose(Attachments[i1].lpszFileName);

end;

if Assigned(MapiMessage.lpszSubject) then

StrDispose(MapiMessage.lpszSubject);

if Assigned(MapiMessage.lpszNoteText) then

StrDispose(MapiMessage.lpszNoteText);

if Assigned(Receip.lpszAddress) then

StrDispose(Receip.lpszAddress);

if Assigned(Receip.lpszName) then

StrDispose(Receip.lpszName);

MapiLogOff(MAPI_Session, Handle, 0, 0);

end;

end;

procedure TForm1.BitBtn1Click(Sender: TObject);

var

mail: TStringList;

begin

mail := TStringList.Create;

try

mail.values['to'] := 'annelise.soares@gmail.com'; ///AQUI VAI O EMAIL DO DESTINATARIO///

mail.values['subject'] := 'Hello'; ///AQUI O ASSUNTO///

mail.values['body'] := 'blah'; ///AQUI O TEXTO NO CORPO DO EMAIL///

mail.values['attachment0'] := 'C:\Test.txt'; ////AQUI O ENDEREÇO ONDE ENCONTRAM OS ARQUIVOS//

mail.values['attachment1']:='C:\Test2.txt'; ///IDEM - NO ATTACHMENT1 TEM QUE COLOCAR A SEQUNCIA DO EMAIL A QUAL DESEJA ENVIAR EXEMPLO: ATTACHMENT1

sendEMail(Application.Handle, mail);

finally

mail.Free;

end;

end;

end.

Link para o comentário
Compartilhar em outros sites

9 respostass a esta questão

Posts Recomendados

  • 0

TENHO TB O SEGUINTE CODIGO:

{ Seu servidor SMTP }

NMSMTP1.Host := 'santacasabh.org.br';

{ Porta SMTP, **NÃO MUDE ISTO** }

NMSMTP1.Port := 25;

{ Nome de login do usuário }

NMSMTP1.UserID := 'annelise';

{ Conecta ao servidor }

NMSMTP1.Connect;

{ Se ocorrer algum erro durante a conexão com o servidor, avise! }

if not NMSMTP1.Connected then

raise Exception.Create('Erro de conexão');

with NMSMTP1.PostMessage do

begin

{ Seu e-mail }

FromAddress := 'annelise@santacasabh.org.br';

{ Seu nome }

FromName := 'Annelise';

{ E-mail do destinatário }

ToAddress.Clear;

ToAddress.Add('annelise.soares@gmail.com');

{ Assunto da mensagem }

Subject := 'TESTE - ENVIO DE EMAIL';

{ Corpo da mensagem }

Body.Clear;

Body.Add('Primeira linha da mensagem');

Body.Add('Segunda linha da mensagem');

Body.Add(''); { Linha em branco }

Body.Add('Última linha da mensagem');

{ Anexar arquivos(Se não quiser anexar arquivos, apague as 3 linhas seguintes) }

Attachments.Clear;

{ Endereço do anexo }

Attachments.Add('c:\diretorio\arquivo.txt');

end;

{ Manda o e-mail }

NMSMTP1.SendMail;

{ Disconecta do servidor }

NMSMTP1.Disconnect;

end; { Para enviar o mesmo e-mail para vários destinatário de uma só vez basta adicionar os endereços de e-mails de todos os destinatários em NMSMTP1.PostMessage.ToAddress. }

QUE DA O SEGUINTE ERRO:

... raised excepition class ESockError with message "Host LookupFailed". ...

Link para o comentário
Compartilhar em outros sites

  • 0

OLA TO USANDO O CODIGO DO LINK DO IMASTERS QUE você ME PASSOU.....MAS TA DANDO O SEGUINTE ERRO:

ELE ABRE UMA TELA E PEDE O SEGUINTE: IdStack.pas

quando CONCELO OU IGNORO ESSA MSG DA O SEGUINTE ERRO:

Socket error #11001 Host not Found

O CODIGO E ESSE:

unit email;

interface

uses

Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,

Dialogs, IdMessage, IdBaseComponent, IdComponent, IdTCPConnection,

IdTCPClient, IdMessageClient, IdSMTP, StdCtrls, Buttons;

type

TForm1 = class(TForm)

IdMessage: TIdMessage;

IdSMTP: TIdSMTP;

edtPara: TEdit;

edtCC: TEdit;

edtCCO: TEdit;

edtAssunto: TEdit;

cbxPrioridade: TComboBox;

cbxConfirmaLeitura: TCheckBox;

botaoanexar: TBitBtn;

mmMensagem: TMemo;

BitBtn2: TBitBtn;

odanexos: TOpenDialog;

ListBox1: TListBox;

procedure botaoanexarClick(Sender: TObject);

procedure BitBtn2Click(Sender: TObject);

private

{ Private declarations }

public

{ Public declarations }

end;

var

Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.botaoanexarClick(Sender: TObject);

begin

if odAnexos.Execute then

ListBox1.Items.Add(odAnexos.FileName);

end;

procedure TForm1.BitBtn2Click(Sender: TObject);

var xAnexo : Integer;

begin

IdMessage.Recipients.EMailAddresses := edtPara.Text;

IdMessage.CCList.EMailAddresses := edtCC.Text;

IdMessage.BccList.EMailAddresses := edtCCO.Text;

//Trata a Prioridade da mensagem

case cbxPrioridade.ItemIndex of

0 : IdMessage.Priority := mpHigh;

1 : IdMessage.Priority := mpNormal;

2 : IdMessage.Priority := mpLow;

end;

IdMessage.Subject := edtAssunto.Text;

IdMessage.Body := mmMensagem.Lines;

if cbxConfirmaLeitura.Checked then

IdMessage.ReceiptRecipient.Text := IdMessage.From.Text; // Auto Resposta

//Tratando os arquivos anexos

for xAnexo := 0 to ListBox1.Items.Count-1 do

TIdAttachment.create(idmessage.MessageParts, TFileName(ListBox1.Items.Strings[xAnexo]));

IdSMTP.Connect;

try

IdSMTP.Send(IdMessage);

finally

IdSMTP.Disconnect;

end;

Application.MessageBox('Email enviado com sucesso!', 'Confirmação', MB_ICONINFORMATION + MB_OK);

end;

end.

Link para o comentário
Compartilhar em outros sites

  • 0

Olá Annelise,

ESSSE FORUM já FOI MELHOR......................................TO HORROROSO ..................

Não seja tão radical! Não é porque está havendo demora nas respostas é que o Fórum tá horroroso! Afinal, até agora muitos tem te ajudado no possível! wink.gif

Vamos ao problema agora!

Eu testei o código aki e funcionou! Qual é a versão do seu Delphi e componente Indy?

Tá configurado certo o IdSMTP, com Host, Tipo de Autenticação?

Abs.

Kiko

Link para o comentário
Compartilhar em outros sites

  • 0

Anelise...eu este codigo abaixo a algum tempo sem problemas..em varios aplicativos.....é claro que uso Outlook express....

Haaaaaaaa....e não pode ser versão do Outlook express inferior a 6.00

Tive problemas com versão anterior...e por isso tive que atualizar.

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Mapi,
StdCtrls, Buttons;

type
TForm1 = class(TForm)
BitBtn1: TBitBtn;
procedure BitBtn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.DFM}

function SendEMail(Handle: THandle; Mail: TStrings):

Cardinal;

type

TAttachAccessArray = array [0..0] of TMapiFileDesc;

PAttachAccessArray = ^TAttachAccessArray;

var 

MapiMessage: TMapiMessage; 

Receip: TMapiRecipDesc; 

Attachments: PAttachAccessArray;

AttachCount: Integer; 

i1: integer; 

FileName: string; 

dwRet: Cardinal;

MAPI_Session: Cardinal; 

WndList: Pointer; 

begin 

dwRet := MapiLogon(Handle,

PChar(''), 

PChar(''), 

MAPI_LOGON_UI or MAPI_NEW_SESSION, 

0, @MAPI_Session);



if (dwRet <> SUCCESS_SUCCESS) then 

begin

MessageBox(Handle,

PChar('Error while trying to send email'), 

PChar('Error'), 

MB_ICONERROR or MB_OK); 

end

else 

begin

FillChar(MapiMessage, SizeOf(MapiMessage), #0);

Attachments := nil;

FillChar(Receip, SizeOf(Receip), #0);



if Mail.Values['to'] <> '' then

begin

Receip.ulReserved := 0;

Receip.ulRecipClass := MAPI_TO; 

Receip.lpszName := 

StrNew(PChar(Mail.Values['to']));

Receip.lpszAddress := StrNew(PChar('SMTP:' + 

Mail.Values['to'])); 

Receip.ulEIDSize := 0; 

MapiMessage.nRecipCount := 1;

MapiMessage.lpRecips := @Receip; 

end; 



AttachCount := 0;



for i1 := 0 to MaxInt do 

begin 

if Mail.Values['attachment' + IntToStr(i1)] = ''

then 

break; 

Inc(AttachCount); 

end;



if AttachCount > 0 then 

begin 

GetMem(Attachments, SizeOf(TMapiFileDesc) *

AttachCount); 



for i1 := 0 to AttachCount - 1 do 

begin

FileName := Mail.Values['attachment' +

IntToStr(i1)]; 

Attachments[i1].ulReserved := 0; 

Attachments[i1].flFlags := 0;

Attachments[i1].nPosition := ULONG($FFFFFFFF); 

Attachments[i1].lpszPathName :=

StrNew(PChar(FileName)); 

Attachments[i1].lpszFileName :=

StrNew(PChar(ExtractFileName(FileName))); 

Attachments[i1].lpFileType := nil; 

end;

MapiMessage.nFileCount := AttachCount;

MapiMessage.lpFiles := @Attachments^; 

end; 



if Mail.Values['subject'] <> '' then

MapiMessage.lpszSubject := 

StrNew(PChar(Mail.Values['subject'])); 

if Mail.Values['body'] <> '' then 

MapiMessage.lpszNoteText :=

StrNew(PChar(Mail.Values['body']));



WndList := DisableTaskWindows(0); 

try

Result := MapiSendMail(MAPI_Session, Handle, 

MapiMessage, MAPI_DIALOG, 0); 

finally 

EnableTaskWindows( WndList );

end; 



for i1 := 0 to AttachCount - 1 do 

begin

StrDispose(Attachments[i1].lpszPathName); 

StrDispose(Attachments[i1].lpszFileName); 

end; 



if Assigned(MapiMessage.lpszSubject) then 

StrDispose(MapiMessage.lpszSubject); 

if Assigned(MapiMessage.lpszNoteText) then 

StrDispose(MapiMessage.lpszNoteText);

if Assigned(Receip.lpszAddress) then 

StrDispose(Receip.lpszAddress); 

if Assigned(Receip.lpszName) then

StrDispose(Receip.lpszName); 

MapiLogOff(MAPI_Session, Handle, 0, 0); 

end;

end;

procedure TForm1.BitBtn1Click(Sender: TObject);
var
mail: TStringList;
begin
mail := TStringList.Create;
try
mail.values['to'] := 'annelise.soares@gmail.com'; ///AQUI VAI O EMAIL DO DESTINATARIO///
mail.values['subject'] := 'Hello'; ///AQUI O ASSUNTO///
mail.values['body'] := 'blah'; ///AQUI O TEXTO NO CORPO DO EMAIL///
mail.values['attachment0'] := 'C:\Test.txt'; ////AQUI O ENDEREÇO ONDE ENCONTRAM OS ARQUIVOS//
mail.values['attachment1']:='C:\Test2.txt'; ///IDEM - NO ATTACHMENT1 TEM QUE COLOCAR A SEQUNCIA DO EMAIL A QUAL DESEJA ENVIAR EXEMPLO: ATTACHMENT1
sendEMail(Application.Handle, mail);
finally
mail.Free;
end;
end;


end.

biggrin.gif

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152k
    • Posts
      651,8k
×
×
  • Criar Novo...