天天看點

delphi發送郵件程式

unit Unit1;

interface

uses

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

  Dialogs, IdMessage, IdBaseComponent, IdComponent, IdTCPConnection,

  IdTCPClient, IdMessageClient, IdSMTP, StdCtrls;

type

  TForm1 = class(TForm)

    btn1: TButton;

    SMTP: TIdSMTP;

    MailMessage: TIdMessage;

    mmo1: TMemo;

    procedure btn1Click(Sender: TObject);

  private

    { Private declarations }

  public

    { Public declarations }

  end;

var

  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.btn1Click(Sender: TObject);

Var

    i: integer;

    sEmail, sFullName: string;

begin

           sEmail :='[email protected]';//sEmail 用于臨時儲存收件者的郵箱位址如我本人的:[email protected]

            if Trim(sEmail) <> '' then

            begin

                with MailMessage do

                begin

                     Clear; // 清除前一次産生的 body & headerm, 以免第二次按時重複

                    Body.Assign(mmo1.Lines);    //郵件正文

                     From.Text :='[email protected]'; // 發送者的郵箱位址

                    Recipients.EMailAddresses := sEmail ; // 前面申請的收件者位址變量

                     Subject := '你好嗎,親愛的'; //寫入郵件主題

                 //Priority := TIdMessagePriority(2);//設定發送的優先級 0-4, 0表示最高優先順序

                  CCList.EMailAddresses :='[email protected]';//如果要抄送可以在這裡進行操作

                 //  ReceiptRecipient.Text := From.Text; //若要寄件回函,那麼就添加這行

               end;

                // 以下幾行代碼就是發送EMAIL的驗證使用者名及密碼代碼:

               SMTP.AuthenticationType := atLogin;{Simple Login}

                SMTP.Username :='weifengx10';//如發送者的Email位址為'[email protected]'那麼在此時可以在使用者名中填入'a123456'

               SMTP.Password := 'weifeng123';//'在所在的郵件伺服器中注冊的密碼'

             //一般設定

               SMTP.Host := 'smtp.163.com';//一般發送郵件伺服器的位址都以smtp.XXXX.com進行,如此時的126郵箱的為:smtp.126.com;

               SMTP.Port := 25;//發郵件者的發送郵件伺服器端口号,一般為25要注意的是這裡25是一個integer類型的.

           //發送

               try

                   SMTP.Connect;//與發件者伺服器建立連接配接

                   try

                       SMTP.Send(MailMessage);//發送EMAIL内容至收件者.

                      ShowMessage('Send email successful.');

                    finally

                       SMTP.Disconnect;//此時不管發送是否成功與否都将Free掉所占的資源

                   end;

                except

                    on e:exception do

                    begin

                       ShowMessage('Send email unsuccessful.' + e.Message);//當連接配接錯誤時顯示具體錯誤資訊.

                   end;

                end;

            end;

end;

end.

繼續閱讀