Envio de email delphi

Delphi

06/05/2018

Depois de passar certo trabalho para configurar e testar, decidi postar aqui um código fonte bem simples e que funciona para envio de emails utilizando o delphi e indy 10.

Testes utilizando o Indy 10 para servidores Gmail, Hotmail, Yahoo e Servidor Próprio!

Abaixo segue o código fonte:

var
IdSMTP1: TIdSMTP;
Idmessage: TIdMessage;
TextoMsg: TidText;
IdSSL: TIdSSLIOHandlerSocketOpenSSL;
begin
IdSMTP1 := TIdSMTP.create(nil);
IdSMTP1.ConnectTimeout := 10000;
IdSMTP1.ReadTimeout := 10000;

IdMessage := TIdMessage.create(nil);
IdMessage.Clear;
IdMessage.CharSet := 'iso-8859-1';
IdMessage.Encoding := MeMIME;
IdMessage.ContentType := 'multipart/related' ;
IdMessage.subject := 'Assunto';

textomsg := TIdText.Create(IdMessage.MessageParts);
textomsg.Body.Text := 'Se você consegue ler isto então é porque funcionou o teste!';
textomsg.ContentType := 'text/html';

if ((cbtipo.itemindex = 0) or (cbtipo.itemindex = 2)) then
begin
// GMAIL e YAHOO

if cbtipo.itemindex = 0 then
begin
idSMTP1.Host := 'smtp.gmail.com';
idSMTP1.Username := 'email@gmail.com';
idSMTP1.Password := 'senha';
end
else begin
idSMTP1.Host := 'smtp.mail.yahoo.com';
idSMTP1.Username := 'email@yahoo.com.br';
idSMTP1.Password := 'senha';
end;

IdMessage.from.address := idSMTP1.Username;
IdMessage.recipients.emailaddresses := 'teste@hotmail.com';

with idSMTP1 do
begin
IdSSL := nil;

try
port := 465;
IdSSL := TIdSSLIOHandlerSocketOpenSSL.Create( nil );
IdSMTP1.IOHandler := IdSSL;
UseTLS := utUseImplicitTLS;
except on E: Exception do
begin
IOHandler := TIdIOHandler.MakeDefaultIOHandler( nil );
UseTLS := utNoTLSSupport;
end;
end;

if Assigned(IdSSL) then
begin
IdSSL.SSLOptions.Method := sslvSSLv3;
IdSSL.SSLOptions.Mode := sslmClient;
end;

AuthType := satDefault;
end;
end;

//***************************** xxxxxxxxxxxxxxxx ***************************

if ((cbtipo.itemindex = 1) or (cbtipo.itemindex = 3)) then
begin
// HOTMAIL e SERVIDOR PROPRIO

idSMTP1.Port := 587;

if cbtipo.itemindex = 1 then
begin
idSMTP1.Host := 'smtp.live.com';
idSMTP1.Username := 'email@hotmail.com';
idSMTP1.Password := 'senha';
end
else begin
idSMTP1.Host := 'smtp.servidorproprio.inf.br';
idSMTP1.Username := 'email@servidorproprio.inf.br';
idSMTP1.Password := 'senha';
end;

IdMessage.from.address := idSMTP1.Username;
IdMessage.recipients.emailaddresses := 'teste@hotmail.com';

with idSMTP1 do
begin
IdSSL := nil;

try
IdSSL := TIdSSLIOHandlerSocketOpenSSL.Create( nil );
IdSMTP1.IOHandler := IdSSL;
UseTLS := utUseExplicitTLS;

IdSSL.SSLOptions.Method := sslvTLSv1;
IdSSL.PassThrough := true;
except on E: Exception do
begin
IOHandler := TIdIOHandler.MakeDefaultIOHandler( nil );
UseTLS := utNoTLSSupport;
end;
end;
end;
end;

idSMTP1.Connect;

try
idSMTP1.send(IdMessage);
except
on E : Exception do
begin
Memo1.Lines.Add(e.Message);
end;
end;

idSMTP1.Disconnect;

IdMessage.Free;
IdSMTP1.Free;
Diego Bolognini

Diego Bolognini

Curtidas 0

Melhor post

Carlos Eduardo

Carlos Eduardo

06/05/2018

Eu fiz dessa forma a um tempo atras.

[code=delphi]
unit uClass_Mail;

interface

// É necessario Configurar o host
// no gmail basta Ativa o POP3 ou algo parecido

uses
IdSMTP, IdSSLOpenSSL, IdMessage, IdText, IdAttachmentFile,
IdExplicitTLSClientServerBase,Vcl.StdCtrls, System.SysUtils, Vcl.Dialogs,
System.UITypes;

type
TMail = Class
Strict Private
// Parametros de Configuração de Email
Port: integer; // porta do servidor de email ex // ''''''''465'''''''' porta do gmail
host: String; // host do servidor de email ex // ''''''''smtp.gmail.com'''''''' host do gmail
UserName: string; // username do servidor de email ex // ''''''''devsouza01@gmail.com''''''''
Password: String; // Senha do Username(Email) do servidor de Email
// Conteudo da Mensagem

private
IdSSLIOHandlerSocket: TIdSSLIOHandlerSocketOpenSSL;
IdSMTP: TIdSMTP;
IdMessage: TIdMessage;
IdText: TIdText;
// Conteudo do Email
FFromAddress: String; // Endereco de Partida
FFromName: String; // Nome Do usuario de Partida
FRecipientsAddress: String; // Endereco do Destinatario
FBody: String; // Corpo da Mensagem
FSubject: String; // Assunto
FReplyToAddress: String; // Responder a
FAttachment: String; // Caminho do Anexo
procedure SetBody(const Value: String);
procedure SetFromAddress(const Value: String);
procedure SetFromName(const Value: String);
procedure SetRecipientsAddress(const Value: String);
procedure SetReplyToAddress(const Value: String);
procedure SetSubject(const Value: String);
procedure SetAttachment(const Value: String);
function GetAttachment: String;
function GetBody: String;
function GetFromAddress: String;
function GetFromName: String;
function GetRecipientsAddress: String;
function GetReplyToAddress: String;
function GetSubject: String;
Public
// proriedades
property FromAddress : String read GetFromAddress write SetFromAddress;
property FromName : String read GetFromName write SetFromName;
property ReplyToAddress : String read GetReplyToAddress write SetReplyToAddress;
property RecipientsAddress : String read GetRecipientsAddress write SetRecipientsAddress;
property Subject : String read GetSubject write SetSubject;
Property Body : String read GetBody write SetBody;
property Attachment : String read GetAttachment write SetAttachment;

// Metodos
procedure Send(); // Procedure para enviar Email
constructor Create();
destructor Destroy();override;
End;

implementation

{ TMail }

constructor TMail.Create;
begin
// pegar do arquivo .ini ou Direto da base de dados
Self.Port := 465;
Self.host := ''''''''smtp.gmail.com'''''''';
Self.UserName := ''''''''sistema.convexus@gmail.com'''''''';
Self.Password := ''''''''@Function773'''''''';


// instanciação dos objetos Necesarios
IdSSLIOHandlerSocket := TIdSSLIOHandlerSocketOpenSSL.Create();
IdSMTP := TIdSMTP.Create();
IdMessage := TIdMessage.Create();
try
// Configuração do protocolo SSL (TIdSSLIOHandlerSocketOpenSSL)
IdSSLIOHandlerSocket.SSLOptions.Method := sslvSSLv23;
IdSSLIOHandlerSocket.SSLOptions.Mode := sslmClient;

// Configuração do servidor SMTP (TIdSMTP)
IdSMTP.IOHandler := IdSSLIOHandlerSocket;
IdSMTP.UseTLS := utUseImplicitTLS;
IdSMTP.AuthType := satDefault;

// Configuração do servidor de Email
IdSMTP.Port := Self.Port;
IdSMTP.host := Self.host;
IdSMTP.UserName := Self.UserName;
IdSMTP.Password := Self.Password;

except
on e: Exception do
ShowMessage(''''''''Erro ao instanciar Email.'''''''');
end;
end;

destructor TMail.Destroy;
begin
FreeAndNil(IdSSLIOHandlerSocket);
FreeAndNil(IdSMTP);
FreeAndNil(IdMessage);
inherited;
end;

function TMail.GetAttachment: String;
begin
Result := FAttachment;
end;

function TMail.GetBody: String;
begin
if Self.FBody.IsEmpty then
raise Exception.Create(''''''''Corpo da Mensagem Vazio'''''''')
else
Result := FBody;
end;

function TMail.GetFromAddress: String;
begin
Result := FFromAddress;
end;

function TMail.GetFromName: String;
begin
Result := FFromName;
end;

function TMail.GetRecipientsAddress: String;
begin
if Self.FRecipientsAddress.IsEmpty then
raise Exception.Create(''''''''Sem destinatario.'''''''')
else
Result := FRecipientsAddress;
end;

function TMail.GetReplyToAddress: String;
begin
Result := FReplyToAddress;
end;

function TMail.GetSubject: String;
begin
if Self.FSubject.IsEmpty then
raise Exception.Create(''''''''Sem Assunto.'''''''')
else
Result := FSubject;
end;

procedure TMail.Send;
begin
try
// Configuração da mensagem (TIdMessage)
IdMessage.From.Address := self.FromAddress;
IdMessage.From.Name := self.FromName;
IdMessage.ReplyTo.EMailAddresses := self.ReplyToAddress;
IdMessage.Recipients.Add.Text := self.RecipientsAddress;
IdMessage.Subject := self.Subject;
IdMessage.Encoding := meMIME;

// Configuração do corpo do email (TIdText)
IdText := TIdText.Create(IdMessage.MessageParts);


IdText.Body.Add(self.Body); // Corpo da mensagem

IdText.ContentType := ''''''''text/html; charset=utf-8'''''''';// TextPlan = Texto Puro; Text/html = Formatado Com template

//Opcional - Anexo da mensagem (TIdAttachmentFile)
if not(Attachment.IsEmpty) then
if FileExists(Self.Attachment) then
begin
TIdAttachmentFile.Create(IdMessage.MessageParts, Self.Attachment);
end;

except
on e : Exception do ShowMessage(e.Message);
end;

try
// Conexão e autenticação
try
IdSMTP.Connect;
IdSMTP.Authenticate;
except
on e: Exception do
begin
//ShowMessage(e.Message);
Exit;
end;
end;

// Envio da mensagem
try
IdSMTP.Send(IdMessage);
// ShowMessage(''''''''Mensagem Enviada!'''''''');
except
On e: Exception do ShowMessage(e.Message);
end;
finally
// desconecta do servidor
IdSMTP.Disconnect;
// liberação da DLL
UnLoadOpenSSLLibrary;
end;
end;

procedure TMail.SetAttachment(const Value: String);
begin
FAttachment := Value;
end;

procedure TMail.SetBody(const Value: String);
begin
FBody := Value;
end;

procedure TMail.SetFromAddress(const Value: String);
begin
FFromAddress := Value;
end;

p
GOSTEI 1
POSTAR