デルファイを活用してメールを送信する方法
メール送信を Delphi で実現するには、Indy コンポーネントライブラリの TIdSMTP と TIdMessage コンポーネントが使用できます。
まずDelphiのFormにTIdSMTPおよびTIdMessageコンポーネントを追加します。
その後、SMTPサーバアドレス、SMTPサーバポート、SMTPサーバユーザ名、SMTPサーバパスワードなどを設定したTIdSMTPコンポーネントを設置します。
次に、差出人アドレス、宛先アドレス、件名、本文など、TIdMessageコンポーネントのプロパティを設定します。
最後に、TIdSMTPコンポーネントのSendメソッドを呼び出してメールを送信します。
次のコード例を示します。
uses
IdSMTP, IdMessage, IdExplicitTLSClientServerBase, IdSSLOpenSSL;
procedure TForm1.Button1Click(Sender: TObject);
var
SMTP: TIdSMTP;
Msg: TIdMessage;
begin
SMTP := TIdSMTP.Create(nil);
Msg := TIdMessage.Create(nil);
try
SMTP.Host := 'smtp.example.com';
SMTP.Port := 25;
SMTP.Username := 'your_username';
SMTP.Password := 'your_password';
Msg.From.Address := 'sender@example.com';
Msg.Recipients.Add.Address := 'recipient@example.com';
Msg.Subject := 'Test Email';
Msg.Body.Text := 'This is a test email.';
SMTP.Connect;
try
SMTP.Send(Msg);
finally
SMTP.Disconnect;
end;
finally
SMTP.Free;
Msg.Free;
end;
end;
上記のコードでは, smtp.example.comを実際のSMTPサーバアドレスに, your_username, your_passwordを実際のSMTPサーバのログイン情報に置き換え, sender@example.com, recipient@example.comを実際の送信者, 送信先アドレスに置き換える必要があります.
SMTPサーバーを利用するには、SMTPサーバーのサポートが必要で、そのSMTPサーバーとネットワーク接続を行う必要があります。また、一部のSMTPサーバーはSSLまたはTLSで暗号化した接続を必要とするため、TIdSSLIOHandlerSocketOpenSSLコンポーネントで暗号化接続を行うことができます。