Delphi XE 10.1 Berlin Indy发送QQ邮件
程序员文章站
2023-12-22 16:28:04
...
突发奇想, 如果服务在运行过程中, 出现某些问题, 需要提醒管理员时, 就发一封邮件出来, 在网上也找了些资料, 学习了下使用Indy发送QQ邮件.
发件人我用的QQ邮箱, 关于这个, QQ邮箱需要进行一些设置, 进而获取授权码.
QQ邮箱设置可参考: https://jingyan.baidu.com/article/ac6a9a5eb439f36b653eacc0.html
获取授权码后, 当邮箱密码用即可.
代码如下:
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, IdBaseComponent,
IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase,
IdMessageClient, IdSMTPBase, IdSMTP, IdMessage, IdIOHandler,
IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdSSLOpenSSLHeaders;
type
TForm1 = class(TForm)
GroupBox1: TGroupBox;
Label1: TLabel;
Edit1: TEdit;
GroupBox2: TGroupBox;
Label2: TLabel;
Edit2: TEdit;
Label3: TLabel;
Edit3: TEdit;
GroupBox3: TGroupBox;
Label4: TLabel;
Edit4: TEdit;
GroupBox4: TGroupBox;
Label5: TLabel;
Memo1: TMemo;
Button1: TButton;
IdSMTP: TIdSMTP;
IdMessage: TIdMessage;
Label6: TLabel;
Edit5: TEdit;
Label7: TLabel;
Edit6: TEdit;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
fIdSSL: TIdSSLIOHandlerSocketOpenSSL;
public
{ Public declarations }
end;
var
Form1: TForm1;
iResult: boolean;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
IdSMTP.Host:= Trim(Edit1.Text); //SMTP地址
IdSMTP.Port:= StrToInt(Edit5.Text); //端口
IdSMTP.Username:= Trim(Edit2.Text); //用户名
IdSMTP.Password:= Trim(Edit3.Text); //密码
try
try
IdSMTP.Connect; //建立连接
IdMessage.Recipients.EMailAddresses:= Trim(Edit4.Text); //收件人地址
IdMessage.Subject:= Trim(Edit6.Text); //邮件标题
IdMessage.CharSet:= 'UTF-8';
IdMessage.Body.Clear;
IdMessage.Body.Add('This is my first email!'); //邮件正文
IdMessage.From.Address:= Trim(Edit2.Text); //发件人地址
IdMessage.Priority:= mpHigh; //优先级
IdSMTP.Send(IdMessage); //发送邮件
ShowMessage('发送成功!');
except
on e: Exception do
begin
ShowMessage(e.Message);
end;
end;
finally
IdSMTP.Disconnect();
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
fIdSSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
fIdSSL.SSLOptions.Method := sslvSSLv23;
fIdSSL.SSLOptions.Mode := sslmClient;
IdSMTP.IOHandler:= fIdSSL;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
if Assigned(fIdSSL) then
FreeAndNil(fIdSSL);
end;
initialization
iResult := IdSSLOpenSSLHeaders.Load();
end.
点击发送后, 收件人收到:
需要注意的是, 使用了SSL的两个dll文件(libeay32.dll, ssleay32.dll). 这两个文件需要根据开发工具的版本去找对应的.