•  

ГлавнаяIndyIdSMTP → Утилита командной строки с поддержкой авторизации на почтовом сервере IdSMTP

Создано: 30.05.2010 1:09:34 · Исправлено: 30.05.2010 1:10:16 · Прочтений: 3691

Небольшая утилита с исходниками, при помощи которой можно отправить файл любому количеству получателей из командной строки.
program sendmail;

{

  fake sendmail for windows

  Copyright (c) 2004, Byron Jones, [email protected]
  All rights reserved.

  version 3
    - smtp authentication support
    - clearer error message when missing from or to address
    - optional error logging
    - adds date header if missing

  version 2
    - reads default domain from registry (.ini setting overrides)

  version 1
    - initial release

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
  are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

    * Neither the name of the glob nor the names of its contributors may
      be used to endorse or promote products derived from this software
      without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

}

{$APPTYPE CONSOLE}

uses
  Windows, Classes, SysUtils, Registry, IniFiles, IDSmtp, IdMessage, IdEmailAddress;

var

  smtpServer    : string;
  defaultFrom   : string;
  defaultDomain : string;
  messageContent: string;
  errorLogFile  : string;
  authUsername  : string;
  authPassword  : string;

  i    : integer;
  s    : string;
  ss   : TStringStream;
  msg  : TIdMessage;
  f    : TextFile;
  addr : TIdEMailAddressItem;

begin

  // read default domain from registry

  with TRegistry.Create do
  try
    RootKey := HKEY_LOCAL_MACHINE;
    if (OpenKeyReadOnly('\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters')) then
      defaultDomain := ReadString('Domain');
  finally
    Free;
  end;

  // read ini

  with TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini')) do
  try

    smtpServer    := ReadString('sendmail', 'smtp_server',    'mail.mydomain.com');
    defaultDomain := ReadString('sendmail', 'default_domain', defaultDomain);
    defaultFrom   := ReadString('sendmail', 'default_from',   defaultFrom);
    errorLogFile  := ReadString('sendmail', 'error_logfile',  '');
    authUsername  := ReadString('sendmail', 'auth_username',  '');
    authPassword  := ReadString('sendmail', 'auth_password',  '');

    if (smtpServer = 'mail.mydomain.com') or (defaultDomain = 'mydomain.com') then
    begin
      writeln('you must configure the smtp_server and default_domain in ' + fileName);
      halt(1);
    end;

  finally
    Free;
  end;

  if (errorLogFile <> '') and (ExtractFilePath(errorLogFile) = '') then
    errorLogFile := ExtractFilePath(ParamStr(0)) + errorLogFile;

  // read email from stdin

  messageContent := '';
  while (not eof(Input)) do
  begin
    readln(Input, s);
    messageContent := messageContent + s + #13#10;
  end;

  // deliver message

  try

    // load message into stream (TidMessage expects message to end in ".")

    ss  := TStringStream.Create(messageContent + #13#10'.'#13#10);
    msg := nil;

    try

      // load message

      msg := TIdMessage.Create(nil);
      msg.LoadFromStream(ss);

      // check for from and to

      if (Msg.From.Address = '') then
        if (defaultFrom = '') then
          raise Exception.Create('email is missing sender''s address')
        else
          Msg.From.Address := defaultFrom;

      if (Msg.Recipients.Count = 0) then
        if (ParamCount = 0)
          then
            raise Exception.Create('email is missing recipient''s address')
          else
            for i:= 1 to ParamCount do
              begin
                addr := Msg.Recipients.Add;
                addr.Address := ParamStr(i);
              end;



      // add date header if missing

      if (Msg.Headers.Values['date'] = '') then
        Msg.Date := now;

      // append default domain

      if (Pos('@', Msg.From.Address) = 0) then
        Msg.From.Text := Msg.From.Address + '@' + defaultDomain;

      for i := 0 to msg.Recipients.Count - 1 do
        if (pos('@', msg.Recipients[i].Address) = 0) then
          msg.Recipients[i].Address := msg.Recipients[i].Address + '@' + defaultDomain;

      // deliver message

      with TIdSMTP.Create(nil) do
      try
        Host     := smtpServer;
        if (authUsername <> '') then
        begin
          AuthenticationType := atLogin;
          Username := authUsername;
          Password := authPassword;
        end;
        Connect;
        Send(msg);
      finally
        Free;
      end;

    finally
      msg.Free;
      ss.Free;
    end;

  except
    on e:Exception do
    begin
      writeln('sendmail: error during delivery: ' + e.message);

      if (errorLogFile <> '') then
      begin

        AssignFile(f, errorLogFile);
        try

          if (not FileExists(errorLogFile)) then
          begin
            ForceDirectories(ExtractFilePath(errorLogFile));
            Rewrite(f);
          end
          else
            Append(f);

          writeln(f, '[' + DateTimeToStr(Now) + '] ' + e.message);
          closeFile(f);

        except
          on e:Exception do
            writeln('sendmail: error writing to error.log: ' + e.message);
        end;

      end;

      halt(1);
    end;
  end;

end.


Скачать исходный код утилиты для отправки из командной строки при помощи IdSMTP