PhysiologyWeb Logo  Search
PhysiologyWeb Loading...

Delphi Code - Send Email with Attachments from Microsoft Outlook
Here is a simple Delphi procedure that uses Microsoft Outlook to programmatically send emails with attachments. The code works well whether or not Outlook is already open. However, please note that the code will not work if Outlook is closed, and your installed Outlook requires any form of authentication upon launching the program. The most relevant parts of the code are highlighted. Comments are included to explain the code. If you copy and paste the code into your program, be sure to change the form and procedure names to match your setup. For additional Excel automation solutions, see Microsoft Outlook Automation with Delphi.
procedure TForm1.UseDelphiToSendEmailWithAttachmentsFromMicrosoftOutlook(Sender: TObject);
var
OutlookApplication, OutlookMailItem: Variant;
begin
//be sure ComObj and Variants units are included in the "uses" clause

OutlookApplication := Null;
OutlookMailItem := Null;

try
//create Outlook OLE
OutlookApplication := CreateOleObject('Outlook.Application');
except
OutlookApplication := Null;
//add error/exception handling code as desired
end;

If VarIsNull(OutlookApplication) = False then
begin
try
//Create Outlook Mail Item
try
OutlookMailItem := OutlookApplication.CreateItem(0); //olMailItem = $00000000
//reference
//https://docs.microsoft.com/en-us/office/vba/api/outlook.mailitem
except
OutlookMailItem := Null;
//add error/exception handling code as desired
end;

If VarIsNull(OutlookMailItem) = False then
begin
OutlookMailItem.To := 'recipient@example.com'; //change the recipient email address
OutlookMailItem.Subject := 'Sending email with three attachments from Outlook programmatically';
OutlookMailItem.Body := 'This email, containing three attachments, is being sent from Outlook...';
OutlookMailItem.Attachments.Add('C:\PhysiologyWeb\delphi_code_examples\test.docx'); //change file name
OutlookMailItem.Attachments.Add('C:\PhysiologyWeb\delphi_code_examples\test.xlsx'); //change file name
OutlookMailItem.Attachments.Add('C:\PhysiologyWeb\delphi_code_examples\test.pptx'); //change file name
OutlookMailItem.Send;
//reference
//https://docs.microsoft.com/en-us/office/vba/api/Outlook.MailItem.Send(method)
end;
finally
OutlookMailItem := Unassigned;
OutlookApplication := Unassigned;
end;
end;
end;






Posted: Saturday, September 3, 2022