0
I am using the following code snippet for sending email in Delphi, but when trying to send an attachment, the attachment becomes part of the body of the email. What could be wrong?
function SendEmail(sendTo, subject, body: string;
attachFiles: TStringList; smtpHost: string; smtpPort: Integer; smtpUser,
smtpPass: string; tls: TIdUseTLS; respoderPara: string): boolean;
var
smtp: TIdSmtp;
ssl: TIdSSLIOHandlerSocketOpenSSL;
msg: TIdMessage;
i: Integer;
replyTo: TIdEMailAddressItem;
IdAttachmentFile : TIdAttachmentFile;
begin
smtp:=TIdSmtp.Create(nil);
ssl:=TIdSSLIOHandlerSocketOpenSSL.Create(nil);
msg:=TIdMessage.Create(nil);
try
try
smtp.Host := smtpHost;
smtp.Port := smtpPort;
smtp.Username := smtpUser;
smtp.Password := smtpPass;
//smtp.OnConnected :=IdSMTP1Connected;
//smtp.OnDisconnected :=IdSMTP1Disconnected;
//smtp.OnFailedRecipient :=IdSMTP1FailedRecipient;
//smtp.OnStatus :=IdSMTP1Status;
//smtp.OnTLSNotAvailable :=IdSMTP1TLSNotAvailable;
//smtp.OnWork :=IdSMTP1Work;
if not (tls=utNoTLSSupport) then
begin
ssl.Destination := smtpHost + ':' + IntToStr(smtpPort);
ssl.Host := smtpHost;
ssl.Port := smtpPort;
ssl.SSLOptions.Method := sslvTLSv1;
//ssl.OnStatusInfo:=IdSSLIOHandlerSocketOpenSSL1StatusInfo;
//ssl.OnGetPassword:=IdSSLIOHandlerSocketOpenSSL1GetPassword;
//ssl.OnStatus:=IdSSLIOHandlerSocketOpenSSL1Status;
smtp.IOHandler := ssl;
smtp.UseTLS := tls;
end;
msg.Recipients.EMailAddresses := sendTo;
msg.Subject := subject;
msg.ContentType := 'text/html';
msg.Body.Text := body;
if respoderPara <> '' then
begin
replyTo := msg.ReplyTo.Add;
replyTo.Name := 'SYNS - Contato';
replyTo.Address := respoderPara;
end;
if(Assigned(attachFiles)) then
begin
for i := 0 to attachFiles.Count - 1 do
begin
if FileExists(attachFiles[i]) then
begin
IdAttachmentFile := TIdAttachmentFile.Create(msg.MessageParts, attachFiles[i]); //Incluindo o anexo na mensagem
IdAttachmentFile.ContentType := 'application/pdf;'; //Informando o tipo MIME do anexo. IMPORTANTE! Colocar o tipo MIME + ; (ponto-e-vírgula)
IdAttachmentFile.FileName := ExtractFileName(attachFiles[i]); //Nome do arquivo
//TIdAttachmentFile.Create(msg.MessageParts, attachFiles[i]);
end;
end;
end;
smtp.Connect;
smtp.Send(msg);
smtp.Disconnect;
result:=true;
finally
msg.Free;
ssl.Free;
smtp.Free;
end;
except
result:=false;
end;
end;