Search code examples
delphimailtodelphi-xe7shellexecute

How do I include line breaks in an e-mail message created with ShellExecute?


I can successfully send an email with ShellExecute. The To address is correct, the Sender Address is correct, and the Subject is correct. The body of the email is correct, except there are no line breaks at all and everything appears as a single paragraph with no line breaks. The default email client in my case is Windows 8.1 mail.

My question is, can ShellExecute be used so the line breaks are retained? I am not looking to send the email directly with Indy. All I need to do is to send an email to the default email client and have it formatted correctly.

procedure TForm1.Email1Click(Sender: TObject);
var
  iGridTableItem: TcxCustomGridTableItem;
  iName, iDate, iEmail, iSubject, iBody, iParam: string;
begin
  iGridTableItem := cxGrid1DBTableView1.DataController.
    GetItemByFieldName('EMail');
  if iGridTableItem.EditValue <> null then
  iEmail := iGridTableItem.EditValue;
  iGridTableItem := cxGrid1DBTableView1.DataController.
    GetItemByFieldName('Name');
  if iGridTableItem.EditValue <> null then
  iName := iGridTableItem.EditValue;
  iGridTableItem := cxGrid1DBTableView1.DataController.
    GetItemByFieldName('Date');
  if iGridTableItem.EditValue <> null then
  iDate := DateToStr(iGridTableItem.EditValue);
  iSubject := 'ImageEn EBook';
  iBody := 'Dear Mr. ' + iName + ',' + sLineBreak + sLineBreak +
    'PayPal has advised me that you purchased xxxxx on ' + iDate +
    '.' + '  Thank-you for your purchase.' + sLineBreak + sLineBreak + 'You may ' +
    'download the xxx at' + sLineBreak +
    'http://www.xxxxx.xxx/xxx/EBook/xxx101.zip' + sLineBreak +
    'Best regards,' + sLineBreak  + 'William Miller' + sLineBreak  +
    'Adirondack Software and Graphics ' + sLineBreak  + 'Email: [email protected]'
     iParam := 'mailto:' + iEmail + '?subject=' + iSubject + '&Body=' + iBody;
  ShellExecute(Form1.Handle, 'open', PChar(iParam), nil, nil, SW_SHOWNORMAL);
end;

Solution

  • Different mail apps support the mailto protocol differently. Not all apps allow multiple parameters to be specified together, etc. So using mailto to send emails is going to be very spotty on different machines.

    That being said, you are essentially invoking a URL, just one with the mailto: protocol scheme. As such, you need to url-encode reserved characters, like spaces and line breaks. You might not want to use Indy to send the mail, but you can use it to encode your parameter values, at least:

    uses
      ..., IdURI;
    
    iParam := 'mailto:' + iEmail + '?subject=' + TIdURI.ParamsEncode(iSubject) + '&Body=' + TIdURI.ParamsEncode(iBody);