Advertisement
D98rolb

SendMail

Nov 22nd, 2023
1,914
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 2.00 KB | Source Code | 0 0
  1. class function TATMail.SendMail(const aReceiver, aSender, aReplyTo, aCc,
  2.     aSubject, aBody, aAttachments: string; out aOutMessage: string): Boolean;
  3. var
  4.   smtp: TIdSMTP;      
  5.   msg: TidMessage;    
  6.   builder: TIdMessageBuilderHtml;
  7.   i: Integer;
  8.   vStrList: TStringList;        
  9.   vUserName, vPassword: String;
  10.   vHelp: IBoldHelper;            
  11. begin
  12.   Result := False;
  13.   // This will release memory for parameters later with vHelp interfaces. try/finally is not needed
  14.   vHelp := CreateBoldHelper(vStrList, smtp, msg, builder);
  15.   vStrList := TStringList.Create;
  16.   msg := TIdMessage.Create(nil);
  17.  
  18.   builder := TIdMessageBuilderHtml.Create;
  19.   builder.PlainText.Text := aBody;
  20.   builder.PlainTextCharSet := cnUTF8;
  21.  
  22.   if aAttachments <> '' then
  23.   begin
  24.     vStrList.CommaText := aAttachments;
  25.  
  26.     for i := 0 to vStrList.Count - 1 do
  27.       if FileExists(vStrList[i]) then
  28.         builder.Attachments.Add(vStrList[i]);
  29.   end;
  30.   builder.FillMessage(msg);
  31.  
  32.   msg.From.Name := aSender;
  33.   msg.From.Address := aReplyTo;
  34.   msg.Subject := aSubject;
  35.   msg.Recipients.EMailAddresses := aReceiver;
  36.   if Pos('@', aCc) > 0 then
  37.     msg.CCList.EMailAddresses := aCc;
  38.  
  39.   smtp := TIdSMTP.Create(nil);
  40.   try
  41.     smtp.Host := GetSystemConfig.SMTPHost;
  42.     // smtp.UseTLS := utNoTLSSupport;
  43.     smtp.Port := GetSystemConfig.Port;
  44.     vUserName := GetSystemConfig.UserName;
  45.     vPassword := GetSystemConfig.PassWord;
  46.     if (vUserName <> '') and (vPassword <> '') then
  47.     begin
  48.       smtp.Username := vUserName;
  49.       smtp.Password := vPassword;
  50.       smtp.AuthType := satDefault;
  51.     end
  52.     else
  53.       smtp.AuthType := satNone;
  54.  
  55.     smtp.Connect;
  56.     try
  57.       smtp.Send(msg);
  58.       aOutMessage := 'Mail sent to ' + aReceiver +'.';
  59.       Result := true;
  60.     finally
  61.       smtp.Disconnect;
  62.     end;
  63.   except
  64.     on E: Exception do  // Do not raise exception again. Only show errormessage for user
  65.       aOutMessage := Format('%s. Mail couldn''t be sent to %s.', [E.Message, aReceiver]);
  66.   end;
  67. end;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement