您的位置:首页 > 大数据 > 人工智能

How to send gmail by Indy (TIdSMTP)?

2016-02-06 11:51 579 查看
procedure SendEmail(const Recipients: string; const Subject: string;
const Body: string);
var
SMTP: TIdSMTP;
Email: TIdMessage;
SSLHandler: TIdSSLIOHandlerSocketOpenSSL;
eFrom: string;
begin
eFrom := 'duytuanvn@gmail.com';
SMTP := TIdSMTP.Create(nil);
Email := TIdMessage.Create(nil);
SSLHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
try
SSLHandler.MaxLineAction := maException;
SSLHandler.SSLOptions.Method := sslvTLSv1;
SSLHandler.SSLOptions.Mode := sslmUnassigned;
SSLHandler.SSLOptions.VerifyMode := [];
SSLHandler.SSLOptions.VerifyDepth := 0;
SSLHandler.Host := 'smtp.gmail.com';
SSLHandler.Port := 587;
SMTP.IOHandler := SSLHandler;
SMTP.Host := 'smtp.gmail.com';
SMTP.Port := 587;
SMTP.Username := eFrom;
SMTP.Password := 'xxxxxx';
SMTP.UseTLS := utUseExplicitTLS;
Email.From.Address := eFrom;
Email.Recipients.EmailAddresses := Recipients;
Email.Subject := Subject;
Email.Body.Text := Body;
SMTP.Connect;
// always raise 'Host not found'
SMTP.Send(Email);
SMTP.Disconnect;
finally
SMTP.Free;
Email.Free;
SSLHandler.Free;
end;
end;;

procedure TestSendMail(Sender: TObject);
begin
SendEmail('tuanktcdcn@yahoo.com', 'Subject', 'Body');
end;


I run procedure "TestSendMail" it always raise 'Host not found'. Please fix it for me. Thank you!

Tuan wrote:> My code to send gmail: Examples of using TIdSMTP to send emails to Gmail have been posted many times before, in Embarcadero's forums, AToZed's Indy forums, and various online blogs. Did you search around for them?> I run procedure "TestSendMail"
it always raise 'Host not found'. You are setting the Host/Port properties of TIdSSLIOHandlerSocketOpenSSL. Do not do that, Connect() handles that internally for you. Outside of that, you are setting the TIdSMTP.UseTLS property after setting the TIdSMTP.Port
property. Try reversing those. The UseTLS property setter can change the Port value, so you should set the UseTLS first, then set the Port to what you really need, in case it is different than what UseTLS assigns. If that still does not work, then double check
your OS network settings. Check that the OS's HOSTS file is not redirecting smtp.gmail.com, make sure you can ping smtp.gmail.com, etc. If you don't find any problems with that, then use a packet sniffer like Wireshark to see what Connect() is actually doing
on the network. Maybe your OS's DNS system is failing to find the IP address for smtp.gmail.com.

I change setting the TIdSMTP.UseTLS before setting TIdSMTP.Port. It is fine ! Thanks to Mr. Remy Lebeau!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: