Delphi. Как отправлять Email из VCL приложения? | >Digital-flame

Delphi. как отправлять email из vcl приложения? | >digital-flame

uses

  Windows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,

  Dialogs,StdCtrls,ComCtrls,IdBaseComponent,IdComponent,IdTCPConnection,

  IdTCPClient,IdExplicitTLSClientServerBase,IdMessageClient,IdSMTPBase,IdMessage,

  IdSMTP,IdIOHandler,IdIOHandlerSocket,IdIOHandlerStack,IdSSL,IdSSLOpenSSL,IdText;

procedureTForm1.Button1Click(Sender:TObject);

var

  // variáveis e objetos necessários para o envio

  IdSSLIOHandlerSocket:TIdSSLIOHandlerSocketOpenSSL;

  IdSMTP:TIdSMTP;

  IdMessage:TIdMessage;

  IdText:TIdText;

  sAnexo:string;

begin

  // instanciação dos objetos

  IdSSLIOHandlerSocket:=TIdSSLIOHandlerSocketOpenSSL.Create(Self);

  IdSMTP:=TIdSMTP.Create(Self);

  IdMessage:=TIdMessage.Create(Self);

  try

    // Configuração do protocolo SSL (TIdSSLIOHandlerSocketOpenSSL)

    IdSSLIOHandlerSocket.SSLOptions.Method:=sslvSSLv23;

    IdSSLIOHandlerSocket.SSLOptions.Mode:=sslmClient;

    // Configuração do servidor SMTP (TIdSMTP)

    IdSMTP.IOHandler:=IdSSLIOHandlerSocket;

    IdSMTP.UseTLS:=utUseImplicitTLS;

    IdSMTP.AuthType:=satDefault;

    IdSMTP.Port:=465;

    IdSMTP.Host:=‘smtp.gmail.com’;

    IdSMTP.Username:=‘MYLOGIN@gmail.com’;

    IdSMTP.Password:=‘MYPASS’;

    // Configuração da mensagem (TIdMessage)

    IdMessage.From.Address:=‘MYLOGIN@gmail.com’;

    IdMessage.From.Name:=‘John Smith’;

    IdMessage.ReplyTo.EMailAddresses:=IdMessage.From.Address;

    IdMessage.Recipients.Add.Text:=‘receiver@example.com’;

    IdMessage.Subject:=‘Hello World’;

    IdMessage.Encoding:=meMIME;

    // Configuração do corpo do email (TIdText)

    IdText:=TIdText.Create(IdMessage.MessageParts);

    IdText.Body.Add(‘The body of the e-mail goes here’);

    IdText.ContentType:=‘text/plain; charset=iso-8859-1’;

    // Conexão e autenticação

    try

      IdSMTP.Connect;

      IdSMTP.Authenticate;

    except

      onE:Exceptiondo

      begin

        MessageDlg(‘Cannot authenticate: ‘

          E.Message,mtWarning,[mbOK],);

        Exit;

      end;

    end;

    // Envio da mensagem

    try

      IdSMTP.Send(IdMessage);

      MessageDlg(‘Message sent successfully!’,mtInformation,[mbOK],);

    except

      OnE:Exceptiondo

      begin

        MessageDlg(‘Error while sending a message: ‘

          E.Message,mtWarning,[mbOK],);

      end;

    end;

  finally

    // liberação dos objetos da memória

    FreeAndNil(IdMessage);

    FreeAndNil(IdSSLIOHandlerSocket);

    FreeAndNil(IdSMTP);

  end;

end;

Encrypt email in delphi – s/mime with rc2, 3des and rsaes-oaep¶

In previous section, I introduced how to send email with digital
signature. In this section, I will introduce how to encrypt email with digital certificate
in Delphi.

[Delphi – Email Encryption (S/MIME) – Example]

The following example codes demonstrate how to
encrypt email with digital certificate in Delphi.

unitUnit1;interfaceusesWindows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls,EASendMailObjLib_TLB;// add EASendMail unittypeTForm1=class(TForm)Button1:TButton;procedureButton1Click(Sender:TObject);private{ Private declarations }public{ Public declarations }end;constConnectNormal=;ConnectSSLAuto=1;ConnectSTARTTLS=2;ConnectDirectSSL=3;ConnectTryTLS=4;CRYPT_MACHINE_KEYSET=32;CRYPT_USER_KEYSET=4096;CERT_SYSTEM_STORE_CURRENT_USER=65536;CERT_SYSTEM_STORE_LOCAL_MACHINE=131072;varForm1:TForm1;implementation{$R *.dfm}procedureTForm1.Button1Click(Sender:TObject);varoSmtp:TMail;oEncryptCert:TCertificate;beginoSmtp:=TMail.Create(Application);oSmtp.LicenseCode:='TryIt';// Set your sender email addressoSmtp.FromAddr:='test@emailarchitect.net';// Add recipient email addressoSmtp.AddRecipientEx('support@emailarchitect.net',);// Set email subjectoSmtp.Subject:='test encrypted email from Delphi with digital signature';// Set body textoSmtp.BodyText:='this is a test encrypted email sent from Delphi with digital signature';// Add digital signatureifnotoSmtp.SignerCert.FindSubject('test@emailarchitect.net',CERT_SYSTEM_STORE_CURRENT_USER,'my')thenbeginShowMessage(oSmtp.SignerCert.GetLastError());exit;end;ifnotoSmtp.SignerCert.HasCertificateThenbeginShowMessage('Signer certificate has no private key, ' 'this certificate can not be used to sign email');end;// Find the encrypting certificate for every recipientsoEncryptCert:=TCertificate.Create(Application);ifnotoEncryptCert.FindSubject('support@emailarchitect.net',CERT_SYSTEM_STORE_CURRENT_USER,'AddressBook')thenifnotoEncryptCert.FindSubject('support@emailarchitect.net',CERT_SYSTEM_STORE_CURRENT_USER,'my')thenbeginShowMessage(oEncryptCert.GetLastError());exit;end;// Add encrypting certificateoSmtp.RecipientsCerts.Add(oEncryptCert.DefaultInterface);// Your SMTP server addressoSmtp.ServerAddr:='smtp.emailarchitect.net';// User and password for ESMTP authentication, if your server doesn't require// user authentication, please remove the following codesoSmtp.UserName:='test@emailarchitect.net';oSmtp.Password:='testpassword';// ConnectTryTLS means if server supports SSL/TLS connection, SSL/TLS is used automaticallyoSmtp.ConnectType:=ConnectTryTLS;// If your server uses 587 port// oSmtp.ServerPort := 587;// If your server uses 25/587/465 port with SSL/TLS// oSmtp.ConnectType := ConnectSSLAuto;// oSmtp.ServerPort := 587; // 25 or 587 or 465ShowMessage('start to send email ...');ifoSmtp.SendMail()=thenShowMessage('email was sent successfully!')elseShowMessage('failed to send email with the following error: ' oSmtp.GetLastErrDescription());end;end.

If you received digital signed and encrypted email by Windows Mail(Outlook Express),
it looks like this:

Delphi sign and encrypt email - s/mime

Send mass emails using database queue in delphi¶

In previous section, I introduced how to send email EASendMail
Service Queue. In this section, I will introduce how to send mass emails with advanced
database queue in Delphi.

Introduction

Although EASendMail service provides a faster way to send email in background, but
there are thousands of emails in a task, the SendMailToQueue will be invoked for
thousands times, obviously it is not effect way.

Therefore, EASendMail service provides a more effective way to send mass emails.
In short, you just need to submit your database connection and record set once,
EASendMail service will pick up the record set in background and send email to each
record one by one. It is very useful to send mass emails in ASP web application.

send email using database queue in ASP/VBScript

To better understand the database queue, we need to create three tables in your
SQL database like this:

CREATETABLE[dbo].[rcpts]([uid][bigint]IDENTITY(1,1)NOTNULL,[name][nvarchar](50)NULL,[email][nvarchar](128)NOTNULL,CONSTRAINT[PK_rcpts]PRIMARYKEYCLUSTERED([uid]ASC)WITH(PAD_INDEX=OFF,STATISTICS_NORECOMPUTE=OFF,IGNORE_DUP_KEY=OFF,ALLOW_ROW_LOCKS=ON,ALLOW_PAGE_LOCKS=ON)ON[PRIMARY])ON[PRIMARY]GOCREATETABLE[dbo].[errorlog]([uid][bigint]IDENTITY(1,1)NOTNULL,[email][nvarchar](128)NULL,[server][nvarchar](50)NULL,[errorcode][nvarchar](50)NULL,[errordescription][nvarchar](255)NULL,CONSTRAINT[PK_errorlog]PRIMARYKEYCLUSTERED([uid]ASC)WITH(PAD_INDEX=OFF,STATISTICS_NORECOMPUTE=OFF,IGNORE_DUP_KEY=OFF,ALLOW_ROW_LOCKS=ON,ALLOW_PAGE_LOCKS=ON)ON[PRIMARY])ON[PRIMARY]GOCREATETABLE[dbo].[sentlog]([uid][bigint]IDENTITY(1,1)NOTNULL,[server][nvarchar](50)NULL,[email][nvarchar](128)NULL,CONSTRAINT[PK_sentlog]PRIMARYKEYCLUSTERED([uid]ASC)WITH(PAD_INDEX=OFF,STATISTICS_NORECOMPUTE=OFF,IGNORE_DUP_KEY=OFF,ALLOW_ROW_LOCKS=ON,ALLOW_PAGE_LOCKS=ON)ON[PRIMARY])ON[PRIMARY]GO

Then insert two records in table ‘rcpts’ like this:

SQL table sample

[Delphi – Send mass emails with EASendMail Service Database Queue – Example]

The following example codes demonstrate how to send mass emails using email queue database in Delphi.

unitUnit1;interfaceusesWindows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls,EASendMailObjLib_TLB;// add EASendMail unittypeTForm1=class(TForm)Button1:TButton;procedureButton1Click(Sender:TObject);private{ Private declarations }public{ Public declarations }end;constConnectNormal=;ConnectSSLAuto=1;ConnectSTARTTLS=2;ConnectDirectSSL=3;ConnectTryTLS=4;varForm1:TForm1;implementation{$R *.dfm}procedureTForm1.Button1Click(Sender:TObject);varoSmtp:TMail;beginoSmtp:=TMail.Create(Application);oSmtp.LicenseCode:='TryIt';// Set your sender email addressoSmtp.FromAddr:='test@emailarchitect.net';// Set email subjectoSmtp.Subject:='simple email from Delphi project';// change it to your sql server address, database, user and password.// The server/instance name syntax used in the server option is the same for all SQL Server connection strings.// e.g.: Server=serveraddressinstancename;// EASendMail will use the following connection to connect to the database,// the syntax is same as ADO connection object.oSmtp.AddHeader('X-Data-Connection','Driver={SQL Native Client};Server=serveraddress;Database=database;Uid=user;Pwd=password;');// For more connection string// MS SQL Server 2000// 'Driver={SQL Server};Server=localhost;Database=pubs;Uid=sa;Pwd=asdasd;'// MS SQL Server 2005// 'Driver={SQL Server Native Client};Server=localhost;Database=pubs;Uid=sa;Pwd=asdasd;'// MS SQL Server 2005 Native Provider// 'Provider=SQLNCLI;Server=serveraddress;Database=database;Uid=user;Pwd=password;'// MS SQL Server 2008// 'Driver={SQL Server Native Client 10.0};Server=localhost;Database=myDataBase;Uid=myUsername;Pwd=myPassword;'// MS SQL Server 2008 Native Provider// 'Provider=SQLNCLI10;Server=serveraddress;Database=database;Uid=user;Pwd=password;'// MS SQL Server 2022// 'Driver={SQL Server Native Client 11.0};Server=localhost;Database=myDataBase;Uid=myUsername;Pwd=myPassword;'// MS SQL Server 2022 Native Provider// 'Provider=SQLNCLI11;Server=serveraddress;Database=database;Uid=user;Pwd=password;'// EASendMail will select the fields by the following sql statement// before sending email,// then pick the recipient address from specified field.oSmtp.AddHeader('X-Sql-Select','SELECT uid, name, email FROM Recipients');// Pick "name" field as the recipient name and "email" field as the recipient address.// You can also use {$var_srecord:fieldname} to pick any field in X-Sql-Select statement// and put it to subject, bodytext, then EASendMail will replace it automatially.oSmtp.DisplayTo:='"{$var_srecord:name}" <{$var_srecord:email}>';oSmtp.AddHeader('X-Rcpt-To','{$var_srecord:email}');// EASendMail service will execute the following sql statement on// every email was sent successfully.oSmtp.AddHeader('X-Sql-OnSentSuccess','INSERT INTO sentlog (server, email) VALUES(''{$var_server}'', ''{$var_rcptaddr}'')');// EASendMail service will execute the following sql statement on// every email could not be sent.oSmtp.AddHeader('X-Sql-OnSentError','INSERT INTO errorlog(email, server, errorcode, errordescription) ' 'VALUES(''{$var_rcptaddr}'', ''{$var_server}'', ''{$var_errcode}'', ''{$var_errdesc}'')');oSmtp.BodyText:='Hi {$var_srecord:name}, ' #13#10 'Send email with queue.' #13#10 #13#10 'From:Tester' #13#10 'To:{$var_srecord:email}' #13#10 #13#10 'Your id in database is {$var_srecord:uid}.' #13#10;// {$var_srecord:uid} {$var_srecord:name} {$var_srecord:email} in// body text will be replaced by EASendMail automatically.// Your SMTP server addressoSmtp.ServerAddr:='smtp.emailarchitect.net';// User and password for ESMTP authentication, if your server doesn't require// user authentication, please remove the following codesoSmtp.UserName:='test@emailarchitect.net';oSmtp.Password:='testpassword';// ConnectTryTLS means if server supports SSL/TLS connection, SSL/TLS is used automaticallyoSmtp.ConnectType:=ConnectTryTLS;// If your server uses 587 port// oSmtp.ServerPort := 587;// If your server uses 25/587/465 port with SSL/TLS// oSmtp.ConnectType := ConnectSSLAuto;// oSmtp.ServerPort := 587; // 25 or 587 or 465ShowMessage('start to send email ...');// You just need to change SendMail method to SendMailToQueue method in// your Delphi application, then EASendMail uses queue to send email.// SendMailToQueue can be used in windows application as well.ifoSmtp.SendMailToQueue()=thenShowMessage('email was sent to queue successfully!')elseShowMessage('failed to send email with the following error: ' oSmtp.GetLastErrDescription());end;end.

With above codes, no matter how many records in your table, SendMailToQueue is only
invoked once and EASendMail service will pick up records in background and send
the email based on each record to recipient one by one. It also inserts the results
back to “errorlog” and “sentlog” tables automatically. You can open EASendMail Service
Manager to monitor the queue and view Journal -> System Error to check if there
is error with your database connection and SQL statement.

Send email in delphi – tutorial¶

This tutorial introduces how to send email in Delphi using SMTP.
It also demonstrates SSL, S/MIME, Embedded Images, Multiple Threads, Email Queue, Exchange WebDAV and Exchange Web Service (EWS) usage.

Send email in a simple Delphi project

To better demonstrate how to send email using SMTP protocol, let’s create a Delphi
Standard EXE project at first, then add a TButton on the Form, double-click this
button. It is like this:

Похожее:  Катрен личный кабинет

Delphi form project

Add Reference

To use EASendMail SMTP ActiveX Object in your Delphi project, the first step is “Add Unit file of EASendMail to your project”.
Please go to C:ProgramFilesEASendMailIncludedelphi or
C:ProgramFiles(x86)EASendMailIncludedelphi folder, find EASendMailObjLib_TLB.pas,
and then copy this file to your project folder.

unitUnit1;interface// include EASendMailObjLib_TLB unit to your Delphi ProjectusesWindows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,EASendMailObjLib_TLB,StdCtrls;

You can also create “EASendMailObjLib_TLB.pas” manually like this:

Then you can start to use it in your Delphi Project.

[Delphi – Send email – Example]

Now add the following codes to the project and change From, To, Server, User and
Password to corresponding value.
The following example codes demonstrate how to send email using SMTP protocol in Delphi project.

unitUnit1;interfaceusesWindows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls,EASendMailObjLib_TLB;// add EASendMail unittypeTForm1=class(TForm)Button1:TButton;procedureButton1Click(Sender:TObject);private{ Private declarations }public{ Public declarations }end;constConnectNormal=;ConnectSSLAuto=1;ConnectSTARTTLS=2;ConnectDirectSSL=3;ConnectTryTLS=4;varForm1:TForm1;implementation{$R *.dfm}procedureTForm1.Button1Click(Sender:TObject);varoSmtp:TMail;beginoSmtp:=TMail.Create(Application);oSmtp.LicenseCode:='TryIt';// Set your sender email addressoSmtp.FromAddr:='test@emailarchitect.net';// Add recipient email addressoSmtp.AddRecipientEx('support@emailarchitect.net',);// Set email subjectoSmtp.Subject:='simple email from Delphi project';// Set email bodyoSmtp.BodyText:='this is a test email sent from Delphi project, do not reply';// Your SMTP server addressoSmtp.ServerAddr:='smtp.emailarchitect.net';// User and password for ESMTP authentication, if your server doesn't require// user authentication, please remove the following codesoSmtp.UserName:='test@emailarchitect.net';oSmtp.Password:='testpassword';// ConnectTryTLS means if server supports SSL/TLS connection, SSL/TLS is used automaticallyoSmtp.ConnectType:=ConnectTryTLS;// If your server uses 587 port// oSmtp.ServerPort := 587;// If your server uses 25/587/465 port with SSL/TLS// oSmtp.ConnectType := ConnectSSLAuto;// oSmtp.ServerPort := 587; // 25 or 587 or 465ShowMessage('start to send email ...');ifoSmtp.SendMail()=thenShowMessage('email was sent successfully!')elseShowMessage('failed to send email with the following error: ' oSmtp.GetLastErrDescription());end;end.

If you set everything right, you can get “email was sent successfully”. If you get
“failed to send email with the following error:”, then please have a look at the
following section.

Where can I get my SMTP email server address, user and password?

Because each email account provider has different server address, so you should
query your SMTP server address from your email account provider. To prevent spreading
email from the server, most SMTP servers also require user authentication. User
name is your email address or your email address without domain part, it depends
on your email provider setting.

Finally, if you have already set your account in your email client such as Outlook
or Window Mail, you can query your SMTP server address, user in your email client.
For example, you can choose menu -> “Tools” – > – “Accounts” – > “Your email
account” – > “Properties” – > “Servers” in Outlook express or Windows Mail
to get your SMTP server, user. Using EASendMail to send email does not require you
have email client installed on your machine or MAPI, however you can query your
exist email accounts in your email client.

Send email in Delphi project

Email Address Syntax and Multiple Recipients

The following example codes demonstrates how to specify display name and email address by different syntax.

// For single email address (From, ReplyTo, ReturnPath), the syntax can be:
// ["][display name]["]<email address>.
// For example:
"Tester, T"<test@adminsystem.com>
Tester <test@adminsystem.com>
<test@adminsystem.com>
test@adminsystem.com

// For mulitple email address (To, CC, Bcc), the syntax can be:
// [single email],[single email]...
// (,;rn) can be used to separate multiple email addresses.
// For example:
"Tester, T"<test1@adminsystem.com>, Tester2 <test2@adminsystem.com>,
   <test3@adminsystem.com>, test4@adminsystem.com

[Delphi – Email syntax – Example]

To better understand the email address syntax, please refer to the following codes.
It demonstrate how to specify from, to, cc by different email address syntax.

oSmtp.FromAddr:='Tester<test@adminsystem.com>';oSmtp.FromAddr:='test@adminsystem.com';oSmtp.FromAddr:='<test@adminsystem.com>';// Using AddRecipientEx to add To, Cc and Bcc in Delphi/Visual Basic 6.0// Multiple addresses are separated with (,)// The syntax is like this: "test@adminsystem.com, test1@adminsystem.com"oSmtp.AddRecipientEx('test1@adminsystem.com, test2@adminsystem.com',);oSmtp.AddRecipientEx('Test1<test@adminsystem.com>, Test2<test2@adminsystem.com>',);// You can also add carbon copy (CC) or blind carbon copy (BCC) in the email.oSmtp.AddRecipientEx('CC recipient<cc@adminsystem.com>',1);oSmtp.AddRecipientEx('Bcc recipient<bcc@adminsystem.com>',2);

From, ReplyTo, Sender and Return-Path

From, Reply-To, Sender and Return-Path are common email headers in email message. You should always set From property at first, it is a MUST to identify the email sender. The following table lists the header and corresponding properties:

  • From

    This property indicates the original email sender. This is what you see as the “FROM” in most mail clients.

  • Reply-To

    This property indicates the reply address. Basically, when the user clicks “reply” in mail client, the Reply-To value should be used as the recpient address of the replied email. If you don’t set this property, the Reply address is same as From address.

  • Sender

    This property indicates the who submit/send the email. When the user received the email, the email client displays:
    From: “sender address” on behalf of “from address”.
    If you don’t set this property, the Sender address is same as From address. Sender property is common used by mail listing provider. This property also takes effect to DKIM/DomainKeys signature, if Sender is different with From address, then you should sign DKIM/DomainKeys based on Sender domain instead of From address domain.

  • Return-Path

    This property indicates the delivery notification report address. If you don’t set this property, the Return-Path address is same as From address. This property also takes effect to SPF record, if Return-Path is different with From address, then remote SMTP server checkes SPF record of Return-Path instead of From address.

[Delphi – From, ReplyTo, Sender and Return-Path in Email – Example]

The following example codes demonstrate how to specify From, Reply-To, Sender and
Return-Path in Email. With the following example codes:

Troubleshooting

When you send email in above simple delphi project, if it returned an error,
please have a look at the following tips:

Distribution

  • Standard EXE

    For VB6, C , Delphi or other standard exe application, you can distribute EASendMailObj.dll with your application to target machine without COM-registration and installer.
    To learn more detail, please have a look at Registration-free COM with Manifest File.

  • Script

    For ASP, VBScript, VBA, MS SQL Stored Procedure, you need to install EASendMail on target machine by EASendMail installer, both 32bit/x64 DLL are installed and registered.

Next Section

In this section, I introduced how to send email in a simple Delphi project using SMTP protocol.
At next section I will introduce how to send email over SSL/TLS connection in Delphi.

Send email with embedded images in delphi¶

In previous section, I introduced how to send email with file
attachment. In this section, I will introduce how to send email with embedded images in Delphi.

[Delphi – Send email with embedded images – Example]

The following example codes demonstrate how to
send email with embedded images in Delphi.

unitUnit1;interfaceusesWindows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls,EASendMailObjLib_TLB;// add EASendMail unittypeTForm1=class(TForm)Button1:TButton;procedureButton1Click(Sender:TObject);private{ Private declarations }public{ Public declarations }end;constConnectNormal=;ConnectSSLAuto=1;ConnectSTARTTLS=2;ConnectDirectSSL=3;ConnectTryTLS=4;varForm1:TForm1;implementation{$R *.dfm}procedureTForm1.Button1Click(Sender:TObject);varoSmtp:TMail;cid:WideString;beginoSmtp:=TMail.Create(Application);oSmtp.LicenseCode:='TryIt';// Set your sender email addressoSmtp.FromAddr:='test@emailarchitect.net';// Add recipient email addressoSmtp.AddRecipientEx('support@emailarchitect.net',);// Set email subjectoSmtp.Subject:='test HTML email from Delphi with embedded images';// Add embedded image and return the unique identifier of the attachmentcid:=oSmtp.AddInline('c:test.jpg');ifcid=''thenbeginShowMessage('Failed to add embedded image with error: ' oSmtp.GetLastErrDescription());exit;end;// Set HTML body formatoSmtp.BodyFormat:=1;// Set HTML bodyoSmtp.BodyText:='<html><body>Hello, this is an embedded <img src="cid:' cid '"> picture.</body></html>';// Your SMTP server addressoSmtp.ServerAddr:='smtp.emailarchitect.net';// User and password for ESMTP authentication, if your server doesn't require// user authentication, please remove the following codesoSmtp.UserName:='test@emailarchitect.net';oSmtp.Password:='testpassword';// ConnectTryTLS means if server supports SSL/TLS connection, SSL/TLS is used automaticallyoSmtp.ConnectType:=ConnectTryTLS;// If your server uses 587 port// oSmtp.ServerPort := 587;// If your server uses 25/587/465 port with SSL/TLS// oSmtp.ConnectType := ConnectSSLAuto;// oSmtp.ServerPort := 587; // 25 or 587 or 465ShowMessage('start to send email ...');ifoSmtp.SendMail()=thenShowMessage('email was sent successfully!')elseShowMessage('failed to send email with the following error: ' oSmtp.GetLastErrDescription());end;end.

To attach embedded images/pictures, ImportMailEx
and ImportHtml methods are strongly recommended. With these
methods, you don’t have to specify the ContentID manually. The html source/file
html body can be imported to email with embedded pictures automatically.

[Delphi – Send email with embedded images – ImportHtml – Example]

The following example codes demonstrate how to
send email using ImportHtml method with embedded images in Delphi.

unitUnit1;interfaceusesWindows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls,EASendMailObjLib_TLB;// add EASendMail unittypeTForm1=class(TForm)Button1:TButton;procedureButton1Click(Sender:TObject);private{ Private declarations }public{ Public declarations }end;constConnectNormal=;ConnectSSLAuto=1;ConnectSTARTTLS=2;ConnectDirectSSL=3;ConnectTryTLS=4;varForm1:TForm1;implementation{$R *.dfm}procedureTForm1.Button1Click(Sender:TObject);varoSmtp:TMail;cid:WideString;beginoSmtp:=TMail.Create(Application);oSmtp.LicenseCode:='TryIt';// Set your sender email addressoSmtp.FromAddr:='test@emailarchitect.net';// Add recipient email addressoSmtp.AddRecipientEx('support@emailarchitect.net',);// Set email subjectoSmtp.Subject:='test HTML email from Delphi with embedded images';// Set HTML body formatoSmtp.BodyFormat:=1;// test.gif is in c:my picture// test.gif will be imported as embedded image in the emailoSmtp.ImportHtml('<html><body>test <img src="test.gif"> importhtml</body></html>','c:my picture');// Your SMTP server addressoSmtp.ServerAddr:='smtp.emailarchitect.net';// User and password for ESMTP authentication, if your server doesn't require// user authentication, please remove the following codesoSmtp.UserName:='test@emailarchitect.net';oSmtp.Password:='testpassword';// ConnectTryTLS means if server supports SSL/TLS connection, SSL/TLS is used automaticallyoSmtp.ConnectType:=ConnectTryTLS;// If your server uses 587 port// oSmtp.ServerPort := 587;// If your server uses 25/587/465 port with SSL/TLS// oSmtp.ConnectType := ConnectSSLAuto;// oSmtp.ServerPort := 587; // 25 or 587 or 465ShowMessage('start to send email ...');ifoSmtp.SendMail()=thenShowMessage('email was sent successfully!')elseShowMessage('failed to send email with the following error: ' oSmtp.GetLastErrDescription());end;end.

You can also refer to the htmlmail.* samples in EASendMail Installer. Those samples demonstrate how to build a HTML email
editor and send HTML email with attachment or embedded images/pictures.

Похожее:  Управляющая компания «Наш дом», Ангарск — адрес и телефон, официальный сайт, отзывы жителей

Delphi html editor

Next Section

At next section I will introduce how to sign email with digital certificate in Delphi.

Send email asynchronously in delphi¶

In previous section, I introduced how to encrypt email with
digital certificate. In this section, I will introduce how to use event handler
and send email asynchronously in Delphi.

Introduction

Asynchronous mode

In synchronous mode, once SendMail method is called, it returns to application after the method is
complete. Therefore, if the runtime (it depends on the networking connection and
the email size) is long, your application cannot do anything before this method
ends, which results “my application is blocked or halted”. In contrast, in asynchronous
mode, as SendMail
method works in background, this methods return to application immediately no matter
the running method is complete or not.

Event handler

In previous examples, after SendMail method is invoked,
if you want to know the progress of the email sending, you should use Event Handler to monitor the progress of email sending.

[Delphi – Send email with event handler in asynchronous mode – Example]

To demonstrate how to use asynchronous mode and event handler, let’s add a TLabel
control
in the form at first, the name of the label is “Label1”.

The following example codes demonstrate how to send email with event handler in asynchronous mode.

unitUnit1;interfaceusesWindows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls,EASendMailObjLib_TLB;// add EASendMail unittypeTForm1=class(TForm)Button1:TButton;Label1:TLabel;procedureButton1Click(Sender:TObject);// Event handler procedureprocedureOnAuthenticated(ASender:TObject);procedureOnConnected(ASender:TObject);procedureOnClosed(ASender:TObject);procedureOnError(ASender:TObject;lError:Integer;constErrDescription:WideString);procedureOnSending(ASender:TObject;lSent:Integer;lTotal:Integer);private{ Private declarations }public{ Public declarations }end;constConnectNormal=;ConnectSSLAuto=1;ConnectSTARTTLS=2;ConnectDirectSSL=3;ConnectTryTLS=4;varForm1:TForm1;m_bFinished:Boolean;m_bError:Boolean;implementation{$R *.dfm}procedureTForm1.OnAuthenticated(ASender:TObject);beginLabel1.Caption:='Authenticated';end;procedureTForm1.OnConnected(ASender:TObject);beginLabel1.Caption:='Connected';end;procedureTForm1.OnClosed(ASender:TObject);beginifnotm_bErrorthenLabel1.Caption:='email was sent successfully';m_bFinished:=true;end;procedureTForm1.OnError(ASender:TObject;lError:Integer;constErrDescription:WideString);beginLabel1.Caption:='Failed to send email with error: ' ErrDescription;m_bError:=true;m_bFinished:=true;end;procedureTForm1.OnSending(ASender:TObject;lSent:Integer;lTotal:Integer);beginLabel1.Caption:=Format('Sending %d/%d ...',[lSent,lTotal]);end;procedureTForm1.Button1Click(Sender:TObject);varoSmtp:TMail;beginoSmtp:=TMail.Create(Application);oSmtp.LicenseCode:='TryIt';// Set your sender email addressoSmtp.FromAddr:='test@emailarchitect.net';// Add recipient email addressoSmtp.AddRecipientEx('support@emailarchitect.net',);// Set email subjectoSmtp.Subject:='simple email from Delphi project';// Set body textoSmtp.BodyText:='this is a test email sent from delphi';// Your SMTP server addressoSmtp.ServerAddr:='smtp.emailarchitect.net';// User and password for ESMTP authentication, if your server doesn't require// user authentication, please remove the following codesoSmtp.UserName:='test@emailarchitect.net';oSmtp.Password:='testpassword';// ConnectTryTLS means if server supports SSL/TLS connection, SSL/TLS is used automaticallyoSmtp.ConnectType:=ConnectTryTLS;// If your server uses 587 port// oSmtp.ServerPort := 587;// If your server uses 25/587/465 port with SSL/TLS// oSmtp.ConnectType := ConnectSSLAuto;// oSmtp.ServerPort := 587; // 25 or 587 or 465m_bError:=false;m_bFinished:=false;// Set Asynchronous modeoSmtp.Asynchronous:=1;// Add event handleroSmtp.OnConnected:=OnConnected;oSmtp.OnClosed:=OnClosed;oSmtp.OnError:=OnError;oSmtp.OnSending:=OnSending;oSmtp.OnAuthenticated:=OnAuthenticated;Button1.Enabled:=false;Label1.Caption:='start to send email ...';oSmtp.SendMail();// Wait for the resultwhilenotm_bFinisheddoApplication.ProcessMessages();ShowMessage(Label1.Caption);Button1.Enabled:=true;end;end.

Next Section

At next section I will introduce how to send mass emails with multiple threads in Delphi.

Send email using gmail in delphi¶

In previous section, I introduced how to send email over SSL/TLS
connection. In this section, I will introduce how to send email using Gmail account in Delphi.

[Delphi – Send email using Gmail account over implicit SSL on 465 port – Example ]

The following example codes demonstrate how to send email using Gmail account over SSL in Delphi.

unitUnit1;interfaceusesWindows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls,EASendMailObjLib_TLB;// add EASendMail unittypeTForm1=class(TForm)Button1:TButton;procedureButton1Click(Sender:TObject);private{ Private declarations }public{ Public declarations }end;constConnectNormal=;ConnectSSLAuto=1;ConnectSTARTTLS=2;ConnectDirectSSL=3;ConnectTryTLS=4;varForm1:TForm1;implementation{$R *.dfm}procedureTForm1.Button1Click(Sender:TObject);varoSmtp:TMail;beginoSmtp:=TMail.Create(Application);oSmtp.LicenseCode:='TryIt';// Your Gmail email addressoSmtp.FromAddr:='gmailid@gmail.com';// Add recipient email addressoSmtp.AddRecipientEx('support@emailarchitect.net',);// Set email subjectoSmtp.Subject:='simple email from gmail account';// Set email bodyoSmtp.BodyText:='this is a test email sent from Delphi using Gmail';// Gmail SMTP server addressoSmtp.ServerAddr:='smtp.gmail.com';// set direct SSL 465 port,oSmtp.ServerPort:=465;// detect SSL/TLS automaticallyoSmtp.ConnectType:=ConnectSSLAuto;// Gmail user authentication should use your// Gmail email address as the user name.// For example: your email is "gmailid@gmail.com", then the user should be "gmailid@gmail.com"oSmtp.UserName:='gmailid@gmail.com';// Create app password in Google account// https://support.google.com/accounts/answer/185833?hl=enoSmtp.Password:='your app password';ShowMessage('start to send email ...');ifoSmtp.SendMail()=thenShowMessage('email was sent successfully!')elseShowMessage('failed to send email with the following error: ' oSmtp.GetLastErrDescription());end;end.

[Delphi – Send email using Gmail account over explicit SSL (TLS) on 25 or 587 port]

The following example codes demonstrate how to send email using Gmail account over TLS in Delphi.

unitUnit1;interfaceusesWindows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls,EASendMailObjLib_TLB;// add EASendMail unittypeTForm1=class(TForm)Button1:TButton;procedureButton1Click(Sender:TObject);private{ Private declarations }public{ Public declarations }end;constConnectNormal=;ConnectSSLAuto=1;ConnectSTARTTLS=2;ConnectDirectSSL=3;ConnectTryTLS=4;varForm1:TForm1;implementation{$R *.dfm}procedureTForm1.Button1Click(Sender:TObject);varoSmtp:TMail;beginoSmtp:=TMail.Create(Application);oSmtp.LicenseCode:='TryIt';// Your Gmail email addressoSmtp.FromAddr:='gmailid@gmail.com';// Add recipient email addressoSmtp.AddRecipientEx('support@emailarchitect.net',);// Set email subjectoSmtp.Subject:='simple email from gmail account';// Set email bodyoSmtp.BodyText:='this is a test email sent from Delphi using Gmail';// Gmail SMTP server addressoSmtp.ServerAddr:='smtp.gmail.com';// set 587 port, if you want to use 25 port, please change 587 to 25oSmtp.ServerPort:=587;// detect SSL/TLS automaticallyoSmtp.ConnectType:=ConnectSSLAuto;// Gmail user authentication should use your// Gmail email address as the user name.// For example: your email is "gmailid@gmail.com", then the user should be "gmailid@gmail.com"oSmtp.UserName:='gmailid@gmail.com';// Create app password in Google account// https://support.google.com/accounts/answer/185833?hl=enoSmtp.Password:='your app password';ShowMessage('start to send email ...');ifoSmtp.SendMail()=thenShowMessage('email was sent successfully!')elseShowMessage('failed to send email with the following error: ' oSmtp.GetLastErrDescription());end;end.

[delphi – send email with event handler in asynchronous mode – example]¶

To demonstrate how to use asynchronous mode and event handler, let’s add a TLabel
control in the form at first, the name of the label is “Label1”.

The following example codes demonstrate how to send email with event handler in asynchronous mode.

unitUnit1;interfaceusesWindows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls,EASendMailObjLib_TLB;// add EASendMail unittypeTForm1=class(TForm)Button1:TButton;Label1:TLabel;procedureButton1Click(Sender:TObject);// Event handler procedureprocedureOnAuthenticated(ASender:TObject);procedureOnConnected(ASender:TObject);procedureOnClosed(ASender:TObject);procedureOnError(ASender:TObject;lError:Integer;constErrDescription:WideString);procedureOnSending(ASender:TObject;lSent:Integer;lTotal:Integer);private{ Private declarations }public{ Public declarations }end;constConnectNormal=;ConnectSSLAuto=1;ConnectSTARTTLS=2;ConnectDirectSSL=3;ConnectTryTLS=4;varForm1:TForm1;m_bFinished:Boolean;m_bError:Boolean;implementation{$R *.dfm}procedureTForm1.OnAuthenticated(ASender:TObject);beginLabel1.Caption:='Authenticated';end;procedureTForm1.OnConnected(ASender:TObject);beginLabel1.Caption:='Connected';end;procedureTForm1.OnClosed(ASender:TObject);beginifnotm_bErrorthenLabel1.Caption:='email was sent successfully';m_bFinished:=true;end;procedureTForm1.OnError(ASender:TObject;lError:Integer;constErrDescription:WideString);beginLabel1.Caption:='Failed to send email with error: ' ErrDescription;m_bError:=true;m_bFinished:=true;end;procedureTForm1.OnSending(ASender:TObject;lSent:Integer;lTotal:Integer);beginLabel1.Caption:=Format('Sending %d/%d ...',[lSent,lTotal]);end;procedureTForm1.Button1Click(Sender:TObject);varoSmtp:TMail;beginoSmtp:=TMail.Create(Application);oSmtp.LicenseCode:='TryIt';// Set your sender email addressoSmtp.FromAddr:='test@emailarchitect.net';// Add recipient email addressoSmtp.AddRecipientEx('support@emailarchitect.net',);// Set email subjectoSmtp.Subject:='simple email from Delphi project';// Set body textoSmtp.BodyText:='this is a test email sent from delphi';// Your SMTP server addressoSmtp.ServerAddr:='smtp.emailarchitect.net';// User and password for ESMTP authentication, if your server doesn't require// user authentication, please remove the following codesoSmtp.UserName:='test@emailarchitect.net';oSmtp.Password:='testpassword';// ConnectTryTLS means if server supports SSL/TLS connection, SSL/TLS is used automaticallyoSmtp.ConnectType:=ConnectTryTLS;// If your server uses 587 port// oSmtp.ServerPort := 587;// If your server uses 25/587/465 port with SSL/TLS// oSmtp.ConnectType := ConnectSSLAuto;// oSmtp.ServerPort := 587; // 25 or 587 or 465m_bError:=false;m_bFinished:=false;// Set Asynchronous modeoSmtp.Asynchronous:=1;// Add event handleroSmtp.OnConnected:=OnConnected;oSmtp.OnClosed:=OnClosed;oSmtp.OnError:=OnError;oSmtp.OnSending:=OnSending;oSmtp.OnAuthenticated:=OnAuthenticated;Button1.Enabled:=false;Label1.Caption:='start to send email ...';oSmtp.SendMail();// Wait for the resultwhilenotm_bFinisheddoApplication.ProcessMessages();ShowMessage(Label1.Caption);Button1.Enabled:=true;end;end.

Next Section

At next section I will introduce how to send mass emails with multiple threads in Delphi.

Send email over ssl/tls in delphi¶

In previous section, I introduced how to send email in a simple Delphi project. In this section,
I will introduce how to send email over SSL/TLS connection in Delphi.

[Delphi – Send email over implicit SSL on 465 port – Example]

The following example codes demonstrate how to send email over SSL connection on 465 port.

unitUnit1;interfaceusesWindows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls,EASendMailObjLib_TLB;// add EASendMail unittypeTForm1=class(TForm)Button1:TButton;procedureButton1Click(Sender:TObject);private{ Private declarations }public{ Public declarations }end;constConnectNormal=;ConnectSSLAuto=1;ConnectSTARTTLS=2;ConnectDirectSSL=3;ConnectTryTLS=4;varForm1:TForm1;implementation{$R *.dfm}procedureTForm1.Button1Click(Sender:TObject);varoSmtp:TMail;beginoSmtp:=TMail.Create(Application);oSmtp.LicenseCode:='TryIt';// Set your sender email addressoSmtp.FromAddr:='test@emailarchitect.net';// Add recipient email addressoSmtp.AddRecipientEx('support@emailarchitect.net',);// Set email subjectoSmtp.Subject:='simple email from Delphi project';// Set email bodyoSmtp.BodyText:='this is a test email sent from Delphi project, do not reply';// Your SMTP server addressoSmtp.ServerAddr:='smtp.emailarchitect.net';// Set SSL 465 portoSmtp.ServerPort:=465;// Set direct SSL connectionoSmtp.ConnectType:=ConnectSSLAuto;// User and password for ESMTP authentication, if your server doesn't require// user authentication, please remove the following codesoSmtp.UserName:='test@emailarchitect.net';oSmtp.Password:='testpassword';ShowMessage('start to send email ...');ifoSmtp.SendMail()=thenShowMessage('email was sent successfully!')elseShowMessage('failed to send email with the following error: ' oSmtp.GetLastErrDescription());end;end.

[Delphi – Send email over TLS (Explicit SSL) on 25 or 587 port – Example]

The following example codes demonstrate how to
send email over TLS (STARTTLS command, Explicit SSL) connection on 25 port.

unitUnit1;interfaceusesWindows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls,EASendMailObjLib_TLB;// add EASendMail unittypeTForm1=class(TForm)Button1:TButton;procedureButton1Click(Sender:TObject);private{ Private declarations }public{ Public declarations }end;constConnectNormal=;ConnectSSLAuto=1;ConnectSTARTTLS=2;ConnectDirectSSL=3;ConnectTryTLS=4;varForm1:TForm1;implementation{$R *.dfm}procedureTForm1.Button1Click(Sender:TObject);varoSmtp:TMail;beginoSmtp:=TMail.Create(Application);oSmtp.LicenseCode:='TryIt';// Set your sender email addressoSmtp.FromAddr:='test@emailarchitect.net';// Add recipient email addressoSmtp.AddRecipientEx('support@emailarchitect.net',);// Set email subjectoSmtp.Subject:='simple email from Delphi project';// Set email bodyoSmtp.BodyText:='this is a test email sent from Delphi project, do not reply';// Your SMTP server addressoSmtp.ServerAddr:='smtp.emailarchitect.net';// Set 25 port, if your server uses 587 port, please change 25 to 587oSmtp.ServerPort:=25;// Set TLS connectionoSmtp.ConnectType:=ConnectSSLAuto;// User and password for ESMTP authentication, if your server doesn't require// user authentication, please remove the following codesoSmtp.UserName:='test@emailarchitect.net';oSmtp.Password:='testpassword';ShowMessage('start to send email ...');ifoSmtp.SendMail()=thenShowMessage('email was sent successfully!')elseShowMessage('failed to send email with the following error: ' oSmtp.GetLastErrDescription());end;end.

SMTP Server SSL Certificate

To send email over SSL/TLS connection, you don’t need to install a certificate on your machine. The data is encrypted by
server certificate public/private key pair.

Send email using yahoo in delphi¶

In previous section, I introduced how to send email using Gmail
account. In this section, I will introduce how to send email using Yahoo account in Delphi.

[Delphi – Send email using Yahoo over Implicit SSL on 465 port – Example]

The following example codes demonstrate how to send email using Yahoo account in Delphi over SSL 465 port.

unitUnit1;interfaceusesWindows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls,EASendMailObjLib_TLB;// add EASendMail unittypeTForm1=class(TForm)Button1:TButton;procedureButton1Click(Sender:TObject);private{ Private declarations }public{ Public declarations }end;constConnectNormal=;ConnectSSLAuto=1;ConnectSTARTTLS=2;ConnectDirectSSL=3;ConnectTryTLS=4;varForm1:TForm1;implementation{$R *.dfm}procedureTForm1.Button1Click(Sender:TObject);varoSmtp:TMail;beginoSmtp:=TMail.Create(Application);oSmtp.LicenseCode:='TryIt';// Your Yahoo email addressoSmtp.FromAddr:='myid@yahoo.com';// Add recipient email addressoSmtp.AddRecipientEx('support@emailarchitect.net',);// Set email subjectoSmtp.Subject:='simple email from Yahoo account';// Set email bodyoSmtp.BodyText:='this is a test email sent from Delphi using Yahoo';// Yahoo SMTP server addressoSmtp.ServerAddr:='smtp.mail.yahoo.com';// Because yahoo deploys SMTP server on 465 port with direct SSL connection.// So we should change the port to 465.oSmtp.ServerPort:=465;// detect SSL/TLS automaticallyoSmtp.ConnectType:=ConnectSSLAuto;// For example: your email is "myid@yahoo.com", then the user should be "myid@yahoo.com"oSmtp.UserName:='myid@yahoo.com';oSmtp.Password:='yourpassword';ShowMessage('start to send email ...');ifoSmtp.SendMail()=thenShowMessage('email was sent successfully!')elseShowMessage('failed to send email with the following error: ' oSmtp.GetLastErrDescription());end;end.

[Delphi – Send Email using Yahoo over Explicit SSL (TLS) on 25 or 587 Port – Example]

The following example codes demonstrate how to send email using Yahoo account in Delphi over TLS 587 port.

unitUnit1;interfaceusesWindows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls,EASendMailObjLib_TLB;// add EASendMail unittypeTForm1=class(TForm)Button1:TButton;procedureButton1Click(Sender:TObject);private{ Private declarations }public{ Public declarations }end;constConnectNormal=;ConnectSSLAuto=1;ConnectSTARTTLS=2;ConnectDirectSSL=3;ConnectTryTLS=4;varForm1:TForm1;implementation{$R *.dfm}procedureTForm1.Button1Click(Sender:TObject);varoSmtp:TMail;beginoSmtp:=TMail.Create(Application);oSmtp.LicenseCode:='TryIt';// Your Yahoo email addressoSmtp.FromAddr:='myid@yahoo.com';// Add recipient email addressoSmtp.AddRecipientEx('support@emailarchitect.net',);// Set email subjectoSmtp.Subject:='simple email from Yahoo account';// Set email bodyoSmtp.BodyText:='this is a test email sent from Delphi using Yahoo';// Yahoo SMTP server addressoSmtp.ServerAddr:='smtp.mail.yahoo.com';// set 587 port, if you want to use 25 port, please change 587 to 25oSmtp.ServerPort:=587;// detect SSL/TLS automaticallyoSmtp.ConnectType:=ConnectSSLAuto;// For example: your email is "myid@yahoo.com", then the user should be "myid@yahoo.com"oSmtp.UserName:='myid@yahoo.com';oSmtp.Password:='yourpassword';ShowMessage('start to send email ...');ifoSmtp.SendMail()=thenShowMessage('email was sent successfully!')elseShowMessage('failed to send email with the following error: ' oSmtp.GetLastErrDescription());end;end.

[delphi – send mass emails with easendmail service database queue – example]¶

The following example codes demonstrate how to send mass emails using email queue database in Delphi.

unitUnit1;interfaceusesWindows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls,EASendMailObjLib_TLB;// add EASendMail unittypeTForm1=class(TForm)Button1:TButton;procedureButton1Click(Sender:TObject);private{ Private declarations }public{ Public declarations }end;constConnectNormal=;ConnectSSLAuto=1;ConnectSTARTTLS=2;ConnectDirectSSL=3;ConnectTryTLS=4;varForm1:TForm1;implementation{$R *.dfm}procedureTForm1.Button1Click(Sender:TObject);varoSmtp:TMail;beginoSmtp:=TMail.Create(Application);oSmtp.LicenseCode:='TryIt';// Set your sender email addressoSmtp.FromAddr:='test@emailarchitect.net';// Set email subjectoSmtp.Subject:='simple email from Delphi project';// change it to your sql server address, database, user and password.// The server/instance name syntax used in the server option is the same for all SQL Server connection strings.// e.g.: Server=serveraddressinstancename;// EASendMail will use the following connection to connect to the database,// the syntax is same as ADO connection object.oSmtp.AddHeader('X-Data-Connection','Driver={SQL Native Client};Server=serveraddress;Database=database;Uid=user;Pwd=password;');// For more connection string// MS SQL Server 2000// 'Driver={SQL Server};Server=localhost;Database=pubs;Uid=sa;Pwd=asdasd;'// MS SQL Server 2005// 'Driver={SQL Server Native Client};Server=localhost;Database=pubs;Uid=sa;Pwd=asdasd;'// MS SQL Server 2005 Native Provider// 'Provider=SQLNCLI;Server=serveraddress;Database=database;Uid=user;Pwd=password;'// MS SQL Server 2008// 'Driver={SQL Server Native Client 10.0};Server=localhost;Database=myDataBase;Uid=myUsername;Pwd=myPassword;'// MS SQL Server 2008 Native Provider// 'Provider=SQLNCLI10;Server=serveraddress;Database=database;Uid=user;Pwd=password;'// MS SQL Server 2022// 'Driver={SQL Server Native Client 11.0};Server=localhost;Database=myDataBase;Uid=myUsername;Pwd=myPassword;'// MS SQL Server 2022 Native Provider// 'Provider=SQLNCLI11;Server=serveraddress;Database=database;Uid=user;Pwd=password;'// EASendMail will select the fields by the following sql statement// before sending email,// then pick the recipient address from specified field.oSmtp.AddHeader('X-Sql-Select','SELECT uid, name, email FROM Recipients');// Pick "name" field as the recipient name and "email" field as the recipient address.// You can also use {$var_srecord:fieldname} to pick any field in X-Sql-Select statement// and put it to subject, bodytext, then EASendMail will replace it automatially.oSmtp.DisplayTo:='"{$var_srecord:name}" <{$var_srecord:email}>';oSmtp.AddHeader('X-Rcpt-To','{$var_srecord:email}');// EASendMail service will execute the following sql statement on// every email was sent successfully.oSmtp.AddHeader('X-Sql-OnSentSuccess','INSERT INTO sentlog (server, email) VALUES(''{$var_server}'', ''{$var_rcptaddr}'')');// EASendMail service will execute the following sql statement on// every email could not be sent.oSmtp.AddHeader('X-Sql-OnSentError','INSERT INTO errorlog(email, server, errorcode, errordescription) ' 'VALUES(''{$var_rcptaddr}'', ''{$var_server}'', ''{$var_errcode}'', ''{$var_errdesc}'')');oSmtp.BodyText:='Hi {$var_srecord:name}, ' #13#10 'Send email with queue.' #13#10 #13#10 'From:Tester' #13#10 'To:{$var_srecord:email}' #13#10 #13#10 'Your id in database is {$var_srecord:uid}.' #13#10;// {$var_srecord:uid} {$var_srecord:name} {$var_srecord:email} in// body text will be replaced by EASendMail automatically.// Your SMTP server addressoSmtp.ServerAddr:='smtp.emailarchitect.net';// User and password for ESMTP authentication, if your server doesn't require// user authentication, please remove the following codesoSmtp.UserName:='test@emailarchitect.net';oSmtp.Password:='testpassword';// ConnectTryTLS means if server supports SSL/TLS connection, SSL/TLS is used automaticallyoSmtp.ConnectType:=ConnectTryTLS;// If your server uses 587 port// oSmtp.ServerPort := 587;// If your server uses 25/587/465 port with SSL/TLS// oSmtp.ConnectType := ConnectSSLAuto;// oSmtp.ServerPort := 587; // 25 or 587 or 465ShowMessage('start to send email ...');// You just need to change SendMail method to SendMailToQueue method in// your Delphi application, then EASendMail uses queue to send email.// SendMailToQueue can be used in windows application as well.ifoSmtp.SendMailToQueue()=thenShowMessage('email was sent to queue successfully!')elseShowMessage('failed to send email with the following error: ' oSmtp.GetLastErrDescription());end;end.

With above codes, no matter how many records in your table, SendMailToQueue is only
invoked once and EASendMail service will pick up records in background and send
the email based on each record to recipient one by one. It also inserts the results
back to “errorlog” and “sentlog” tables automatically.

1 Звезда2 Звезды3 Звезды4 Звезды5 Звезд (Пока оценок нет)
Загрузка...

Добавить комментарий

Ваш адрес email не будет опубликован.

Adblock
detector