Отправка email в Indy 10

Материал из DRKB

Рабочий пример отправки Email через Indy с HTML в кодировке UTF-8 и вложениями файлов.

Используется Indy 10 + Lazarus 2.2.6

type
  TDummyEncode = class
  protected
    class procedure SetCharSet(var VHeaderEncoding: char; var VCharSet: string);
  end;

class procedure TDummyEncode.SetCharSet(var VHeaderEncoding: char; var VCharSet: string);
begin
  VCharSet := IdCharsetNames[idcs_UTF_8];
  VHeaderEncoding := 'B';
end;

function SendSmtpEmail(Recipients, Subject, HTMLBody: string;
  Attachments: TStringList; SMTPHost: string; SMTPPort: Word;
  Username, Password: string; UseSSL: Boolean): Boolean;
var
  SMTP: TIdSMTP;
  Message: TIdMessage;
  SSLHandler: TIdSSLIOHandlerSocketOpenSSL;
  Builder: TIdMessageBuilderHtml;
  Attachment: TIdAttachmentFile;
  i: integer;
begin
  SMTP := TIdSMTP.Create(Application);
  Message := TIdMessage.Create(Application);
  Builder := TIdMessageBuilderHtml.Create;
  try
    // Настройка SMTP
    SMTP.Host := SMTPHost;
    SMTP.Port := SMTPPort;
    SMTP.Username := Username;
    SMTP.Password := Password;

    if UseSSL then
    begin
      SSLHandler := TIdSSLIOHandlerSocketOpenSSL.Create(Application);
      SSLHandler.SSLOptions.Method := sslvSSLv23;
      SSLHandler.SSLOptions.Mode := sslmUnassigned;
      SSLHandler.SSLOptions.VerifyMode := [];
      SSLHandler.SSLOptions.VerifyDepth := 0;
      SMTP.IOHandler := SSLHandler;
    end;

    // Создание сообщения
    Message.From.Address := Username;
    Message.From.Text := Username;
    Message.Recipients.EMailAddresses := Recipients;
    Message.Subject := Subject;
    //Message.CharSet := 'utf-8';
    Message.OnInitializeISO := TDummyEncode.SetCharSet;
    Message.CharSet := IdCharsetNames[idcs_UTF_8];
    SMTP.UseTLS := utUseExplicitTLS;

    // Создание HTML-тела письма
    Builder.Html.Text := HTMLBody;
    Builder.HtmlCharSet := 'utf-8';

    // Добавление вложений
    if Attachments.Count> 0 then
    begin
      for i := 0 to Attachments.Count - 1 do
      begin
        if (FileExists(Attachments[i])) and (Attachments[i] <> EmptyStr) then
        begin
          Builder.Attachments.Add(Attachments[i]);
        end;
      end;
    end;

    // Построение сообщения
    Builder.FillMessage(Message);

    // Отправка сообщения
    SMTP.Connect;
    try
      SMTP.Send(Message);
    finally
      SMTP.Disconnect;
    end;
  finally
    SMTP.Free;
    Message.Free;
    Builder.Free;
  end;
end;


Author: Mikhail Tchervonenko
Source: https://t.me/Delphi_Lazarus