Solved

Delphi 7 - Opening default mail client via code.

Posted on 2011-03-24
9
1,904 Views
Last Modified: 2012-05-11
Hi, I need to open the default mail client via a button click code, how can I accomplish this ?

Thanks.
0
Comment
Question by:John86a
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 19

Expert Comment

by:Thommy
ID: 35211365
This is exactly what you want...

Sending Email Messages with Attachments using Delphi and Indy
http://delphi.about.com/od/indy/a/email-send-indy.htm
0
 

Author Comment

by:John86a
ID: 35211389
Sorry, not really, I need to open the default mail client configured in windows, that's all..
0
 
LVL 32

Expert Comment

by:ewangoya
ID: 35211631
try
unit Unit2;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm2 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

uses
  MAPI;

function MAPIErrorToStr(ACode: Integer): string;
begin
  Result := 'Unknown Error Code: ' + IntToStr(ACode);
  case ACode of
    MAPI_E_USER_ABORT               : Result := 'User cancelled request';
    MAPI_E_FAILURE                  : Result := 'General MAPI failure';
    MAPI_E_LOGON_FAILURE            : Result := 'Logon failure';
    MAPI_E_DISK_FULL                : Result := 'Disk full';
    MAPI_E_INSUFFICIENT_MEMORY      : Result := 'Insufficient memory';
    MAPI_E_ACCESS_DENIED            : Result := 'Access denied';
    MAPI_E_TOO_MANY_SESSIONS        : Result := 'Too many sessions';
    MAPI_E_TOO_MANY_FILES           : Result := 'Too many files open';
    MAPI_E_TOO_MANY_RECIPIENTS      : Result := 'Too many recipients';
    MAPI_E_ATTACHMENT_NOT_FOUND     : Result := 'Attachment not found';
    MAPI_E_ATTACHMENT_OPEN_FAILURE  : Result := 'Failed to open attachment';
    MAPI_E_ATTACHMENT_WRITE_FAILURE : Result := 'Failed to write attachment';
    MAPI_E_UNKNOWN_RECIPIENT        : Result := 'Unknown recipient';
    MAPI_E_BAD_RECIPTYPE            : Result := 'Invalid recipient type';
    MAPI_E_NO_MESSAGES              : Result := 'No messages';
    MAPI_E_INVALID_MESSAGE          : Result := 'Invalid message';
    MAPI_E_TEXT_TOO_LARGE           : Result := 'Text too large.';
    MAPI_E_INVALID_SESSION          : Result := 'Invalid session';
    MAPI_E_TYPE_NOT_SUPPORTED       : Result := 'Type not supported';
    MAPI_E_AMBIGUOUS_RECIPIENT      : Result := 'Ambiguous recipient';
    MAPI_E_MESSAGE_IN_USE           : Result := 'Message in use';
    MAPI_E_NETWORK_FAILURE          : Result := 'Network failure';
    MAPI_E_INVALID_EDITFIELDS       : Result := 'Invalid edit fields';
    MAPI_E_INVALID_RECIPS           : Result := 'Invalid recipients';
    MAPI_E_NOT_SUPPORTED            : Result := 'Not supported';
  end;
end;

function SendEmail(const AHandle: THandle; const ASenderName, ASenderAddress,
  AReceiverAddress, ASubject, ABody: AnsiString;
  AAttachments: TStrings): Integer;
var
  MapiMessage: TMapiMessage;
  MsgSender, MsgTarget: TMapiRecipDesc;
  //MsgAttachments: IMapiAttachments;
  PReceiverName, PReceiverAddress, PSenderName, PSenderAddress, PSubject, PBody: PAnsiChar;
  I: Integer;
begin
  FillChar(MapiMessage, SizeOf(MapiMessage), 0);
  FillChar(MsgTarget, SizeOf(MsgTarget), 0);
  FillChar(MsgSender, SizeOf(MsgSender), 0);

  //Receiver
  PReceiverAddress := PAnsiChar('SMTP:' + AReceiverAddress);
  PReceiverName := PAnsiChar(AReceiverAddress);
  MsgTarget.lpszAddress := PReceiverAddress;
  MsgTarget.lpszName := PReceiverName;
  MsgTarget.ulRecipClass := MAPI_TO;
  MapiMessage.nRecipCount := 1;
  MapiMessage.lpRecips := @MsgTarget;

  //Sender
  PSenderAddress := PAnsiChar(ASenderAddress);
  PSenderName := PAnsiChar(ASenderName);
  MsgSender.lpszAddress := PSenderAddress;
  MsgSender.lpszName := PSenderName;
  MsgSender.ulRecipClass := MAPI_ORIG;
  MapiMessage.lpOriginator := @MsgSender;

  //Subject
  PSubject := PAnsiChar(ASubject);
  MapiMessage.lpszSubject := PSubject;

  //Body
  PBody := PAnsiChar(ABody);
  MapiMessage.lpszNoteText := PBody;

  //Attachments
  {for I := AAttachments.Count -1 downto 0 do
  begin
    if not FileExists(AAttachments[I]) then
      AAttachments.Delete(I);
  end;

  if AAttachments.Count > 0 then
  begin
    MsgAttachments := TMapiAttachments.Create(AAttachments.Count);
    for I := 0 to AAttachments.Count - 1 do
      MsgAttachments.Add(AAttachments[I]);

    MapiMessage.nFileCount := MsgAttachments.Count;
    MapiMessage.lpFiles := MsgAttachments.MapiFileDesc;
  end; }

  Result := Mapi.MapiSendMail(0, 0, MapiMessage, MAPI_DIALOG or MAPI_LOGON_UI or MAPI_NEW_SESSION, 0);

  if Result <> 0 then
    raise Exception.Create(MAPIErrorToStr(Result));
end;

procedure TForm2.Button1Click(Sender: TObject);
begin
  SendEmail(Handle, 'Experts Exchange', 'sender@EE.com', 'receiver@EE.com', 'Hello', 'Test Message', nil);
end;

end.

Open in new window

0
 

Author Comment

by:John86a
ID: 35211818
Hi ewan, that's almost it, in fact what you posted is useful, but not really what I need atm.
I just need to execute the executable file of the default client, no need to send mail. I can manually set to the outlook folder, but not every one uses outlook, you see the problem?
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 32

Accepted Solution

by:
ewangoya earned 250 total points
ID: 35211847
I see

Try using mailto

ShellExecute(0,'open','mailto: someone@home.org', nil, nil, 0);  //this should open an available mail client
0
 
LVL 24

Assisted Solution

by:jimyX
jimyX earned 250 total points
ID: 35212629
>   "I just need to execute the executable file of the default client"
If you want to open the default mail client with no address, no subject,...etc then:
uses ShellAPI;

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShellExecute(Handle, nil, pChar('mailto:'), nil,nil, SW_SHOWNORMAL);
end;

Open in new window


But if you want to add the Addresses, Subject and Body then:
uses ShellAPI;

procedure TForm1.Button1Click(Sender: TObject);
var
  MailTo, MailCC, Subject,Body:String;
begin
  MailTo := 'email1@Server.Domain';
  MailCC := 'email2@Server.Domain';
  Subject := 'Any subject';
  Body := 'Your message goes here';
  ShellExecute(Handle, nil, pChar('mailto:'+ MailTo+'&CC='+MailCC+'?subject='+Subject+'&body='+Body), nil,nil, SW_SHOWNORMAL);
end;

Open in new window


BTW, which antivirus you are using, or you customers are using? It might seem irrelevant, but it's very relevant.
0
 

Author Closing Comment

by:John86a
ID: 35212670
None of the solutions provided did what I wanted, which was to open the inbox. But it was close enough.
0
 
LVL 24

Expert Comment

by:jimyX
ID: 35212852
Why B Grade? It just was not clear. And you could have elaborate on your requirement.
Anyways here is the code:
uses ShellApi, StrUtils;

procedure TForm1.Button1Click(Sender: TObject);
var
  Reg : TRegistry;
  MailClient:String;
begin
  Reg:= TRegistry.Create;
  try
    Reg.RootKey:= HKEY_CLASSES_ROOT;
    Reg.OpenKey('\mailto\shell\open\command\', False);
    MailClient := Reg.ReadString('');
    MailClient:=copy(MailClient,2,posEx('"',MailClient,2)-2);
    Reg.CloseKey;
  finally
    Reg.Free;
  end;
  ShellExecute(Handle,'open',Pchar(MailClient),nil,nil,SW_SHOWNORMAL);
end;

Open in new window

0
 
LVL 24

Expert Comment

by:jimyX
ID: 35212861
To improve it more. Catch if there is no default mail client:
uses ShellApi, StrUtils;

procedure TForm1.Button1Click(Sender: TObject);
var
  Reg : TRegistry;
  MailClient:String;
begin
  Reg:= TRegistry.Create;
  try
    Reg.RootKey:= HKEY_CLASSES_ROOT;
    Reg.OpenKey('\mailto\shell\open\command\', False);
    MailClient := Reg.ReadString('');
    MailClient:=copy(MailClient,2,posEx('"',MailClient,2)-2);
    Reg.CloseKey;
  finally
    Reg.Free;
  end;
  if FileExists(MailClient) then
    ShellExecute(0,'open',Pchar(MailClient),nil,nil,SW_SHOWNORMAL)
  else
    showmessage('No default mail client.');
end;

Open in new window

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
firstChar challenge 13 110
Multiple image collision 13 69
Unique identifier on a terminal server (rdp) 4 46
Re-position sub-options beneath the TAB 7 77
In this tutorial I will show you how to use the Windows Speech API in Delphi. I will only cover basic functions such as text to speech and controlling the speed of the speech. SAPI Installation First you need to install the SAPI type library, th…
This article will show, step by step, how to integrate R code into a R Sweave document
This video teaches viewers about errors in exception handling.
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now