前言现在很多STMP服务器在发送邮件时均需重新认证一遍而Delphi的TNMSMTP控件对它没有很可视化的支持使很多人在开发过程中大打问号
由于前段时间在做《CSDN查询助手》的时候使用的也是需认证的服务器(com)从其它地方摘取了部分代码得以解决现在此发布与大家共享
实现
在NMSMTP的OnConnect事件中添加代码
var strUserName strPassword: String;
begin
strUserName := EncodeString(CoolSlob);//CoolSlob是服务器的帐号
strPassword := EncodeString(Password);//Password是密码
{进行认证输入编码后的用户名密码}
nmsmtpTransaction(EHLO) ;
nmsmtpTransaction(AUTH LOGIN);
nmsmtpTransaction(strUserName);
nmsmtpTransaction(strPassword);
StatusBarSimpleText := 连接成功;
end;
EncodeString函数实现过程
{对参数Decoded字符串进行Base编码返回编码后的字符串}
function EncodeString(Decoded:string):String;
var
mmTempmmDecoded:TMemoryStream;
strTemp:TStrings;
begin
mmTemp := TMemoryStreamCreate;
mmDecoded:=TMemoryStreamCreate;
strTemp:=TStringListCreate;
strTempAdd(Decoded);
strTempSaveToStream(mmTemp);
mmTempPosition := ;
{剔除mmTemp从strTemp中带来的字符##}
mmDecodedCopyFrom(mmTempmmTempSize);
{对mmDecoded进行Base编码由mmTemp返回编码后的结果}
EncodeBASE(mmTempmmDecoded);
{获得Base编码后的字符串}
mmTempPosition:=;
strTempLoadFromStream(mmTemp);
{返回结果必须从strTemp[]中获得如果使用strTempText会
带来不必要的字符##}
Result:=strTemp[];
end;
EncodeBASE函数实现过程
function EncodeBASE(Encoded: TMemoryStream ; Decoded: TMemoryStream): Integer;
const
_Code: String[] =
(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/);
var
I: LongInt;
B: array[] of Byte;
J K L M Quads: Integer;
Stream: string[];
EncLine: String;
begin
EncodedClear;
Stream := ;
Quads := ;
{为提高效率每字节流为一组进行编码}
J := DecodedSize div ;
DecodedPosition := ;
{对前J*个字节流进行编码}
for I := to J do
begin
DecodedRead(B );
for M := to do
begin
for K := to do
begin
L:= *M + *K;
Stream[Quads+] := _Code[(B[L] div )+];
Stream[Quads+] := _Code[(B[L] mod )* + (B[L+] div )+];
Stream[Quads+] := _Code[(B[L+] mod )* + (B[L+] div )+];
Stream[Quads+] := _Code[B[L+] mod +];
Inc(Quads );
if Quads = then
begin
Stream[] := #;
EncLine := Stream+##;
EncodedWrite(EncLine[] Length(EncLine));
Quads := ;
end;
end;
end;
end;
{对以为模的余数字节流进行编码}
J := (DecodedSize mod ) div ;
for I := to J do
begin
DecodedRead(B );
Stream[Quads+] := _Code[(B[] div )+];
Stream[Quads+] := _Code[(B[] mod )* + (B[] div )+];
Stream[Quads+] := _Code[(B[] mod )* + (B[] div )+];
Stream[Quads+] := _Code[B[] mod +];
Inc(Quads );
{每行个字符}
if Quads = then
begin
Stream[] := #;
EncLine := Stream+##;
EncodedWrite(EncLine[] Length(EncLine));
Quads := ;
end;
end;
{=补位}
if (DecodedSize mod ) = then
begin
DecodedRead(B );
Stream[Quads+] := _Code[(B[] div )+];
Stream[Quads+] := _Code[(B[] mod )* + (B[] div )+];
Stream[Quads+] := _Code[(B[] mod )* + ];
Stream[Quads+] := =;
Inc(Quads );
end;
if (DecodedSize mod ) = then
begin
DecodedRead(B );
Stream[Quads+] := _Code[(B[] div )+];
Stream[Quads+] := _Code[(B[] mod )* + ];
Stream[Quads+] := =;
Stream[Quads+] := =;
Inc(Quads );
end;
Stream[] := Chr(Quads);
if Quads > then
begin
EncLine := Stream+##;
EncodedWrite(EncLine[] Length(EncLine));
end;
Result := EncodedSize;
end;