Delphi用Indy10发邮件的单元,超简单

unit USendMail;

interface

uses SysUtils, Classes, IdSMTP, IdMessage, IdAttachmentFile;

/// <summary>
/// 邮件发送
/// </summary>
/// <param name="Smtp">邮件服务器主机 例如:smtp.qq.com</param>
/// <param name="Port">邮件服务器端口 默认:25</param>
/// <param name="User">邮件用户名,需要加上xxxx@qq.com</param>
/// <param name="Pass">邮件密码</param>
/// <param name="MailTo">邮件接收人,多个时用“;”分隔</param>
/// <param name="MailCC">邮件抄送接收人,多个时用“;”分隔</param>
/// <param name="Subject">邮件主题</param>
/// <param name="Content">邮件内容</param>
/// <param name="Attachment">附件文件,多个文件名用“;”分隔</param>
/// <returns></returns>
function SendMail(Smtp: string; Port: Word; User, Pass, MailTo, MailCC, Subject, Content, Attachment: string): Integer; stdcall;

implementation

function SendMail(Smtp: string; Port: Word; User, Pass, MailTo, MailCC, Subject, Content, Attachment: string): Integer; stdcall;
var
  FSMTP: TIdSMTP;
  FMailMessage: TIdMessage;
  SL: TStrings;
  I: Integer;
begin
  FSMTP := TIdSMTP.Create(nil);
  FMailMessage := TIdMessage.Create(nil);
  FMailMessage.CharSet := 'utf-8';

  FSMTP.Host := Smtp;
  FSMTP.Port := Port;
  FSMTP.Username := User;
  FSMTP.Password := Pass;

  SL := TStringList.Create;
  SL.Delimiter := ';';
  try
    {Mail To}
    SL.DelimitedText := MailTo;
    if SL.Count > 0 then
    for I := 0 to SL.Count - 1 do
      FMailMessage.Recipients.Add.Address := SL[I];
    {Mail CC}
    SL.DelimitedText := MailCC;
    if SL.Count > 0 then
    for I := 0 to SL.Count - 1 do
      FMailMessage.CCList.Add.Address := SL[I];
    {Subject and Content}
    FMailMessage.Subject := Subject;
    FMailMessage.Body.Text := Content;
    {Attachment}
    SL.DelimitedText := Attachment;
    if SL.Count > 0 then
      for I := 0 to SL.Count - 1 do
        with TIdAttachmentFile.Create(FMailMessage.MessageParts, SL[I]) do
        begin
          ContentType := 'application/octet-stream';
          ContentDisposition := 'attachment';
          ContentTransfer := 'base64';
        end;
  finally
    SL.Free;
  end;
  try
    try
      FSMTP.Connect();
      FSMTP.Send(FMailMessage);
      Result := 0;
    except on E:Exception do
      Result := -1;
    end;
  finally
    if FSMTP.Connected then
      FSMTP.Disconnect;
  end;

  FMailMessage.Free;
  FSMTP.Free;
end;

end.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值