Send Plaintext Message

This application demonstrates how:

  1. How to logon to an EWS Session using a profile.
  2. How to create and send a plaintext email.
  3. How to add attachments to email messages.
  4. How to send email from a different address
  5. How to set a replyto recipient
  6. How to use the addressbook dialog to select recipients
  7. How to verify recipients

Example code:


procedure TFrmMain.actSendExecute(Sender: TObject);
var
  MsgStore: IRwEWSMsgStore;
  Folder: IRwEWSFolder;
  NewMessage: IRwEWSEMail;
  RecipTableTo, RecipTableCC: IRwEWSRecipients;
  i: Integer;
begin
  if Trim(edtTo.Text) = '' then
    raise Exception.Create('No recipients specified');

  if Trim(edtSubject.Text) = '' then
    if RwMsgBoxYesNo('There is no subject. Do you want to send the message anyway?') = mrNO then
      raise EAbort.Create('');

  // Check if all recpients are valid
  RecipTableTo := EWSSession.CreateRecipients;
  RecipTableTo.Add(edtTo.Text);
  if not EWSSession.ResolveNames(RecipTableTo, False) then
    raise EAbort.Create('One ore more recipients are invalid.');

  if edtCC.Text <> '' then
  begin
    RecipTableCC := EWSSession.CreateRecipients;
    RecipTableCC.Add(edtCC.Text);
    if not EWSSession.ResolveNames(RecipTableCC, False) then
      raise EAbort.Create('One ore more recipients are invalid.');
  end;

  if FSelectedAccountID = FDefaultAccountID then
    MsgStore := EWSSession.OpenDefaultMsgStore {create the new message in the drafts folder of the default messagestore}
  else
    MsgStore := EWSSession.OpenMsgStore(EWSSession.MsgStores.Names[FSelectedAccountID]); {use impersonation to open the store}

  Folder     := MsgStore.GetFolder(dfindrafts);
  NewMessage := Folder.CreateItem(tMessage) as IRwEWSEMail;

  NewMessage.ToRecipients.AsString := edtTo.Text;
  NewMessage.CcRecipients.AsString := edtCC.Text;
  NewMessage.Subject    := edtSubject.Text;
  NewMessage.BodyText   := msgBody.Lines.Text;

  // add the attachments
  for i := 0 to lvAttachments.Items.Count - 1 do
    NewMessage.Attachments.AddAttachment(TAttachment(lvAttachments.Items[i].Data).FileName);

  if Assigned(FOnBehalfOf) then
  begin
    NewMessage.From.Name         := FOnBehalfOf.Name; // to do: NewMessage.From.Assign(FOnBehalfOf) where FOnBehalfOf is of type IRwEWSRecipient
    NewMessage.From.EmailAddress := FOnBehalfOf.EmailAddress;
    NewMessage.From.RoutingType  := FOnBehalfOf.RoutingType;
    NewMessage.From.MailboxType  := FOnBehalfOf.MailboxType;
  end;

  // Set a custom header for potential tracking purpuses
  NewMessage.SubmitMessage(True);

  ClearMessage;
  RwMsgBoxInfo('The message is submitted.');
end;

Screenshot:


Back to Examples