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

Delphi 专栏收录该内容
44 篇文章 1 订阅
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.


  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

©️2022 CSDN 皮肤主题:技术黑板 设计师:CSDN官方博客 返回首页

打赏作者

cmd9x

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值