delphi發送郵件代碼

procedure TForm1.Button1Click(Sender: TObject); 
begin 
  try 
    IdSMTP1.AuthenticationType:=atLogin; //設置登陸類型 
    IdSMTP1.Username:=Edit1.Text; //設置登陸帳號 
    IdSMTP1.Password:=Edit2.Text; //設置登陸密碼 
    IdSMTP1.Host:=Edit3.Text; //設置SMTP地址 
    IdSMTP1.Port:=strtoint(Edit4.Text); //設置端口  必須轉化爲整型 
    IdSMTP1.Connect;  //開始連接服務器 
  except 
    Showmessage('連接失敗,請重試!'); 
    Exit; //連接失敗 的話 退出該執行過程 
  end; 
  IdMessage1.Body.Clear;  //先清空上次發送的內容 
  IdMessage1.Subject:=Edit5.Text;  //設置郵件發送的標題 
  IdMessage1.Body.Assign(Memo1.Lines);  //設置郵件發送的主體 
  IdMessage1.From.Address:=Edit6.Text; //設置郵件的發件人  也就是說該郵件來自什麼地方 
  IdMessage1.Recipients.EMailAddresses:=Edit7.Text;  //收件人的地址 
  try 
    idSMTP1.Send(IdMessage1); 
    Showmessage('郵件發送成功!'); 
  except 
    Showmessage('郵件發送失敗!'); 
  end; 
end;  

或者:

我寫了一個發郵件的函數,包你滿意
type
  TLoginEmailServer=record               
     SMTPHost:string;
     SMTPPort:integer;
     Username:string;
     Password:string;
     SmtpAuthType:integer;          
  end;
function SendEmail(poSMTPServer:TLoginEmailServer;poBody:Tstrings;psFromEmial,
                  psToEmail,psSubject:string;psContentType:string;
                  CCToEmail:string;poAttachmentPath:TStrings):integer;
var
  loIdMsgSend: TIdMessage;
  loSMTP: TIdSMTP;
  i:integer;
begin
  Result:=3;
  loIdMsgSend:=nil;
  loSMTP:=nil;
  try
    loIdMsgSend:=TIdMessage.Create(nil);
    loSMTP:=TIdSMTP.Create(nil);
    with loIdMsgSend do               
      begin
       ContentType:=psContentType;
       From.Text := psFromEmial;
       ReplyTo.EMailAddresses := psFromEmial;
       Recipients.EMailAddresses := psToEmail;
       CCList.EMailAddresses:=CCToEmail;
       Subject := psSubject;
       Priority := mpHigh;
       ReceiptRecipient.Text := '';
       Body.Assign(poBody);
       if Assigned(poAttachmentPath) then
       begin
         for i := 0 to poAttachmentPath.Count-1 do   
                 begin
           TIdAttachment.Creat(loIdMsgSend.MessageParts,poAttachmentPath.Strings[i]);
         end;
       end;
    end;
    with loSMTP do                   
      begin
      Host :=poSMTPServer.SMTPHost;
      Port := poSMTPServer.SMTPPort;
      if poSMTPServer.SmtpAuthType=1 then
        AuthenticationType:=atLogin
      else
        AuthenticationType:=atNone;
      Username := poSMTPServer.Username;
      Password := poSMTPServer.Password;
      try
        Connect;   
        Send(loIdMsgSend);      
      except
        result:=2;
        exit;
      end;
      Result:=0;
  finally
    loIdMsgSend.Free;
    loSMTP.Free;
  end;
end; 


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章