发送附带内存流的电子邮件

时间:2014-12-23 02:05:54

标签: delphi smtp indy indy10

我正在尝试发送附带内存流的电子邮件,但我总是在收到的电子邮件中收到此消息而没有附件"这是MIME格式的多部分消息..."

代码:

var
  MemStrm : TMemoryStream;
begin
  MemStrm := TMemoryStream.Create;
  Str1.SaveToStream(MemStrm);
  MemStrm.Position := 0;

  try
  with IdSSLIOHandlerSocketOpenSSL1 do
  begin
    Destination            := 'smtp.mail.yahoo.com' + ':' + IntToStr(465);
    Host                   := 'smtp.mail.yahoo.com';
    MaxLineAction          := maException;
    Port                   := 465;
    SSLOptions.Method      := sslvTLSv1;
    SSLOptions.Mode        := sslmUnassigned;
    SSLOptions.VerifyMode  := [];
    SSLOptions.VerifyDepth := 0;
  end;
  with IdSMTP1 do
  begin
    IOHandler          := IdSSLIOHandlerSocketOpenSSL1;
    Host               := 'smtp.mail.yahoo.com';
    Port               := 465;
    AuthType           := satDefault;
    Password           := 'password';
    Username           := 'sender@yahoo.com';
    UseTLS             := utUseImplicitTLS;
  end;
  with IdMessage1 do
  begin

    From.Address              := 'sender@yahoo.com';

    List:= Recipients.Add;
    List.Address:=  'receiver@yahoo.com';
    Recipients.EMailAddresses := 'receiver@yahoo.com';
    Subject                   := 'test';
    Body.Text                 := 'test';
    ContentType               := 'text/plain';

    IdAttachment := TIdAttachmentMemory.Create(IdMessage1.MessageParts,MemStrm);
    IdAttachment.ContentType := 'text/plain';
    IdAttachment.FileName := 'attached.txt';
  end;
  finally
    idsmtp1.Connect;
    idsmtp1.Send(idmessage1);
    idsmtp1.Disconnect;
    MemStrm.Free;
  end;
end

我不想先将其保存为文件然后附加它,如何将示例内存流附加到我的电子邮件中?

编辑:即使使用TIdAttachmentFile它也没有用,我在delphi 7上使用Indy10版本10.6.0.5049

2 个答案:

答案 0 :(得分:3)

您将顶级TIdMessage.ContentType设置为text/plain,告诉读者将整个电子邮件解释为纯文本。您需要将该属性设置为multipart/mixed,然后读者将解释附件:

with IdMessage1 do
begin
  ...
  ContentType := 'multipart/mixed';
end;

我还建议你添加一个TIdText对象,让读者知道电子邮件的内容,例如:

IdText := TIdText.Create(IdMessage1.MessageParts, nil);
IdText.ContentType := 'text/plain';
IdText.Body.Text := 'here is an attachment for you.';

IdAttachment := TIdAttachmentMemory.Create(IdMessage1.MessageParts,MemStrm);
IdAttachment.ContentType := 'text/plain';
IdAttachment.FileName := 'attached.txt';

此外,您要填写Recipients属性两次。使用Recipients.Add.AddressRecipients.EMailAddresses,请勿同时使用:

with IdMessage1 do
begin
  ...
  List:= Recipients.Add;
  List.Address := 'receiver@yahoo.com';
  ...
end;

with IdMessage1 do
begin
  ...
  Recipients.EMailAddresses := 'receiver@yahoo.com';
  ...
end;

答案 1 :(得分:-1)

问题是附件的内容类型定义。 <是/> 您必须将其设置为'application/x-zip-compressed',如下所示:

IdAttachment := TIdAttachmentMemory.Create(IdMessage1.MessageParts,MemStrm);
IdAttachment.ContentType := 'application/x-zip-compressed';
IdAttachment.FileName := 'attached.txt';