Indy 自带了SMTP控件,发送邮件的时候,可以添加附件,但是默认情况下,Indy Demo的例子,发送带附件的邮件,结果附件都变成了ASCII的内容,而不正常按附件显示!
下面是正常的用Indy发送带附件的HTML邮件的做法:
首先创建IdMessage,然后重要的一点,是必须把IdMessage的 ContentType设置为'multipart/mixed'!否则真个邮件当作普通文本发送走啦! Encoding := meMIME;
然后是正常的设置IdMessage的发送人啊,收件人啊,主题啊什么之类,然后创建IdAttachmentFile,加载文件之类。
procedure TFormMain.SendMail(Recipient, Address: string);
const
sStars = 'BackgroundStars.jpg';
var
AdressItem: TIdEMailAddressItem;
AFile: string;
AMessage: TIdMessage;
ASMTP: TIdSMTP;
AStream: TMemoryStream;
Attachment: TIdAttachment;
IdBody: TIdText;
IdHTML: TIdText;
idStars: TIdAttachment;
resStars: TStream;
TempFile: TStream;
begin
Screen.Cursor := crHourGlass;
AFile := FileListBox.FileName;
if FileExists(AFile) then begin
AMessage := TIdMessage.Create(nil);
AMessage.NoDecode := False;
AMessage.NoEncode := False;
AMessage.ContentType := 'multipart/mixed';
AMessage.Encoding := meMIME;
AMessage.MsgId := 'PrettyPic';
AMessage.References := ChangeFileExt(ExtractFileName(AFile), '');
// Set recipients.
AdressItem := AMessage.Recipients.Add;
AdressItem.Name := Recipient;
AdressItem.Address := Address;
// Set subject.
AMessage.Subject := 'Hello.';
// Set sender.
AMessage.Sender.Name := 'Workshop Alex';
AMessage.Sender.Address := 'someone@somewhere.org';
// Set from.
AMessage.From.Name := AMessage.Sender.Name;
AMessage.From.Address := AMessage.Sender.Address;
// Create plain body.
IdBody := TIdText.Create(AMessage.MessageParts);
IdBody.ContentType := 'text/plain';
IdBody.Body.Add('Hello, friends.');
IdBody.Body.Add('');
// Add more to the plain-text bodypart.
// Create HTML body.
IdHTML := TIdText.Create(AMessage.MessageParts);
IdHTML.ContentType := 'text/html; charset=US-ASCII';
IdHTML.ContentTransfer := '7bit';
IdHTML.Body.Add('<html>');
IdHTML.Body.Add(' <head>');
IdHTML.Body.Add(' <title>Hello</title>');
IdHTML.Body.Add(' </head>');
IdHTML.Body.Add(' <body title="' + AMessage.References + '" background="cid:BackgroundStars">');
IdHTML.Body.Add(' Hello, friends.<br>');
IdHTML.Body.Add(' <br>');
IdHTML.Body.Add(' <img src="cid:PrettyPic" alt="' + ExtractFileName(AFile) + '" name="' + ExtractFileName(AFile) + '" title="Just an image included.">');
IdHTML.Body.Add(' </body>');
IdHTML.Body.Add('</html>');
// Add the attachment. Don't forget the extra headers!
Attachment := TIdAttachment.Create(AMessage.MessageParts, AFile);
Attachment.ExtraHeaders.Values['Content-ID'] := '<PrettyPic>';
Attachment.ContentType := 'image/jpeg';
idStars := TIdAttachment.Create(AMessage.MessageParts, ExtractFilePath(ParamStr(0)) + sStars);
idStars.ExtraHeaders.Values['Content-ID'] := '<BackgroundStars>';
idStars.ContentType := 'image/jpeg';
// Now send the thing...
ASMTP := TIdSMTP.Create(nil);
ASMTP.Host := 'mail.whatever.org';
ASMTP.Port := 25;
ASMTP.AuthenticationType := atNone;
ASMTP.Connect;
try
ASMTP.Send(AMessage);
except
on E: Exception do ShowMessageFmt('Error: %s', [E.Message]);
end;
ASMTP.Disconnect;
AMessage.Free;
ASMTP.Free;
end;
Screen.Cursor := crDefault;
end;