delphi 实现 邮件发送(TidSMTP控件)

来源:互联网 发布:c语言单向链表的建立 编辑:程序博客网 时间:2024/06/05 07:02
delphi 实现 邮件发送(TidSMTP控件)

新建一个delphi工程,添加 TidSMTP控件以及 TidMessage控件。

配置TidSMTP的相关属性:
name = smtp
MaxLineAction = maException
ReadTimeout = 0
Host = 'smtp.163.com' //163邮箱地址
Port = 25
AuthenticationType = atLogin   //在登陆时候进行认证
Password = '邮箱密码'
Username = '邮箱用户名'

配置TidMessage的相关属性:
Name = MSG
AttachmentEncoding = 'MIME'
    Body.Strings = (
      '你好')
    BccList = <>
    CCList = <>
    Encoding = meMIME
    From.Address = 'yangshiqiang@163.com'
    From.Text = 'yangshiqiang@163.com'
    Recipients = <>
    ReplyTo = <>
    Subject = '你好,TEST'

Ok,对TIdSMTP进行编程:
//邮箱的发送过程

with msg do
  begin
    Recipients.Clear;
    Recipients.Add.Address:=MailTo.Text; //配置发送地址
    Subject:=MailTitle.Text;                    //配置主题
    SetBody(MailContent.Lines);              //配置内容
    From.Address:='yangshiqiang@163.com';
  end;
  try
    try
      SMTP.Connect();           //SMTP的连接
      smtp.Authenticate;        //SMTP的相关认证
      SMTP.Send(msg);           //SMTP的发送邮件
    except
      
    end;
  finally
    SMTP.Disconnect;          //SMTP断开连接
  end;

 

实现代码:

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, IdMessage, IdBaseComponent, IdComponent,
IdTCPConnection, IdTCPClient, IdMessageClient, IdSMTP;

type
TForm1 = class(TForm)
SMTP: TIdSMTP;
IdMsgSend: TIdMessage;
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure sendmail(sbody:TStrings);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
Email : Textfile;
Bodytxt : tstrings;
s:string;
begin
Bodytxt := TStringList.Create;
try
AssignFile(Email,extractfilepath(application.ExeName) + 'rf.txt');
reset(Email);
while not EOF(Email) do
begin
readln(Email, s);
Bodytxt.Add(s);
end;
SendMail(Bodytxt);//调用SendMail,传入邮件内容BodyTxt
finally
closefile(email);
end;
ShowMessage('SendMail OK!');
end;

procedure TForm1.sendmail(sBody : TStrings);
begin
with IdMsgSend do
begin
Body := sBody; //邮件内容
From.Text := 'xxxx'; //发件人
Recipients.EMailAddresses := 'xxxx'; { To: header } //收件人
Subject := 'yyyy'; //邮件主旨
tidattachment.Create(IdMsgSend.MessageParts,'D:\Excel\Test.xls');//发送附件,可发送多个
SMTP.Host := 'smtp.michael.com' ; // 主机名称
SMTP.Port := 25; // PORT
SMTP.Connect;

try
try
SMTP.Send(IdMsgSend);
except
end;
finally
SMTP.Disconnect;
end;
end;

end;

end.

转自:http://hi.baidu.com/xiaoduo170/item/b3d8020c7d5a3a3af3eafc40
原创粉丝点击